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
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractGraphComputer.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphSystemMemory.java // public interface GraphSystemMemory extends GraphMemory { // // public void incrIteration(); // // public void setRuntime(final long runtime); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphSystemMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * AbstractGraphComputer provides the requisite fields/methods necessary for a GraphComputer. * This is a helper class that reduces the verbosity of a fully-written GraphComputer implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractGraphComputer implements GraphComputer { protected final Graph graph; protected VertexProgram vertexProgram; protected GraphSystemMemory graphMemory; protected VertexSystemMemory vertexMemory; protected Isolation isolation; public AbstractGraphComputer(final Graph graph, final VertexProgram vertexProgram, final GraphSystemMemory graphMemory, final VertexSystemMemory vertexMemory, final Isolation isolation) { this.graph = graph; this.vertexProgram = vertexProgram; this.graphMemory = graphMemory; this.vertexMemory = vertexMemory; this.isolation = isolation; } public VertexMemory getVertexMemory() { return this.vertexMemory; }
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphSystemMemory.java // public interface GraphSystemMemory extends GraphMemory { // // public void incrIteration(); // // public void setRuntime(final long runtime); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractGraphComputer.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphSystemMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * AbstractGraphComputer provides the requisite fields/methods necessary for a GraphComputer. * This is a helper class that reduces the verbosity of a fully-written GraphComputer implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractGraphComputer implements GraphComputer { protected final Graph graph; protected VertexProgram vertexProgram; protected GraphSystemMemory graphMemory; protected VertexSystemMemory vertexMemory; protected Isolation isolation; public AbstractGraphComputer(final Graph graph, final VertexProgram vertexProgram, final GraphSystemMemory graphMemory, final VertexSystemMemory vertexMemory, final Isolation isolation) { this.graph = graph; this.vertexProgram = vertexProgram; this.graphMemory = graphMemory; this.vertexMemory = vertexMemory; this.isolation = isolation; } public VertexMemory getVertexMemory() { return this.vertexMemory; }
public GraphMemory getGraphMemory() {
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // }
import com.tinkerpop.blueprints.Direction; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs; /** * AbstractVertexProgram provides the requisite fields/methods necessary for a VertexProgram. * This is a helper class that reduces the verbosity of a fully-written VertexProgram implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractVertexProgram implements VertexProgram { protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); public Map<String, KeyType> getComputeKeys() { return computeKeys; }
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java import com.tinkerpop.blueprints.Direction; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs; /** * AbstractVertexProgram provides the requisite fields/methods necessary for a VertexProgram. * This is a helper class that reduces the verbosity of a fully-written VertexProgram implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractVertexProgram implements VertexProgram { protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); public Map<String, KeyType> getComputeKeys() { return computeKeys; }
public void setup(final GraphMemory graphMemory) {
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // }
import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class DegreeRankProgram implements VertexProgram { protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; static { computeKeys.put(DEGREE, KeyType.CONSTANT); } protected DegreeRankProgram() { } public Map<String, KeyType> getComputeKeys() { return computeKeys; }
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class DegreeRankProgram implements VertexProgram { protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; static { computeKeys.put(DEGREE, KeyType.CONSTANT); } protected DegreeRankProgram() { } public Map<String, KeyType> getComputeKeys() { return computeKeys; }
public void setup(final GraphMemory graphMemory) {
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SimpleVertexMemoryTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SimpleVertexMemoryTest extends TestCase { public void testConstantVariables() { Graph graph = TinkerGraphFactory.createTinkerGraph();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SimpleVertexMemoryTest.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SimpleVertexMemoryTest extends TestCase { public void testConstantVariables() { Graph graph = TinkerGraphFactory.createTinkerGraph();
Map<String, VertexProgram.KeyType> keys = new HashMap<String, VertexProgram.KeyType>();
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SimpleVertexMemoryTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SimpleVertexMemoryTest extends TestCase { public void testConstantVariables() { Graph graph = TinkerGraphFactory.createTinkerGraph(); Map<String, VertexProgram.KeyType> keys = new HashMap<String, VertexProgram.KeyType>(); keys.put("name", VertexProgram.KeyType.CONSTANT); keys.put("age", VertexProgram.KeyType.VARIABLE);
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SimpleVertexMemoryTest.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import junit.framework.TestCase; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SimpleVertexMemoryTest extends TestCase { public void testConstantVariables() { Graph graph = TinkerGraphFactory.createTinkerGraph(); Map<String, VertexProgram.KeyType> keys = new HashMap<String, VertexProgram.KeyType>(); keys.put("name", VertexProgram.KeyType.CONSTANT); keys.put("age", VertexProgram.KeyType.VARIABLE);
SimpleVertexMemory memory = new SimpleVertexMemory(GraphComputer.Isolation.BSP);
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractVertexMemory.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // }
import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractVertexMemory implements VertexSystemMemory { protected Map<String, VertexProgram.KeyType> computeKeys;
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractVertexMemory.java import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractVertexMemory implements VertexSystemMemory { protected Map<String, VertexProgram.KeyType> computeKeys;
protected final GraphComputer.Isolation isolation;
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/ParallelGraphComputer.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // }
import com.google.common.base.Preconditions; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ParallelGraphComputer extends AbstractGraphComputer { int threads = Runtime.getRuntime().availableProcessors() - 1; int chunkSize = 1000;
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/ParallelGraphComputer.java import com.google.common.base.Preconditions; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ParallelGraphComputer extends AbstractGraphComputer { int threads = Runtime.getRuntime().availableProcessors() - 1; int chunkSize = 1000;
public ParallelGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) {
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/swarm/SwarmProgram.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // }
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.swarm; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SwarmProgram extends AbstractVertexProgram { private Map<Particle, Long> startParticles = new HashMap<Particle, Long>(); public static final String PARTICLES = SwarmProgram.class.getName() + ".particles"; protected SwarmProgram() { } private void setComputeKeys() { this.computeKeys.put(PARTICLES, KeyType.VARIABLE); for (final Particle particle : this.startParticles.keySet()) { this.computeKeys.putAll(particle.getComputeKeys()); } }
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/swarm/SwarmProgram.java import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.swarm; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SwarmProgram extends AbstractVertexProgram { private Map<Particle, Long> startParticles = new HashMap<Particle, Long>(); public static final String PARTICLES = SwarmProgram.class.getName() + ".particles"; protected SwarmProgram() { } private void setComputeKeys() { this.computeKeys.put(PARTICLES, KeyType.VARIABLE); for (final Particle particle : this.startParticles.keySet()) { this.computeKeys.putAll(particle.getComputeKeys()); } }
public void execute(final Vertex vertex, final GraphMemory graphMemory) {
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/WeightedPageRankProgram.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // }
import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.EdgeHelper; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import com.tinkerpop.pipes.PipeFunction; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class WeightedPageRankProgram extends AbstractVertexProgram { private VertexQueryBuilder outgoingQuery = new VertexQueryBuilder().direction(Direction.OUT); private VertexQueryBuilder incomingQuery = new VertexQueryBuilder().direction(Direction.IN); private PipeFunction<Edge, Double> edgeWeightFunction = new PipeFunction<Edge, Double>() { @Override public Double compute(Edge argument) { return 1.0d; } }; public static final String PAGE_RANK = WeightedPageRankProgram.class.getName() + ".pageRank"; public static final String EDGE_WEIGHT_SUM = WeightedPageRankProgram.class.getName() + "edgeWeightSum"; private double vertexCountAsDouble = 1; private double alpha = 0.85d; private int totalIterations = 30; protected WeightedPageRankProgram() { computeKeys.put(PAGE_RANK, KeyType.VARIABLE); computeKeys.put(EDGE_WEIGHT_SUM, KeyType.CONSTANT); }
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/WeightedPageRankProgram.java import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.EdgeHelper; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import com.tinkerpop.pipes.PipeFunction; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class WeightedPageRankProgram extends AbstractVertexProgram { private VertexQueryBuilder outgoingQuery = new VertexQueryBuilder().direction(Direction.OUT); private VertexQueryBuilder incomingQuery = new VertexQueryBuilder().direction(Direction.IN); private PipeFunction<Edge, Double> edgeWeightFunction = new PipeFunction<Edge, Double>() { @Override public Double compute(Edge argument) { return 1.0d; } }; public static final String PAGE_RANK = WeightedPageRankProgram.class.getName() + ".pageRank"; public static final String EDGE_WEIGHT_SUM = WeightedPageRankProgram.class.getName() + "edgeWeightSum"; private double vertexCountAsDouble = 1; private double alpha = 0.85d; private int totalIterations = 30; protected WeightedPageRankProgram() { computeKeys.put(PAGE_RANK, KeyType.VARIABLE); computeKeys.put(EDGE_WEIGHT_SUM, KeyType.CONSTANT); }
public void setup(final GraphMemory graphMemory) {
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/ParallelGraphComputerTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ParallelGraphComputerTest extends TestCase { public void testBasicParallelComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph(); for (int workers = 1; workers < 25; workers++) { for (int threads = 1; threads < 25; threads++) {
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/ParallelGraphComputerTest.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ParallelGraphComputerTest extends TestCase { public void testBasicParallelComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph(); for (int workers = 1; workers < 25; workers++) { for (int threads = 1; threads < 25; threads++) {
DegreeRankProgram program = DegreeRankProgram.create().build();
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/ParallelGraphComputerTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ParallelGraphComputerTest extends TestCase { public void testBasicParallelComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph(); for (int workers = 1; workers < 25; workers++) { for (int threads = 1; threads < 25; threads++) { DegreeRankProgram program = DegreeRankProgram.create().build();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/ParallelGraphComputerTest.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ParallelGraphComputerTest extends TestCase { public void testBasicParallelComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph(); for (int workers = 1; workers < 25; workers++) { for (int threads = 1; threads < 25; threads++) { DegreeRankProgram program = DegreeRankProgram.create().build();
ParallelGraphComputer computer = new ParallelGraphComputer(graph, program, GraphComputer.Isolation.BSP);
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/ParallelGraphComputerTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ParallelGraphComputerTest extends TestCase { public void testBasicParallelComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph(); for (int workers = 1; workers < 25; workers++) { for (int threads = 1; threads < 25; threads++) { DegreeRankProgram program = DegreeRankProgram.create().build(); ParallelGraphComputer computer = new ParallelGraphComputer(graph, program, GraphComputer.Isolation.BSP); computer.execute();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/ParallelGraphComputerTest.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ParallelGraphComputerTest extends TestCase { public void testBasicParallelComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph(); for (int workers = 1; workers < 25; workers++) { for (int threads = 1; threads < 25; threads++) { DegreeRankProgram program = DegreeRankProgram.create().build(); ParallelGraphComputer computer = new ParallelGraphComputer(graph, program, GraphComputer.Isolation.BSP); computer.execute();
VertexMemory results = computer.getVertexMemory();
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/clustering/PeerPressureProgram.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // }
import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.clustering; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PeerPressureProgram extends AbstractVertexProgram { private VertexQueryBuilder outgoingQuery = new VertexQueryBuilder().direction(Direction.OUT); private VertexQueryBuilder incomingQuery = new VertexQueryBuilder().direction(Direction.IN); public static final String CLUSTER = PeerPressureProgram.class.getName() + ".cluster"; public static final String EDGE_COUNT = PeerPressureProgram.class.getName() + ".edgeCount"; private int totalIterations = 30; protected PeerPressureProgram() { computeKeys.put(CLUSTER, KeyType.VARIABLE); computeKeys.put(EDGE_COUNT, KeyType.CONSTANT); }
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/clustering/PeerPressureProgram.java import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.clustering; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PeerPressureProgram extends AbstractVertexProgram { private VertexQueryBuilder outgoingQuery = new VertexQueryBuilder().direction(Direction.OUT); private VertexQueryBuilder incomingQuery = new VertexQueryBuilder().direction(Direction.IN); public static final String CLUSTER = PeerPressureProgram.class.getName() + ".cluster"; public static final String EDGE_COUNT = PeerPressureProgram.class.getName() + ".edgeCount"; private int totalIterations = 30; protected PeerPressureProgram() { computeKeys.put(CLUSTER, KeyType.VARIABLE); computeKeys.put(EDGE_COUNT, KeyType.CONSTANT); }
public void execute(final Vertex vertex, final GraphMemory globalMemory) {
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputerTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SerialGraphComputerTest extends TestCase { public void testBasicSerialComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputerTest.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SerialGraphComputerTest extends TestCase { public void testBasicSerialComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph();
DegreeRankProgram program = DegreeRankProgram.create().build();
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputerTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SerialGraphComputerTest extends TestCase { public void testBasicSerialComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph(); DegreeRankProgram program = DegreeRankProgram.create().build();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputerTest.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SerialGraphComputerTest extends TestCase { public void testBasicSerialComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph(); DegreeRankProgram program = DegreeRankProgram.create().build();
SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP);
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputerTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SerialGraphComputerTest extends TestCase { public void testBasicSerialComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph(); DegreeRankProgram program = DegreeRankProgram.create().build(); SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP); computer.execute();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/DegreeRankProgram.java // public class DegreeRankProgram implements VertexProgram { // // protected VertexQueryBuilder degreeQuery = new VertexQueryBuilder().direction(Direction.IN); // private static final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public static final String DEGREE = DegreeRankProgram.class.getName() + ".degree"; // // static { // computeKeys.put(DEGREE, KeyType.CONSTANT); // } // // // protected DegreeRankProgram() { // // } // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public void execute(final Vertex vertex, final GraphMemory graphMemory) { // long degree = degreeQuery.build(vertex).count(); // vertex.setProperty(DEGREE, degree); // } // // public boolean terminate(final GraphMemory graphMemory) { // return true; // } // // public static Builder create() { // return new Builder(); // } // // ////////////////////////////// // // public static class Builder { // // private final DegreeRankProgram vertexProgram = new DegreeRankProgram(); // // public Builder degreeQuery(final VertexQueryBuilder degreeQuery) { // this.vertexProgram.degreeQuery = degreeQuery; // return this; // } // // public DegreeRankProgram build() { // return this.vertexProgram; // } // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputerTest.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking.DegreeRankProgram; import junit.framework.TestCase; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SerialGraphComputerTest extends TestCase { public void testBasicSerialComputer() { Graph graph = TinkerGraphFactory.createTinkerGraph(); DegreeRankProgram program = DegreeRankProgram.create().build(); SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP); computer.execute();
VertexMemory results = computer.getVertexMemory();
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/clustering/PeerPressureProgramTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // }
import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.clustering; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PeerPressureProgramTest extends TestCase { public void testProgramOnTinkerGraph() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PeerPressureProgram program = PeerPressureProgram.create().build();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/clustering/PeerPressureProgramTest.java import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.clustering; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PeerPressureProgramTest extends TestCase { public void testProgramOnTinkerGraph() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PeerPressureProgram program = PeerPressureProgram.create().build();
SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP);
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/clustering/PeerPressureProgramTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // }
import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.clustering; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PeerPressureProgramTest extends TestCase { public void testProgramOnTinkerGraph() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PeerPressureProgram program = PeerPressureProgram.create().build();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/clustering/PeerPressureProgramTest.java import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.clustering; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PeerPressureProgramTest extends TestCase { public void testProgramOnTinkerGraph() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PeerPressureProgram program = PeerPressureProgram.create().build();
SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP);
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/clustering/PeerPressureProgramTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // }
import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.clustering; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PeerPressureProgramTest extends TestCase { public void testProgramOnTinkerGraph() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PeerPressureProgram program = PeerPressureProgram.create().build(); SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP); computer.execute();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/clustering/PeerPressureProgramTest.java import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.clustering; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PeerPressureProgramTest extends TestCase { public void testProgramOnTinkerGraph() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PeerPressureProgram program = PeerPressureProgram.create().build(); SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP); computer.execute();
VertexMemory results = computer.getVertexMemory();
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/PageRankProgram.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // }
import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * A VertexProgram for the popular PageRank algorithm. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PageRankProgram extends AbstractVertexProgram { private VertexQueryBuilder outgoingQuery = new VertexQueryBuilder().direction(Direction.OUT); private VertexQueryBuilder incomingQuery = new VertexQueryBuilder().direction(Direction.IN); public static final String PAGE_RANK = PageRankProgram.class.getName() + ".pageRank"; public static final String EDGE_COUNT = PageRankProgram.class.getName() + ".edgeCount"; private double vertexCountAsDouble = 1; private double alpha = 0.85d; private int totalIterations = 30; protected PageRankProgram() { computeKeys.put(PAGE_RANK, KeyType.VARIABLE); computeKeys.put(EDGE_COUNT, KeyType.CONSTANT); }
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/PageRankProgram.java import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * A VertexProgram for the popular PageRank algorithm. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PageRankProgram extends AbstractVertexProgram { private VertexQueryBuilder outgoingQuery = new VertexQueryBuilder().direction(Direction.OUT); private VertexQueryBuilder incomingQuery = new VertexQueryBuilder().direction(Direction.IN); public static final String PAGE_RANK = PageRankProgram.class.getName() + ".pageRank"; public static final String EDGE_COUNT = PageRankProgram.class.getName() + ".edgeCount"; private double vertexCountAsDouble = 1; private double alpha = 0.85d; private int totalIterations = 30; protected PageRankProgram() { computeKeys.put(PAGE_RANK, KeyType.VARIABLE); computeKeys.put(EDGE_COUNT, KeyType.CONSTANT); }
public void setup(final GraphMemory graphMemory) {
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/swarm/AbstractProgramParticle.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // }
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.swarm; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class AbstractProgramParticle implements Particle { protected final VertexProgram program; public AbstractProgramParticle(final VertexProgram program) { this.program = program; } public Map<String, VertexProgram.KeyType> getComputeKeys() { return this.program.getComputeKeys(); }
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/swarm/AbstractProgramParticle.java import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.swarm; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class AbstractProgramParticle implements Particle { protected final VertexProgram program; public AbstractProgramParticle(final VertexProgram program) { this.program = program; } public Map<String, VertexProgram.KeyType> getComputeKeys() { return this.program.getComputeKeys(); }
public void execute(Vertex vertex, GraphMemory graphMemory, Long count, Map<Particle, Long> newParticles) {
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/paths/TraversalProgram.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // }
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.ArrayList; import java.util.List;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.paths; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class TraversalProgram extends AbstractVertexProgram { private int totalIterations = 30;
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/paths/TraversalProgram.java import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.ArrayList; import java.util.List; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.paths; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class TraversalProgram extends AbstractVertexProgram { private int totalIterations = 30;
private final List<VertexQueryBuilder> queries = new ArrayList<VertexQueryBuilder>();
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/paths/TraversalProgram.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // }
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.ArrayList; import java.util.List;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.paths; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class TraversalProgram extends AbstractVertexProgram { private int totalIterations = 30; private final List<VertexQueryBuilder> queries = new ArrayList<VertexQueryBuilder>(); public static final String COUNTS = TraversalProgram.class.getName() + ".counts"; protected TraversalProgram() { computeKeys.put(COUNTS, KeyType.VARIABLE); }
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/paths/TraversalProgram.java import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.ArrayList; import java.util.List; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.paths; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class TraversalProgram extends AbstractVertexProgram { private int totalIterations = 30; private final List<VertexQueryBuilder> queries = new ArrayList<VertexQueryBuilder>(); public static final String COUNTS = TraversalProgram.class.getName() + ".counts"; protected TraversalProgram() { computeKeys.put(COUNTS, KeyType.VARIABLE); }
public void setup(final GraphMemory graphMemory) {
wjaneal/liastem
SampleMultiFunction/src/org/usfirst/frc/team6162/robot/Robot.java
// Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java // public class ExampleCommand extends Command { // // public ExampleCommand() { // // Use requires() here to declare subsystem dependencies // requires(Robot.exampleSubsystem); // } // // // Called just before this Command runs the first time // protected void initialize() { // } // // // Called repeatedly when this Command is scheduled to run // protected void execute() { // } // // // Make this return true when this Command no longer needs to run execute() // protected boolean isFinished() { // return false; // } // // // Called once after isFinished returns true // protected void end() { // } // // // Called when another command which requires one or more of the same // // subsystems is scheduled to run // protected void interrupted() { // } // } // // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/subsystems/ExampleSubsystem.java // public class ExampleSubsystem extends Subsystem { // // Put methods for controlling this subsystem // // here. Call these from Commands. // // public void initDefaultCommand() { // // Set the default command for a subsystem here. // // setDefaultCommand(new MySpecialCommand()); // } // }
import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc.team6162.robot.commands.ExampleCommand; import org.usfirst.frc.team6162.robot.subsystems.ExampleSubsystem;
package org.usfirst.frc.team6162.robot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem(); public static OI oi; Command autonomousCommand; SendableChooser<Command> chooser = new SendableChooser<>(); /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { oi = new OI();
// Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java // public class ExampleCommand extends Command { // // public ExampleCommand() { // // Use requires() here to declare subsystem dependencies // requires(Robot.exampleSubsystem); // } // // // Called just before this Command runs the first time // protected void initialize() { // } // // // Called repeatedly when this Command is scheduled to run // protected void execute() { // } // // // Make this return true when this Command no longer needs to run execute() // protected boolean isFinished() { // return false; // } // // // Called once after isFinished returns true // protected void end() { // } // // // Called when another command which requires one or more of the same // // subsystems is scheduled to run // protected void interrupted() { // } // } // // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/subsystems/ExampleSubsystem.java // public class ExampleSubsystem extends Subsystem { // // Put methods for controlling this subsystem // // here. Call these from Commands. // // public void initDefaultCommand() { // // Set the default command for a subsystem here. // // setDefaultCommand(new MySpecialCommand()); // } // } // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/Robot.java import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc.team6162.robot.commands.ExampleCommand; import org.usfirst.frc.team6162.robot.subsystems.ExampleSubsystem; package org.usfirst.frc.team6162.robot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem(); public static OI oi; Command autonomousCommand; SendableChooser<Command> chooser = new SendableChooser<>(); /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { oi = new OI();
chooser.addDefault("Default Auto", new ExampleCommand());
wjaneal/liastem
java/6162_3739/src/org/usfirst/frc/team6162/robot/Robot.java
// Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java // public class ExampleCommand extends Command { // // public ExampleCommand() { // // Use requires() here to declare subsystem dependencies // requires(Robot.exampleSubsystem); // } // // // Called just before this Command runs the first time // protected void initialize() { // } // // // Called repeatedly when this Command is scheduled to run // protected void execute() { // } // // // Make this return true when this Command no longer needs to run execute() // protected boolean isFinished() { // return false; // } // // // Called once after isFinished returns true // protected void end() { // } // // // Called when another command which requires one or more of the same // // subsystems is scheduled to run // protected void interrupted() { // } // } // // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/subsystems/ExampleSubsystem.java // public class ExampleSubsystem extends Subsystem { // // Put methods for controlling this subsystem // // here. Call these from Commands. // // public void initDefaultCommand() { // // Set the default command for a subsystem here. // // setDefaultCommand(new MySpecialCommand()); // } // }
import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import org.usfirst.frc.team6162.robot.commands.ExampleCommand; import org.usfirst.frc.team6162.robot.subsystems.ExampleSubsystem; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
package org.usfirst.frc.team6162.robot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem(); public static OI oi; Command autonomousCommand; SendableChooser chooser; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { oi = new OI(); chooser = new SendableChooser();
// Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java // public class ExampleCommand extends Command { // // public ExampleCommand() { // // Use requires() here to declare subsystem dependencies // requires(Robot.exampleSubsystem); // } // // // Called just before this Command runs the first time // protected void initialize() { // } // // // Called repeatedly when this Command is scheduled to run // protected void execute() { // } // // // Make this return true when this Command no longer needs to run execute() // protected boolean isFinished() { // return false; // } // // // Called once after isFinished returns true // protected void end() { // } // // // Called when another command which requires one or more of the same // // subsystems is scheduled to run // protected void interrupted() { // } // } // // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/subsystems/ExampleSubsystem.java // public class ExampleSubsystem extends Subsystem { // // Put methods for controlling this subsystem // // here. Call these from Commands. // // public void initDefaultCommand() { // // Set the default command for a subsystem here. // // setDefaultCommand(new MySpecialCommand()); // } // } // Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/Robot.java import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import org.usfirst.frc.team6162.robot.commands.ExampleCommand; import org.usfirst.frc.team6162.robot.subsystems.ExampleSubsystem; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; package org.usfirst.frc.team6162.robot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem(); public static OI oi; Command autonomousCommand; SendableChooser chooser; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { oi = new OI(); chooser = new SendableChooser();
chooser.addDefault("Default Auto", new ExampleCommand());
wjaneal/liastem
FRCGYRO/src/org/usfirst/frc/team6162/robot/Robot.java
// Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java // public class ExampleCommand extends Command { // // public ExampleCommand() { // // Use requires() here to declare subsystem dependencies // requires(Robot.exampleSubsystem); // } // // // Called just before this Command runs the first time // protected void initialize() { // } // // // Called repeatedly when this Command is scheduled to run // protected void execute() { // } // // // Make this return true when this Command no longer needs to run execute() // protected boolean isFinished() { // return false; // } // // // Called once after isFinished returns true // protected void end() { // } // // // Called when another command which requires one or more of the same // // subsystems is scheduled to run // protected void interrupted() { // } // } // // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/subsystems/ExampleSubsystem.java // public class ExampleSubsystem extends Subsystem { // // Put methods for controlling this subsystem // // here. Call these from Commands. // // public void initDefaultCommand() { // // Set the default command for a subsystem here. // // setDefaultCommand(new MySpecialCommand()); // } // }
import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc.team6162.robot.commands.ExampleCommand; import org.usfirst.frc.team6162.robot.subsystems.ExampleSubsystem;
package org.usfirst.frc.team6162.robot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem(); public static OI oi; Command autonomousCommand; SendableChooser<Command> chooser = new SendableChooser<>(); /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { oi = new OI();
// Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java // public class ExampleCommand extends Command { // // public ExampleCommand() { // // Use requires() here to declare subsystem dependencies // requires(Robot.exampleSubsystem); // } // // // Called just before this Command runs the first time // protected void initialize() { // } // // // Called repeatedly when this Command is scheduled to run // protected void execute() { // } // // // Make this return true when this Command no longer needs to run execute() // protected boolean isFinished() { // return false; // } // // // Called once after isFinished returns true // protected void end() { // } // // // Called when another command which requires one or more of the same // // subsystems is scheduled to run // protected void interrupted() { // } // } // // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/subsystems/ExampleSubsystem.java // public class ExampleSubsystem extends Subsystem { // // Put methods for controlling this subsystem // // here. Call these from Commands. // // public void initDefaultCommand() { // // Set the default command for a subsystem here. // // setDefaultCommand(new MySpecialCommand()); // } // } // Path: FRCGYRO/src/org/usfirst/frc/team6162/robot/Robot.java import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc.team6162.robot.commands.ExampleCommand; import org.usfirst.frc.team6162.robot.subsystems.ExampleSubsystem; package org.usfirst.frc.team6162.robot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem(); public static OI oi; Command autonomousCommand; SendableChooser<Command> chooser = new SendableChooser<>(); /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { oi = new OI();
chooser.addDefault("Default Auto", new ExampleCommand());
wjaneal/liastem
SampleFRC/src/org/usfirst/frc/team6162/robot/Robot.java
// Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java // public class ExampleCommand extends Command { // // public ExampleCommand() { // // Use requires() here to declare subsystem dependencies // requires(Robot.exampleSubsystem); // } // // // Called just before this Command runs the first time // protected void initialize() { // } // // // Called repeatedly when this Command is scheduled to run // protected void execute() { // } // // // Make this return true when this Command no longer needs to run execute() // protected boolean isFinished() { // return false; // } // // // Called once after isFinished returns true // protected void end() { // } // // // Called when another command which requires one or more of the same // // subsystems is scheduled to run // protected void interrupted() { // } // } // // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/subsystems/ExampleSubsystem.java // public class ExampleSubsystem extends Subsystem { // // Put methods for controlling this subsystem // // here. Call these from Commands. // // public void initDefaultCommand() { // // Set the default command for a subsystem here. // // setDefaultCommand(new MySpecialCommand()); // } // }
import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.ADXRS450_Gyro; import org.usfirst.frc.team6162.robot.commands.ExampleCommand; import org.usfirst.frc.team6162.robot.subsystems.ExampleSubsystem;
package org.usfirst.frc.team6162.robot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem(); public static OI oi; ADXRS450_Gyro gyro = new ADXRS450_Gyro(); Command autonomousCommand; SendableChooser<Command> chooser = new SendableChooser<>(); /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { oi = new OI();
// Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java // public class ExampleCommand extends Command { // // public ExampleCommand() { // // Use requires() here to declare subsystem dependencies // requires(Robot.exampleSubsystem); // } // // // Called just before this Command runs the first time // protected void initialize() { // } // // // Called repeatedly when this Command is scheduled to run // protected void execute() { // } // // // Make this return true when this Command no longer needs to run execute() // protected boolean isFinished() { // return false; // } // // // Called once after isFinished returns true // protected void end() { // } // // // Called when another command which requires one or more of the same // // subsystems is scheduled to run // protected void interrupted() { // } // } // // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/subsystems/ExampleSubsystem.java // public class ExampleSubsystem extends Subsystem { // // Put methods for controlling this subsystem // // here. Call these from Commands. // // public void initDefaultCommand() { // // Set the default command for a subsystem here. // // setDefaultCommand(new MySpecialCommand()); // } // } // Path: SampleFRC/src/org/usfirst/frc/team6162/robot/Robot.java import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.ADXRS450_Gyro; import org.usfirst.frc.team6162.robot.commands.ExampleCommand; import org.usfirst.frc.team6162.robot.subsystems.ExampleSubsystem; package org.usfirst.frc.team6162.robot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem(); public static OI oi; ADXRS450_Gyro gyro = new ADXRS450_Gyro(); Command autonomousCommand; SendableChooser<Command> chooser = new SendableChooser<>(); /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { oi = new OI();
chooser.addDefault("Default Auto", new ExampleCommand());
wjaneal/liastem
java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java
// Path: SampleAutonomous/src/org/usfirst/frc/team6162/robot/Robot.java // public class Robot extends SampleRobot { // RobotDrive myRobot = new RobotDrive(0, 1,2,3); // Joystick stick = new Joystick(0); // final String defaultAuto = "Default"; // final String customAuto = "My Auto"; // SendableChooser<String> chooser = new SendableChooser<>(); // // public Robot() { // myRobot.setExpiration(0.1); // } // // @Override // public void robotInit() { // chooser.addDefault("Default Auto", defaultAuto); // chooser.addObject("My Auto", customAuto); // SmartDashboard.putData("Auto modes", chooser); // } // // /** // * This autonomous (along with the chooser code above) shows how to select // * between different autonomous modes using the dashboard. The sendable // * chooser code works with the Java SmartDashboard. If you prefer the // * LabVIEW Dashboard, remove all of the chooser code and uncomment the // * getString line to get the auto name from the text box below the Gyro // * // * You can add additional auto modes by adding additional comparisons to the // * if-else structure below with additional strings. If using the // * SendableChooser make sure to add them to the chooser code above as well. // */ // @Override // public void autonomous() { // String autoSelected = chooser.getSelected(); // // String autoSelected = SmartDashboard.getString("Auto Selector", // // defaultAuto); // System.out.println("Auto selected: " + autoSelected); // // switch (autoSelected) { // case customAuto: // myRobot.setSafetyEnabled(false); // myRobot.drive(0.1, 0.1); // spin at half speed // Timer.delay(2.0); // for 2 seconds // myRobot.drive(0.2, -0.2); // stop robot // break; // case defaultAuto: // default: // myRobot.setSafetyEnabled(false); // myRobot.drive(0.1, 0.1); // drive forwards half speed // Timer.delay(2.0); // for 2 seconds // myRobot.drive(0.2, -0.2); // stop robot // break; // } // } // // /** // * Runs the motors with arcade steering. // */ // @Override // public void operatorControl() { // myRobot.setSafetyEnabled(true); // while (isOperatorControl() && isEnabled()) { // myRobot.arcadeDrive(stick); // drive with arcade style (use right // // stick) // Timer.delay(0.005); // wait for a motor update time // } // } // // /** // * Runs during test mode // */ // @Override // public void test() { // } // }
import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc.team6162.robot.Robot;
package org.usfirst.frc.team6162.robot.commands; /** * */ public class ExampleCommand extends Command { public ExampleCommand() { // Use requires() here to declare subsystem dependencies
// Path: SampleAutonomous/src/org/usfirst/frc/team6162/robot/Robot.java // public class Robot extends SampleRobot { // RobotDrive myRobot = new RobotDrive(0, 1,2,3); // Joystick stick = new Joystick(0); // final String defaultAuto = "Default"; // final String customAuto = "My Auto"; // SendableChooser<String> chooser = new SendableChooser<>(); // // public Robot() { // myRobot.setExpiration(0.1); // } // // @Override // public void robotInit() { // chooser.addDefault("Default Auto", defaultAuto); // chooser.addObject("My Auto", customAuto); // SmartDashboard.putData("Auto modes", chooser); // } // // /** // * This autonomous (along with the chooser code above) shows how to select // * between different autonomous modes using the dashboard. The sendable // * chooser code works with the Java SmartDashboard. If you prefer the // * LabVIEW Dashboard, remove all of the chooser code and uncomment the // * getString line to get the auto name from the text box below the Gyro // * // * You can add additional auto modes by adding additional comparisons to the // * if-else structure below with additional strings. If using the // * SendableChooser make sure to add them to the chooser code above as well. // */ // @Override // public void autonomous() { // String autoSelected = chooser.getSelected(); // // String autoSelected = SmartDashboard.getString("Auto Selector", // // defaultAuto); // System.out.println("Auto selected: " + autoSelected); // // switch (autoSelected) { // case customAuto: // myRobot.setSafetyEnabled(false); // myRobot.drive(0.1, 0.1); // spin at half speed // Timer.delay(2.0); // for 2 seconds // myRobot.drive(0.2, -0.2); // stop robot // break; // case defaultAuto: // default: // myRobot.setSafetyEnabled(false); // myRobot.drive(0.1, 0.1); // drive forwards half speed // Timer.delay(2.0); // for 2 seconds // myRobot.drive(0.2, -0.2); // stop robot // break; // } // } // // /** // * Runs the motors with arcade steering. // */ // @Override // public void operatorControl() { // myRobot.setSafetyEnabled(true); // while (isOperatorControl() && isEnabled()) { // myRobot.arcadeDrive(stick); // drive with arcade style (use right // // stick) // Timer.delay(0.005); // wait for a motor update time // } // } // // /** // * Runs during test mode // */ // @Override // public void test() { // } // } // Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc.team6162.robot.Robot; package org.usfirst.frc.team6162.robot.commands; /** * */ public class ExampleCommand extends Command { public ExampleCommand() { // Use requires() here to declare subsystem dependencies
requires(Robot.exampleSubsystem);
wjaneal/liastem
SampleMultiFunction/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java
// Path: SampleAutonomous/src/org/usfirst/frc/team6162/robot/Robot.java // public class Robot extends SampleRobot { // RobotDrive myRobot = new RobotDrive(0, 1,2,3); // Joystick stick = new Joystick(0); // final String defaultAuto = "Default"; // final String customAuto = "My Auto"; // SendableChooser<String> chooser = new SendableChooser<>(); // // public Robot() { // myRobot.setExpiration(0.1); // } // // @Override // public void robotInit() { // chooser.addDefault("Default Auto", defaultAuto); // chooser.addObject("My Auto", customAuto); // SmartDashboard.putData("Auto modes", chooser); // } // // /** // * This autonomous (along with the chooser code above) shows how to select // * between different autonomous modes using the dashboard. The sendable // * chooser code works with the Java SmartDashboard. If you prefer the // * LabVIEW Dashboard, remove all of the chooser code and uncomment the // * getString line to get the auto name from the text box below the Gyro // * // * You can add additional auto modes by adding additional comparisons to the // * if-else structure below with additional strings. If using the // * SendableChooser make sure to add them to the chooser code above as well. // */ // @Override // public void autonomous() { // String autoSelected = chooser.getSelected(); // // String autoSelected = SmartDashboard.getString("Auto Selector", // // defaultAuto); // System.out.println("Auto selected: " + autoSelected); // // switch (autoSelected) { // case customAuto: // myRobot.setSafetyEnabled(false); // myRobot.drive(0.1, 0.1); // spin at half speed // Timer.delay(2.0); // for 2 seconds // myRobot.drive(0.2, -0.2); // stop robot // break; // case defaultAuto: // default: // myRobot.setSafetyEnabled(false); // myRobot.drive(0.1, 0.1); // drive forwards half speed // Timer.delay(2.0); // for 2 seconds // myRobot.drive(0.2, -0.2); // stop robot // break; // } // } // // /** // * Runs the motors with arcade steering. // */ // @Override // public void operatorControl() { // myRobot.setSafetyEnabled(true); // while (isOperatorControl() && isEnabled()) { // myRobot.arcadeDrive(stick); // drive with arcade style (use right // // stick) // Timer.delay(0.005); // wait for a motor update time // } // } // // /** // * Runs during test mode // */ // @Override // public void test() { // } // }
import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc.team6162.robot.Robot;
package org.usfirst.frc.team6162.robot.commands; /** * */ public class ExampleCommand extends Command { public ExampleCommand() { // Use requires() here to declare subsystem dependencies
// Path: SampleAutonomous/src/org/usfirst/frc/team6162/robot/Robot.java // public class Robot extends SampleRobot { // RobotDrive myRobot = new RobotDrive(0, 1,2,3); // Joystick stick = new Joystick(0); // final String defaultAuto = "Default"; // final String customAuto = "My Auto"; // SendableChooser<String> chooser = new SendableChooser<>(); // // public Robot() { // myRobot.setExpiration(0.1); // } // // @Override // public void robotInit() { // chooser.addDefault("Default Auto", defaultAuto); // chooser.addObject("My Auto", customAuto); // SmartDashboard.putData("Auto modes", chooser); // } // // /** // * This autonomous (along with the chooser code above) shows how to select // * between different autonomous modes using the dashboard. The sendable // * chooser code works with the Java SmartDashboard. If you prefer the // * LabVIEW Dashboard, remove all of the chooser code and uncomment the // * getString line to get the auto name from the text box below the Gyro // * // * You can add additional auto modes by adding additional comparisons to the // * if-else structure below with additional strings. If using the // * SendableChooser make sure to add them to the chooser code above as well. // */ // @Override // public void autonomous() { // String autoSelected = chooser.getSelected(); // // String autoSelected = SmartDashboard.getString("Auto Selector", // // defaultAuto); // System.out.println("Auto selected: " + autoSelected); // // switch (autoSelected) { // case customAuto: // myRobot.setSafetyEnabled(false); // myRobot.drive(0.1, 0.1); // spin at half speed // Timer.delay(2.0); // for 2 seconds // myRobot.drive(0.2, -0.2); // stop robot // break; // case defaultAuto: // default: // myRobot.setSafetyEnabled(false); // myRobot.drive(0.1, 0.1); // drive forwards half speed // Timer.delay(2.0); // for 2 seconds // myRobot.drive(0.2, -0.2); // stop robot // break; // } // } // // /** // * Runs the motors with arcade steering. // */ // @Override // public void operatorControl() { // myRobot.setSafetyEnabled(true); // while (isOperatorControl() && isEnabled()) { // myRobot.arcadeDrive(stick); // drive with arcade style (use right // // stick) // Timer.delay(0.005); // wait for a motor update time // } // } // // /** // * Runs during test mode // */ // @Override // public void test() { // } // } // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc.team6162.robot.Robot; package org.usfirst.frc.team6162.robot.commands; /** * */ public class ExampleCommand extends Command { public ExampleCommand() { // Use requires() here to declare subsystem dependencies
requires(Robot.exampleSubsystem);
wjaneal/liastem
37396162/src/org/usfirst/frc/team6162/robot/Robot.java
// Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java // public class ExampleCommand extends Command { // // public ExampleCommand() { // // Use requires() here to declare subsystem dependencies // requires(Robot.exampleSubsystem); // } // // // Called just before this Command runs the first time // protected void initialize() { // } // // // Called repeatedly when this Command is scheduled to run // protected void execute() { // } // // // Make this return true when this Command no longer needs to run execute() // protected boolean isFinished() { // return false; // } // // // Called once after isFinished returns true // protected void end() { // } // // // Called when another command which requires one or more of the same // // subsystems is scheduled to run // protected void interrupted() { // } // } // // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/subsystems/ExampleSubsystem.java // public class ExampleSubsystem extends Subsystem { // // Put methods for controlling this subsystem // // here. Call these from Commands. // // public void initDefaultCommand() { // // Set the default command for a subsystem here. // // setDefaultCommand(new MySpecialCommand()); // } // } // // Path: 37396162/src/org/usfirst/frc/team6162/robot/subsystems/Pneumatics.java // public class Pneumatics extends Subsystem { // // // Put methods for controlling this subsystem // // here. Call these from Commands. // static DoubleSolenoid testDS; // public void initDefaultCommand() { // // Set the default command for a subsystem here. // //setDefaultCommand(new MySpecialCommand()); // testDS=new DoubleSolenoid(1,2); // testDS.set(DoubleSolenoid.Value.kOff); // LiveWindow.addActuator("Pneumatics", "testDS", testDS); // // } // // public void setDS(boolean on) { // if(on) { // testDS.set(DoubleSolenoid.Value.kForward); // } // else{ // testDS.set(DoubleSolenoid.Value.kReverse); // } // // } // // }
import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SampleRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import org.usfirst.frc.team6162.robot.commands.ExampleCommand; import org.usfirst.frc.team6162.robot.subsystems.ExampleSubsystem; import org.usfirst.frc.team6162.robot.subsystems.Pneumatics; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Joystick;
package org.usfirst.frc.team6162.robot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
// Path: java/6162_3739/src/org/usfirst/frc/team6162/robot/commands/ExampleCommand.java // public class ExampleCommand extends Command { // // public ExampleCommand() { // // Use requires() here to declare subsystem dependencies // requires(Robot.exampleSubsystem); // } // // // Called just before this Command runs the first time // protected void initialize() { // } // // // Called repeatedly when this Command is scheduled to run // protected void execute() { // } // // // Make this return true when this Command no longer needs to run execute() // protected boolean isFinished() { // return false; // } // // // Called once after isFinished returns true // protected void end() { // } // // // Called when another command which requires one or more of the same // // subsystems is scheduled to run // protected void interrupted() { // } // } // // Path: SampleMultiFunction/src/org/usfirst/frc/team6162/robot/subsystems/ExampleSubsystem.java // public class ExampleSubsystem extends Subsystem { // // Put methods for controlling this subsystem // // here. Call these from Commands. // // public void initDefaultCommand() { // // Set the default command for a subsystem here. // // setDefaultCommand(new MySpecialCommand()); // } // } // // Path: 37396162/src/org/usfirst/frc/team6162/robot/subsystems/Pneumatics.java // public class Pneumatics extends Subsystem { // // // Put methods for controlling this subsystem // // here. Call these from Commands. // static DoubleSolenoid testDS; // public void initDefaultCommand() { // // Set the default command for a subsystem here. // //setDefaultCommand(new MySpecialCommand()); // testDS=new DoubleSolenoid(1,2); // testDS.set(DoubleSolenoid.Value.kOff); // LiveWindow.addActuator("Pneumatics", "testDS", testDS); // // } // // public void setDS(boolean on) { // if(on) { // testDS.set(DoubleSolenoid.Value.kForward); // } // else{ // testDS.set(DoubleSolenoid.Value.kReverse); // } // // } // // } // Path: 37396162/src/org/usfirst/frc/team6162/robot/Robot.java import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SampleRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import org.usfirst.frc.team6162.robot.commands.ExampleCommand; import org.usfirst.frc.team6162.robot.subsystems.ExampleSubsystem; import org.usfirst.frc.team6162.robot.subsystems.Pneumatics; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Joystick; package org.usfirst.frc.team6162.robot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
public static final Pneumatics pneumatics=new Pneumatics();
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/di/ServiceModule.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/service/TaskService.java // public class TaskService { // // private LocalAdapter mLocalAdapter; // // public TaskService(LocalAdapter localAdapter) { // mLocalAdapter = localAdapter; // } // // public Observable<Void> active(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.activeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Void> complete(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.completeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Task> create(String title, String description) { // return Observable.create(subscriber -> { // Task task = mLocalAdapter.createTask(title, description); // SubscriptionUtils.onNextAndComplete(subscriber, task); // }); // } // // public Observable<Task> find(String taskId) { // return Observable.create(subscriber -> { // Task task = mLocalAdapter.findTask(taskId); // if (task != null) { // SubscriptionUtils.onNextAndComplete(subscriber, task); // } else { // SubscriptionUtils.onError(subscriber, new DataNotFoundException()); // } // }); // } // // public Observable<List<Task>> getAll() { // return Observable.create(subscriber -> { // List<Task> tasks = mLocalAdapter.getTasks(); // SubscriptionUtils.onNextAndComplete(subscriber, tasks); // }); // } // // public Observable<Task> observeTaskCreate() { // return mLocalAdapter.observeTaskCreate(); // } // // public Observable<Task> observeTaskRemove() { // return mLocalAdapter.observeTaskRemove(); // } // // public Observable<Task> observeTaskUpdate() { // return mLocalAdapter.observeTaskUpdate(); // } // // public Observable<Void> remove(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.removeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Void> update(String taskId, String title, String description) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.updateTask(taskId, title, description); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // }
import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.service.TaskService;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.di; /** * Created by henrytao on 4/15/16. */ @Module(includes = { AdapterModule.class }) public class ServiceModule { @Singleton @Provides
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/service/TaskService.java // public class TaskService { // // private LocalAdapter mLocalAdapter; // // public TaskService(LocalAdapter localAdapter) { // mLocalAdapter = localAdapter; // } // // public Observable<Void> active(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.activeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Void> complete(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.completeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Task> create(String title, String description) { // return Observable.create(subscriber -> { // Task task = mLocalAdapter.createTask(title, description); // SubscriptionUtils.onNextAndComplete(subscriber, task); // }); // } // // public Observable<Task> find(String taskId) { // return Observable.create(subscriber -> { // Task task = mLocalAdapter.findTask(taskId); // if (task != null) { // SubscriptionUtils.onNextAndComplete(subscriber, task); // } else { // SubscriptionUtils.onError(subscriber, new DataNotFoundException()); // } // }); // } // // public Observable<List<Task>> getAll() { // return Observable.create(subscriber -> { // List<Task> tasks = mLocalAdapter.getTasks(); // SubscriptionUtils.onNextAndComplete(subscriber, tasks); // }); // } // // public Observable<Task> observeTaskCreate() { // return mLocalAdapter.observeTaskCreate(); // } // // public Observable<Task> observeTaskRemove() { // return mLocalAdapter.observeTaskRemove(); // } // // public Observable<Task> observeTaskUpdate() { // return mLocalAdapter.observeTaskUpdate(); // } // // public Observable<Void> remove(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.removeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Void> update(String taskId, String title, String description) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.updateTask(taskId, title, description); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/di/ServiceModule.java import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.service.TaskService; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.di; /** * Created by henrytao on 4/15/16. */ @Module(includes = { AdapterModule.class }) public class ServiceModule { @Singleton @Provides
TaskService provideTaskService(LocalAdapter localAdapter) {
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/di/ServiceModule.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/service/TaskService.java // public class TaskService { // // private LocalAdapter mLocalAdapter; // // public TaskService(LocalAdapter localAdapter) { // mLocalAdapter = localAdapter; // } // // public Observable<Void> active(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.activeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Void> complete(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.completeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Task> create(String title, String description) { // return Observable.create(subscriber -> { // Task task = mLocalAdapter.createTask(title, description); // SubscriptionUtils.onNextAndComplete(subscriber, task); // }); // } // // public Observable<Task> find(String taskId) { // return Observable.create(subscriber -> { // Task task = mLocalAdapter.findTask(taskId); // if (task != null) { // SubscriptionUtils.onNextAndComplete(subscriber, task); // } else { // SubscriptionUtils.onError(subscriber, new DataNotFoundException()); // } // }); // } // // public Observable<List<Task>> getAll() { // return Observable.create(subscriber -> { // List<Task> tasks = mLocalAdapter.getTasks(); // SubscriptionUtils.onNextAndComplete(subscriber, tasks); // }); // } // // public Observable<Task> observeTaskCreate() { // return mLocalAdapter.observeTaskCreate(); // } // // public Observable<Task> observeTaskRemove() { // return mLocalAdapter.observeTaskRemove(); // } // // public Observable<Task> observeTaskUpdate() { // return mLocalAdapter.observeTaskUpdate(); // } // // public Observable<Void> remove(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.removeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Void> update(String taskId, String title, String description) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.updateTask(taskId, title, description); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // }
import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.service.TaskService;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.di; /** * Created by henrytao on 4/15/16. */ @Module(includes = { AdapterModule.class }) public class ServiceModule { @Singleton @Provides
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/service/TaskService.java // public class TaskService { // // private LocalAdapter mLocalAdapter; // // public TaskService(LocalAdapter localAdapter) { // mLocalAdapter = localAdapter; // } // // public Observable<Void> active(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.activeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Void> complete(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.completeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Task> create(String title, String description) { // return Observable.create(subscriber -> { // Task task = mLocalAdapter.createTask(title, description); // SubscriptionUtils.onNextAndComplete(subscriber, task); // }); // } // // public Observable<Task> find(String taskId) { // return Observable.create(subscriber -> { // Task task = mLocalAdapter.findTask(taskId); // if (task != null) { // SubscriptionUtils.onNextAndComplete(subscriber, task); // } else { // SubscriptionUtils.onError(subscriber, new DataNotFoundException()); // } // }); // } // // public Observable<List<Task>> getAll() { // return Observable.create(subscriber -> { // List<Task> tasks = mLocalAdapter.getTasks(); // SubscriptionUtils.onNextAndComplete(subscriber, tasks); // }); // } // // public Observable<Task> observeTaskCreate() { // return mLocalAdapter.observeTaskCreate(); // } // // public Observable<Task> observeTaskRemove() { // return mLocalAdapter.observeTaskRemove(); // } // // public Observable<Task> observeTaskUpdate() { // return mLocalAdapter.observeTaskUpdate(); // } // // public Observable<Void> remove(String taskId) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.removeTask(taskId); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // // public Observable<Void> update(String taskId, String title, String description) { // return Observable.create(subscriber -> { // try { // mLocalAdapter.updateTask(taskId, title, description); // SubscriptionUtils.onNextAndComplete(subscriber); // } catch (Exception e) { // SubscriptionUtils.onError(subscriber, e); // } // }); // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/di/ServiceModule.java import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.service.TaskService; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.di; /** * Created by henrytao on 4/15/16. */ @Module(includes = { AdapterModule.class }) public class ServiceModule { @Singleton @Provides
TaskService provideTaskService(LocalAdapter localAdapter) {
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskaddedit/TaskAddEditActivity.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // }
import me.henrytao.mvvmlifecycledemo.ui.base.Constants; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import me.henrytao.mdcore.utils.ResourceUtils; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.databinding.TaskAddEditActivityBinding; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui.taskaddedit; /** * Created by henrytao on 4/2/16. */ public class TaskAddEditActivity extends BaseActivity { public static Intent newIntent(Context context) { return newIntent(context, null); } public static Intent newIntent(Context context, String taskId) { Intent intent = new Intent(context, TaskAddEditActivity.class); Bundle bundle = new Bundle();
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskaddedit/TaskAddEditActivity.java import me.henrytao.mvvmlifecycledemo.ui.base.Constants; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import me.henrytao.mdcore.utils.ResourceUtils; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.databinding.TaskAddEditActivityBinding; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui.taskaddedit; /** * Created by henrytao on 4/2/16. */ public class TaskAddEditActivity extends BaseActivity { public static Intent newIntent(Context context) { return newIntent(context, null); } public static Intent newIntent(Context context, String taskId) { Intent intent = new Intent(context, TaskAddEditActivity.class); Bundle bundle = new Bundle();
bundle.putString(Constants.Extra.ID, taskId);
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskaddedit/TaskAddEditActivity.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // }
import me.henrytao.mvvmlifecycledemo.ui.base.Constants; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import me.henrytao.mdcore.utils.ResourceUtils; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.databinding.TaskAddEditActivityBinding; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity;
} @Override public void onSetContentView(Bundle savedInstanceState) { mBinding = DataBindingUtil.setContentView(this, R.layout.task_add_edit_activity); mBinding.setViewModel(mViewModel); setSupportActionBar(mBinding.toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); manageSubscription(mViewModel.getState().subscribe(state -> { switch (state.getName()) { case CREATED_TASK: finish(); break; case CREATING_TASK: // TODO: should handle progressbar break; case MISSING_TITLE: Snackbar.make(findViewById(R.id.container), R.string.empty_task_message, Snackbar.LENGTH_SHORT).show(); break; case UPDATING_TASK: // TODO: should handle progressbar break; case UPDATED_TASK: finish(); break; }
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskaddedit/TaskAddEditActivity.java import me.henrytao.mvvmlifecycledemo.ui.base.Constants; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import me.henrytao.mdcore.utils.ResourceUtils; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.databinding.TaskAddEditActivityBinding; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity; } @Override public void onSetContentView(Bundle savedInstanceState) { mBinding = DataBindingUtil.setContentView(this, R.layout.task_add_edit_activity); mBinding.setViewModel(mViewModel); setSupportActionBar(mBinding.toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); manageSubscription(mViewModel.getState().subscribe(state -> { switch (state.getName()) { case CREATED_TASK: finish(); break; case CREATING_TASK: // TODO: should handle progressbar break; case MISSING_TITLE: Snackbar.make(findViewById(R.id.container), R.string.empty_task_message, Snackbar.LENGTH_SHORT).show(); break; case UPDATING_TASK: // TODO: should handle progressbar break; case UPDATED_TASK: finish(); break; }
}), UnsubscribeLifeCycle.DESTROY_VIEW);
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/MainActivity.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/home/HomeActivity.java // public class HomeActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener { // // public static Intent newIntent(Context context) { // return new Intent(context, HomeActivity.class); // } // // private HomeActivityBinding mBinding; // // private HomeViewModel mViewModel; // // @Override // public void onInitializeViewModels() { // mViewModel = new HomeViewModel(); // addViewModel(mViewModel); // } // // @Override // public boolean onNavigationItemSelected(MenuItem item) { // mBinding.drawerLayout.closeDrawers(); // manageSubscription(Observable // .timer(Constants.Animation.SHORT, TimeUnit.MILLISECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(l -> onNavigationItemSelected(item.getItemId())), UnsubscribeLifeCycle.DESTROY_VIEW); // return true; // } // // @Override // public void onSetContentView(Bundle savedInstanceState) { // mBinding = DataBindingUtil.setContentView(this, R.layout.home_activity); // mBinding.setViewModel(mViewModel); // // setSupportActionBar(mBinding.toolbar); // // ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle( // this, mBinding.drawerLayout, mBinding.toolbar, R.string.text_open, R.string.text_close); // mBinding.drawerLayout.addDrawerListener(actionBarDrawerToggle); // actionBarDrawerToggle.syncState(); // // mBinding.navigationView.setNavigationItemSelectedListener(this); // // if (savedInstanceState == null) { // getSupportFragmentManager() // .beginTransaction() // .replace(R.id.container, TasksFragment.newInstance()) // .commit(); // } // // manageSubscription(mViewModel.getState().subscribe(state -> { // switch (state.getName()) { // case CLICK_ADD_NEW_TASKS: // startActivity(TaskAddEditActivity.newIntent(this)); // break; // } // }), UnsubscribeLifeCycle.DESTROY_VIEW); // } // // private void onNavigationItemSelected(int id) { // switch (id) { // case R.id.menu_item_statistics_navigation: // new AlertDialogBuilder(this) // .setMessage("Let's try to implement this feature with MVVMLifeCycle. Don't hesitate to send me a question hi@henrytao.me") // .setPositiveButton("Close") // .show(); // break; // } // } // }
import android.content.Intent; import android.os.Bundle; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity; import me.henrytao.mvvmlifecycledemo.ui.home.HomeActivity;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui; public class MainActivity extends BaseActivity { @Override public void onInitializeViewModels() { } @Override public void onSetContentView(Bundle savedInstanceState) {
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/home/HomeActivity.java // public class HomeActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener { // // public static Intent newIntent(Context context) { // return new Intent(context, HomeActivity.class); // } // // private HomeActivityBinding mBinding; // // private HomeViewModel mViewModel; // // @Override // public void onInitializeViewModels() { // mViewModel = new HomeViewModel(); // addViewModel(mViewModel); // } // // @Override // public boolean onNavigationItemSelected(MenuItem item) { // mBinding.drawerLayout.closeDrawers(); // manageSubscription(Observable // .timer(Constants.Animation.SHORT, TimeUnit.MILLISECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(l -> onNavigationItemSelected(item.getItemId())), UnsubscribeLifeCycle.DESTROY_VIEW); // return true; // } // // @Override // public void onSetContentView(Bundle savedInstanceState) { // mBinding = DataBindingUtil.setContentView(this, R.layout.home_activity); // mBinding.setViewModel(mViewModel); // // setSupportActionBar(mBinding.toolbar); // // ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle( // this, mBinding.drawerLayout, mBinding.toolbar, R.string.text_open, R.string.text_close); // mBinding.drawerLayout.addDrawerListener(actionBarDrawerToggle); // actionBarDrawerToggle.syncState(); // // mBinding.navigationView.setNavigationItemSelectedListener(this); // // if (savedInstanceState == null) { // getSupportFragmentManager() // .beginTransaction() // .replace(R.id.container, TasksFragment.newInstance()) // .commit(); // } // // manageSubscription(mViewModel.getState().subscribe(state -> { // switch (state.getName()) { // case CLICK_ADD_NEW_TASKS: // startActivity(TaskAddEditActivity.newIntent(this)); // break; // } // }), UnsubscribeLifeCycle.DESTROY_VIEW); // } // // private void onNavigationItemSelected(int id) { // switch (id) { // case R.id.menu_item_statistics_navigation: // new AlertDialogBuilder(this) // .setMessage("Let's try to implement this feature with MVVMLifeCycle. Don't hesitate to send me a question hi@henrytao.me") // .setPositiveButton("Close") // .show(); // break; // } // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/MainActivity.java import android.content.Intent; import android.os.Bundle; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity; import me.henrytao.mvvmlifecycledemo.ui.home.HomeActivity; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui; public class MainActivity extends BaseActivity { @Override public void onInitializeViewModels() { } @Override public void onSetContentView(Bundle savedInstanceState) {
Intent intent = HomeActivity.newIntent(this);
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskdetail/TaskDetailActivity.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskaddedit/TaskAddEditActivity.java // public class TaskAddEditActivity extends BaseActivity { // // public static Intent newIntent(Context context) { // return newIntent(context, null); // } // // public static Intent newIntent(Context context, String taskId) { // Intent intent = new Intent(context, TaskAddEditActivity.class); // Bundle bundle = new Bundle(); // bundle.putString(Constants.Extra.ID, taskId); // intent.putExtras(bundle); // return intent; // } // // private TaskAddEditActivityBinding mBinding; // // private TaskAddEditViewModel mViewModel; // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_task_add_edit, menu); // ResourceUtils.supportDrawableTint(this, menu, ResourceUtils.Palette.PRIMARY); // return super.onCreateOptionsMenu(menu); // } // // @Override // public void onInitializeViewModels() { // Bundle bundle = getIntent().getExtras(); // String taskId = bundle.getString(Constants.Extra.ID); // // setTitle(!TextUtils.isEmpty(taskId) ? R.string.edit_task : R.string.add_task); // // mViewModel = new TaskAddEditViewModel(taskId); // addViewModel(mViewModel); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case R.id.action_done: // mViewModel.onDoneClick(); // break; // } // return true; // } // // @Override // public void onSetContentView(Bundle savedInstanceState) { // mBinding = DataBindingUtil.setContentView(this, R.layout.task_add_edit_activity); // mBinding.setViewModel(mViewModel); // // setSupportActionBar(mBinding.toolbar); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); // ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); // // manageSubscription(mViewModel.getState().subscribe(state -> { // switch (state.getName()) { // case CREATED_TASK: // finish(); // break; // case CREATING_TASK: // // TODO: should handle progressbar // break; // case MISSING_TITLE: // Snackbar.make(findViewById(R.id.container), R.string.empty_task_message, Snackbar.LENGTH_SHORT).show(); // break; // case UPDATING_TASK: // // TODO: should handle progressbar // break; // case UPDATED_TASK: // finish(); // break; // } // }), UnsubscribeLifeCycle.DESTROY_VIEW); // } // }
import me.henrytao.mvvmlifecycledemo.ui.taskaddedit.TaskAddEditActivity; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.Menu; import android.view.MenuItem; import me.henrytao.mdcore.utils.ResourceUtils; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.databinding.TaskDetailActivityBinding; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity; import me.henrytao.mvvmlifecycledemo.ui.base.Constants;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui.taskdetail; /** * Created by henrytao on 4/2/16. */ public class TaskDetailActivity extends BaseActivity { public static Intent newIntent(Context context, String taskId) { Intent intent = new Intent(context, TaskDetailActivity.class); Bundle bundle = new Bundle();
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskaddedit/TaskAddEditActivity.java // public class TaskAddEditActivity extends BaseActivity { // // public static Intent newIntent(Context context) { // return newIntent(context, null); // } // // public static Intent newIntent(Context context, String taskId) { // Intent intent = new Intent(context, TaskAddEditActivity.class); // Bundle bundle = new Bundle(); // bundle.putString(Constants.Extra.ID, taskId); // intent.putExtras(bundle); // return intent; // } // // private TaskAddEditActivityBinding mBinding; // // private TaskAddEditViewModel mViewModel; // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_task_add_edit, menu); // ResourceUtils.supportDrawableTint(this, menu, ResourceUtils.Palette.PRIMARY); // return super.onCreateOptionsMenu(menu); // } // // @Override // public void onInitializeViewModels() { // Bundle bundle = getIntent().getExtras(); // String taskId = bundle.getString(Constants.Extra.ID); // // setTitle(!TextUtils.isEmpty(taskId) ? R.string.edit_task : R.string.add_task); // // mViewModel = new TaskAddEditViewModel(taskId); // addViewModel(mViewModel); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case R.id.action_done: // mViewModel.onDoneClick(); // break; // } // return true; // } // // @Override // public void onSetContentView(Bundle savedInstanceState) { // mBinding = DataBindingUtil.setContentView(this, R.layout.task_add_edit_activity); // mBinding.setViewModel(mViewModel); // // setSupportActionBar(mBinding.toolbar); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); // ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); // // manageSubscription(mViewModel.getState().subscribe(state -> { // switch (state.getName()) { // case CREATED_TASK: // finish(); // break; // case CREATING_TASK: // // TODO: should handle progressbar // break; // case MISSING_TITLE: // Snackbar.make(findViewById(R.id.container), R.string.empty_task_message, Snackbar.LENGTH_SHORT).show(); // break; // case UPDATING_TASK: // // TODO: should handle progressbar // break; // case UPDATED_TASK: // finish(); // break; // } // }), UnsubscribeLifeCycle.DESTROY_VIEW); // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskdetail/TaskDetailActivity.java import me.henrytao.mvvmlifecycledemo.ui.taskaddedit.TaskAddEditActivity; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.Menu; import android.view.MenuItem; import me.henrytao.mdcore.utils.ResourceUtils; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.databinding.TaskDetailActivityBinding; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity; import me.henrytao.mvvmlifecycledemo.ui.base.Constants; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui.taskdetail; /** * Created by henrytao on 4/2/16. */ public class TaskDetailActivity extends BaseActivity { public static Intent newIntent(Context context, String taskId) { Intent intent = new Intent(context, TaskDetailActivity.class); Bundle bundle = new Bundle();
bundle.putString(Constants.Extra.ID, taskId);
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskdetail/TaskDetailActivity.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskaddedit/TaskAddEditActivity.java // public class TaskAddEditActivity extends BaseActivity { // // public static Intent newIntent(Context context) { // return newIntent(context, null); // } // // public static Intent newIntent(Context context, String taskId) { // Intent intent = new Intent(context, TaskAddEditActivity.class); // Bundle bundle = new Bundle(); // bundle.putString(Constants.Extra.ID, taskId); // intent.putExtras(bundle); // return intent; // } // // private TaskAddEditActivityBinding mBinding; // // private TaskAddEditViewModel mViewModel; // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_task_add_edit, menu); // ResourceUtils.supportDrawableTint(this, menu, ResourceUtils.Palette.PRIMARY); // return super.onCreateOptionsMenu(menu); // } // // @Override // public void onInitializeViewModels() { // Bundle bundle = getIntent().getExtras(); // String taskId = bundle.getString(Constants.Extra.ID); // // setTitle(!TextUtils.isEmpty(taskId) ? R.string.edit_task : R.string.add_task); // // mViewModel = new TaskAddEditViewModel(taskId); // addViewModel(mViewModel); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case R.id.action_done: // mViewModel.onDoneClick(); // break; // } // return true; // } // // @Override // public void onSetContentView(Bundle savedInstanceState) { // mBinding = DataBindingUtil.setContentView(this, R.layout.task_add_edit_activity); // mBinding.setViewModel(mViewModel); // // setSupportActionBar(mBinding.toolbar); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); // ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); // // manageSubscription(mViewModel.getState().subscribe(state -> { // switch (state.getName()) { // case CREATED_TASK: // finish(); // break; // case CREATING_TASK: // // TODO: should handle progressbar // break; // case MISSING_TITLE: // Snackbar.make(findViewById(R.id.container), R.string.empty_task_message, Snackbar.LENGTH_SHORT).show(); // break; // case UPDATING_TASK: // // TODO: should handle progressbar // break; // case UPDATED_TASK: // finish(); // break; // } // }), UnsubscribeLifeCycle.DESTROY_VIEW); // } // }
import me.henrytao.mvvmlifecycledemo.ui.taskaddedit.TaskAddEditActivity; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.Menu; import android.view.MenuItem; import me.henrytao.mdcore.utils.ResourceUtils; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.databinding.TaskDetailActivityBinding; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity; import me.henrytao.mvvmlifecycledemo.ui.base.Constants;
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_delete: mViewModel.onDeleteTaskClick(); break; } return true; } @Override public void onSetContentView(Bundle savedInstanceState) { mBinding = DataBindingUtil.setContentView(this, R.layout.task_detail_activity); mBinding.setViewModel(mViewModel); setSupportActionBar(mBinding.toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); manageSubscription(mViewModel.getState().subscribe(state -> { switch (state.getName()) { case ACTIVE_TASK: Snackbar.make(mBinding.container, R.string.task_marked_active, Snackbar.LENGTH_SHORT).show(); break; case COMPLETE_TASK: Snackbar.make(mBinding.container, R.string.task_marked_complete, Snackbar.LENGTH_SHORT).show(); break; case CLICK_EDIT_TASK:
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskaddedit/TaskAddEditActivity.java // public class TaskAddEditActivity extends BaseActivity { // // public static Intent newIntent(Context context) { // return newIntent(context, null); // } // // public static Intent newIntent(Context context, String taskId) { // Intent intent = new Intent(context, TaskAddEditActivity.class); // Bundle bundle = new Bundle(); // bundle.putString(Constants.Extra.ID, taskId); // intent.putExtras(bundle); // return intent; // } // // private TaskAddEditActivityBinding mBinding; // // private TaskAddEditViewModel mViewModel; // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_task_add_edit, menu); // ResourceUtils.supportDrawableTint(this, menu, ResourceUtils.Palette.PRIMARY); // return super.onCreateOptionsMenu(menu); // } // // @Override // public void onInitializeViewModels() { // Bundle bundle = getIntent().getExtras(); // String taskId = bundle.getString(Constants.Extra.ID); // // setTitle(!TextUtils.isEmpty(taskId) ? R.string.edit_task : R.string.add_task); // // mViewModel = new TaskAddEditViewModel(taskId); // addViewModel(mViewModel); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case R.id.action_done: // mViewModel.onDoneClick(); // break; // } // return true; // } // // @Override // public void onSetContentView(Bundle savedInstanceState) { // mBinding = DataBindingUtil.setContentView(this, R.layout.task_add_edit_activity); // mBinding.setViewModel(mViewModel); // // setSupportActionBar(mBinding.toolbar); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); // ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); // // manageSubscription(mViewModel.getState().subscribe(state -> { // switch (state.getName()) { // case CREATED_TASK: // finish(); // break; // case CREATING_TASK: // // TODO: should handle progressbar // break; // case MISSING_TITLE: // Snackbar.make(findViewById(R.id.container), R.string.empty_task_message, Snackbar.LENGTH_SHORT).show(); // break; // case UPDATING_TASK: // // TODO: should handle progressbar // break; // case UPDATED_TASK: // finish(); // break; // } // }), UnsubscribeLifeCycle.DESTROY_VIEW); // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskdetail/TaskDetailActivity.java import me.henrytao.mvvmlifecycledemo.ui.taskaddedit.TaskAddEditActivity; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.Menu; import android.view.MenuItem; import me.henrytao.mdcore.utils.ResourceUtils; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.databinding.TaskDetailActivityBinding; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity; import me.henrytao.mvvmlifecycledemo.ui.base.Constants; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_delete: mViewModel.onDeleteTaskClick(); break; } return true; } @Override public void onSetContentView(Bundle savedInstanceState) { mBinding = DataBindingUtil.setContentView(this, R.layout.task_detail_activity); mBinding.setViewModel(mViewModel); setSupportActionBar(mBinding.toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); manageSubscription(mViewModel.getState().subscribe(state -> { switch (state.getName()) { case ACTIVE_TASK: Snackbar.make(mBinding.container, R.string.task_marked_active, Snackbar.LENGTH_SHORT).show(); break; case COMPLETE_TASK: Snackbar.make(mBinding.container, R.string.task_marked_complete, Snackbar.LENGTH_SHORT).show(); break; case CLICK_EDIT_TASK:
startActivity(TaskAddEditActivity.newIntent(this, state.getData().getString(Constants.Key.ID)));
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskdetail/TaskDetailActivity.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskaddedit/TaskAddEditActivity.java // public class TaskAddEditActivity extends BaseActivity { // // public static Intent newIntent(Context context) { // return newIntent(context, null); // } // // public static Intent newIntent(Context context, String taskId) { // Intent intent = new Intent(context, TaskAddEditActivity.class); // Bundle bundle = new Bundle(); // bundle.putString(Constants.Extra.ID, taskId); // intent.putExtras(bundle); // return intent; // } // // private TaskAddEditActivityBinding mBinding; // // private TaskAddEditViewModel mViewModel; // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_task_add_edit, menu); // ResourceUtils.supportDrawableTint(this, menu, ResourceUtils.Palette.PRIMARY); // return super.onCreateOptionsMenu(menu); // } // // @Override // public void onInitializeViewModels() { // Bundle bundle = getIntent().getExtras(); // String taskId = bundle.getString(Constants.Extra.ID); // // setTitle(!TextUtils.isEmpty(taskId) ? R.string.edit_task : R.string.add_task); // // mViewModel = new TaskAddEditViewModel(taskId); // addViewModel(mViewModel); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case R.id.action_done: // mViewModel.onDoneClick(); // break; // } // return true; // } // // @Override // public void onSetContentView(Bundle savedInstanceState) { // mBinding = DataBindingUtil.setContentView(this, R.layout.task_add_edit_activity); // mBinding.setViewModel(mViewModel); // // setSupportActionBar(mBinding.toolbar); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); // ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); // // manageSubscription(mViewModel.getState().subscribe(state -> { // switch (state.getName()) { // case CREATED_TASK: // finish(); // break; // case CREATING_TASK: // // TODO: should handle progressbar // break; // case MISSING_TITLE: // Snackbar.make(findViewById(R.id.container), R.string.empty_task_message, Snackbar.LENGTH_SHORT).show(); // break; // case UPDATING_TASK: // // TODO: should handle progressbar // break; // case UPDATED_TASK: // finish(); // break; // } // }), UnsubscribeLifeCycle.DESTROY_VIEW); // } // }
import me.henrytao.mvvmlifecycledemo.ui.taskaddedit.TaskAddEditActivity; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.Menu; import android.view.MenuItem; import me.henrytao.mdcore.utils.ResourceUtils; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.databinding.TaskDetailActivityBinding; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity; import me.henrytao.mvvmlifecycledemo.ui.base.Constants;
break; } return true; } @Override public void onSetContentView(Bundle savedInstanceState) { mBinding = DataBindingUtil.setContentView(this, R.layout.task_detail_activity); mBinding.setViewModel(mViewModel); setSupportActionBar(mBinding.toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); manageSubscription(mViewModel.getState().subscribe(state -> { switch (state.getName()) { case ACTIVE_TASK: Snackbar.make(mBinding.container, R.string.task_marked_active, Snackbar.LENGTH_SHORT).show(); break; case COMPLETE_TASK: Snackbar.make(mBinding.container, R.string.task_marked_complete, Snackbar.LENGTH_SHORT).show(); break; case CLICK_EDIT_TASK: startActivity(TaskAddEditActivity.newIntent(this, state.getData().getString(Constants.Key.ID))); break; case DELETE_TASK: finish(); break; }
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseActivity.java // public abstract class BaseActivity extends MVVMActivity { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskaddedit/TaskAddEditActivity.java // public class TaskAddEditActivity extends BaseActivity { // // public static Intent newIntent(Context context) { // return newIntent(context, null); // } // // public static Intent newIntent(Context context, String taskId) { // Intent intent = new Intent(context, TaskAddEditActivity.class); // Bundle bundle = new Bundle(); // bundle.putString(Constants.Extra.ID, taskId); // intent.putExtras(bundle); // return intent; // } // // private TaskAddEditActivityBinding mBinding; // // private TaskAddEditViewModel mViewModel; // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_task_add_edit, menu); // ResourceUtils.supportDrawableTint(this, menu, ResourceUtils.Palette.PRIMARY); // return super.onCreateOptionsMenu(menu); // } // // @Override // public void onInitializeViewModels() { // Bundle bundle = getIntent().getExtras(); // String taskId = bundle.getString(Constants.Extra.ID); // // setTitle(!TextUtils.isEmpty(taskId) ? R.string.edit_task : R.string.add_task); // // mViewModel = new TaskAddEditViewModel(taskId); // addViewModel(mViewModel); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case R.id.action_done: // mViewModel.onDoneClick(); // break; // } // return true; // } // // @Override // public void onSetContentView(Bundle savedInstanceState) { // mBinding = DataBindingUtil.setContentView(this, R.layout.task_add_edit_activity); // mBinding.setViewModel(mViewModel); // // setSupportActionBar(mBinding.toolbar); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); // ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); // // manageSubscription(mViewModel.getState().subscribe(state -> { // switch (state.getName()) { // case CREATED_TASK: // finish(); // break; // case CREATING_TASK: // // TODO: should handle progressbar // break; // case MISSING_TITLE: // Snackbar.make(findViewById(R.id.container), R.string.empty_task_message, Snackbar.LENGTH_SHORT).show(); // break; // case UPDATING_TASK: // // TODO: should handle progressbar // break; // case UPDATED_TASK: // finish(); // break; // } // }), UnsubscribeLifeCycle.DESTROY_VIEW); // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/taskdetail/TaskDetailActivity.java import me.henrytao.mvvmlifecycledemo.ui.taskaddedit.TaskAddEditActivity; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.view.Menu; import android.view.MenuItem; import me.henrytao.mdcore.utils.ResourceUtils; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.databinding.TaskDetailActivityBinding; import me.henrytao.mvvmlifecycledemo.ui.base.BaseActivity; import me.henrytao.mvvmlifecycledemo.ui.base.Constants; break; } return true; } @Override public void onSetContentView(Bundle savedInstanceState) { mBinding = DataBindingUtil.setContentView(this, R.layout.task_detail_activity); mBinding.setViewModel(mViewModel); setSupportActionBar(mBinding.toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mBinding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); ResourceUtils.supportDrawableTint(this, mBinding.toolbar, ResourceUtils.Palette.PRIMARY); manageSubscription(mViewModel.getState().subscribe(state -> { switch (state.getName()) { case ACTIVE_TASK: Snackbar.make(mBinding.container, R.string.task_marked_active, Snackbar.LENGTH_SHORT).show(); break; case COMPLETE_TASK: Snackbar.make(mBinding.container, R.string.task_marked_complete, Snackbar.LENGTH_SHORT).show(); break; case CLICK_EDIT_TASK: startActivity(TaskAddEditActivity.newIntent(this, state.getData().getString(Constants.Key.ID))); break; case DELETE_TASK: finish(); break; }
}), UnsubscribeLifeCycle.DESTROY_VIEW);
henrytao-me/mvvm-life-cycle
mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/viewmodel/ViewModelWithEventDispatcher.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/event/Event.java // public interface Event extends Action1<Object> { // // }
import android.text.TextUtils; import java.util.HashMap; import java.util.Locale; import java.util.Map; import me.henrytao.mvvmlifecycle.event.Event; import rx.Subscription; import rx.functions.Action1; import rx.subjects.PublishSubject;
} } public void dispatch(Enum eventName, Object... objects) { dispatch(eventName.toString(), objects); } public void dispatch(String eventName, Object... objects) { if (sEventSubject.containsKey(eventName)) { sEventSubject.get(eventName).onNext(objects); } } public void register(Object owner, Enum event) { register(owner, event.toString()); } public void register(Object owner, String eventName) { String ownerClassName = owner.getClass().toString(); if (sRegisteredEvents.containsKey(eventName)) { if (!TextUtils.equals(sRegisteredEvents.get(eventName), ownerClassName)) { throw new DuplicatedEventException( String.format(Locale.US, "Event %s has already been registered in %s", eventName, sRegisteredEvents.get(eventName))); } } else { sRegisteredEvents.put(eventName, ownerClassName); } initEventSubject(eventName); }
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/event/Event.java // public interface Event extends Action1<Object> { // // } // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/viewmodel/ViewModelWithEventDispatcher.java import android.text.TextUtils; import java.util.HashMap; import java.util.Locale; import java.util.Map; import me.henrytao.mvvmlifecycle.event.Event; import rx.Subscription; import rx.functions.Action1; import rx.subjects.PublishSubject; } } public void dispatch(Enum eventName, Object... objects) { dispatch(eventName.toString(), objects); } public void dispatch(String eventName, Object... objects) { if (sEventSubject.containsKey(eventName)) { sEventSubject.get(eventName).onNext(objects); } } public void register(Object owner, Enum event) { register(owner, event.toString()); } public void register(Object owner, String eventName) { String ownerClassName = owner.getClass().toString(); if (sRegisteredEvents.containsKey(eventName)) { if (!TextUtils.equals(sRegisteredEvents.get(eventName), ownerClassName)) { throw new DuplicatedEventException( String.format(Locale.US, "Event %s has already been registered in %s", eventName, sRegisteredEvents.get(eventName))); } } else { sRegisteredEvents.put(eventName, ownerClassName); } initEventSubject(eventName); }
public Subscription subscribe(Enum eventName, Event event, Action1<Throwable> onError) {
henrytao-me/mvvm-life-cycle
mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/recyclerview/RecyclerViewBindingViewHolder.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMObserver.java // public interface MVVMObserver { // // void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException; // // void addViewModel(MVVMViewModel viewModel); // // void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions); // // void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void onInitializeViewModels(); // // void unsubscribe(String id); // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMViewModel.java // public abstract class MVVMViewModel<T> extends ViewModelWithEventDispatcherAndState<T> { // // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // }
import android.support.annotation.LayoutRes; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.mvvmlifecycle.MVVMObserver; import me.henrytao.mvvmlifecycle.MVVMViewModel; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle.recyclerview; /** * Created by henrytao on 4/15/16. */ public abstract class RecyclerViewBindingViewHolder<D> extends RecyclerView.ViewHolder implements MVVMObserver { public abstract void bind(D data); protected MVVMObserver mObserver; /** * This constructor should be extended and set proper layoutId */ public RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent) { this(observer, parent, 0); } protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, View view) { super(view); mObserver = observer; onInitializeViewModels(); } protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, @LayoutRes int layoutId) { this(observer, parent, LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false)); } @Override
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMObserver.java // public interface MVVMObserver { // // void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException; // // void addViewModel(MVVMViewModel viewModel); // // void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions); // // void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void onInitializeViewModels(); // // void unsubscribe(String id); // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMViewModel.java // public abstract class MVVMViewModel<T> extends ViewModelWithEventDispatcherAndState<T> { // // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/recyclerview/RecyclerViewBindingViewHolder.java import android.support.annotation.LayoutRes; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.mvvmlifecycle.MVVMObserver; import me.henrytao.mvvmlifecycle.MVVMViewModel; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle.recyclerview; /** * Created by henrytao on 4/15/16. */ public abstract class RecyclerViewBindingViewHolder<D> extends RecyclerView.ViewHolder implements MVVMObserver { public abstract void bind(D data); protected MVVMObserver mObserver; /** * This constructor should be extended and set proper layoutId */ public RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent) { this(observer, parent, 0); } protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, View view) { super(view); mObserver = observer; onInitializeViewModels(); } protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, @LayoutRes int layoutId) { this(observer, parent, LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false)); } @Override
public void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException {
henrytao-me/mvvm-life-cycle
mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/recyclerview/RecyclerViewBindingViewHolder.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMObserver.java // public interface MVVMObserver { // // void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException; // // void addViewModel(MVVMViewModel viewModel); // // void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions); // // void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void onInitializeViewModels(); // // void unsubscribe(String id); // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMViewModel.java // public abstract class MVVMViewModel<T> extends ViewModelWithEventDispatcherAndState<T> { // // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // }
import android.support.annotation.LayoutRes; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.mvvmlifecycle.MVVMObserver; import me.henrytao.mvvmlifecycle.MVVMViewModel; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle.recyclerview; /** * Created by henrytao on 4/15/16. */ public abstract class RecyclerViewBindingViewHolder<D> extends RecyclerView.ViewHolder implements MVVMObserver { public abstract void bind(D data); protected MVVMObserver mObserver; /** * This constructor should be extended and set proper layoutId */ public RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent) { this(observer, parent, 0); } protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, View view) { super(view); mObserver = observer; onInitializeViewModels(); } protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, @LayoutRes int layoutId) { this(observer, parent, LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false)); } @Override public void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException { throw new IllegalAccessException("This method should not be called"); } @Override public void addViewModel(MVVMViewModel viewModel) { try { mObserver.addAdapterViewModel(viewModel); } catch (IllegalAccessException ignore) { } } @Override
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMObserver.java // public interface MVVMObserver { // // void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException; // // void addViewModel(MVVMViewModel viewModel); // // void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions); // // void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void onInitializeViewModels(); // // void unsubscribe(String id); // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMViewModel.java // public abstract class MVVMViewModel<T> extends ViewModelWithEventDispatcherAndState<T> { // // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/recyclerview/RecyclerViewBindingViewHolder.java import android.support.annotation.LayoutRes; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.mvvmlifecycle.MVVMObserver; import me.henrytao.mvvmlifecycle.MVVMViewModel; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle.recyclerview; /** * Created by henrytao on 4/15/16. */ public abstract class RecyclerViewBindingViewHolder<D> extends RecyclerView.ViewHolder implements MVVMObserver { public abstract void bind(D data); protected MVVMObserver mObserver; /** * This constructor should be extended and set proper layoutId */ public RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent) { this(observer, parent, 0); } protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, View view) { super(view); mObserver = observer; onInitializeViewModels(); } protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, @LayoutRes int layoutId) { this(observer, parent, LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false)); } @Override public void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException { throw new IllegalAccessException("This method should not be called"); } @Override public void addViewModel(MVVMViewModel viewModel) { try { mObserver.addAdapterViewModel(viewModel); } catch (IllegalAccessException ignore) { } } @Override
public void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions) {
henrytao-me/mvvm-life-cycle
sample/src/test/java/me/henrytao/mvvmlifecycledemo/data/service/TaskServiceTest.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java // public class BaseTest { // // @Before // public void initialize() { // MockitoAnnotations.initMocks(this); // Transformer.overrideComputationScheduler(Schedulers.immediate()); // Transformer.overrideIoScheduler(Schedulers.immediate()); // Transformer.overrideMainThreadScheduler(Schedulers.immediate()); // Transformer.overrideNewThreadScheduler(Schedulers.immediate()); // } // // @After // public void release() { // Transformer.resetComputationScheduler(); // Transformer.resetIoScheduler(); // Transformer.resetMainThreadScheduler(); // Transformer.resetNewThreadScheduler(); // } // }
import org.junit.Test; import org.mockito.Mock; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.util.BaseTest; import rx.observers.TestSubscriber; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.service; /** * Created by henrytao on 4/21/16. */ public class TaskServiceTest extends BaseTest { @Mock
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java // public class BaseTest { // // @Before // public void initialize() { // MockitoAnnotations.initMocks(this); // Transformer.overrideComputationScheduler(Schedulers.immediate()); // Transformer.overrideIoScheduler(Schedulers.immediate()); // Transformer.overrideMainThreadScheduler(Schedulers.immediate()); // Transformer.overrideNewThreadScheduler(Schedulers.immediate()); // } // // @After // public void release() { // Transformer.resetComputationScheduler(); // Transformer.resetIoScheduler(); // Transformer.resetMainThreadScheduler(); // Transformer.resetNewThreadScheduler(); // } // } // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/data/service/TaskServiceTest.java import org.junit.Test; import org.mockito.Mock; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.util.BaseTest; import rx.observers.TestSubscriber; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.service; /** * Created by henrytao on 4/21/16. */ public class TaskServiceTest extends BaseTest { @Mock
private LocalAdapter mLocalAdapter;
henrytao-me/mvvm-life-cycle
sample/src/test/java/me/henrytao/mvvmlifecycledemo/data/service/TaskServiceTest.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java // public class BaseTest { // // @Before // public void initialize() { // MockitoAnnotations.initMocks(this); // Transformer.overrideComputationScheduler(Schedulers.immediate()); // Transformer.overrideIoScheduler(Schedulers.immediate()); // Transformer.overrideMainThreadScheduler(Schedulers.immediate()); // Transformer.overrideNewThreadScheduler(Schedulers.immediate()); // } // // @After // public void release() { // Transformer.resetComputationScheduler(); // Transformer.resetIoScheduler(); // Transformer.resetMainThreadScheduler(); // Transformer.resetNewThreadScheduler(); // } // }
import org.junit.Test; import org.mockito.Mock; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.util.BaseTest; import rx.observers.TestSubscriber; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.service; /** * Created by henrytao on 4/21/16. */ public class TaskServiceTest extends BaseTest { @Mock private LocalAdapter mLocalAdapter; private TaskService mTaskService; @Override public void initialize() { super.initialize(); mTaskService = new TaskService(mLocalAdapter); } @Test public void testActiveError() throws Exception { TestSubscriber<Void> testSubscriber = new TestSubscriber<>();
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java // public class BaseTest { // // @Before // public void initialize() { // MockitoAnnotations.initMocks(this); // Transformer.overrideComputationScheduler(Schedulers.immediate()); // Transformer.overrideIoScheduler(Schedulers.immediate()); // Transformer.overrideMainThreadScheduler(Schedulers.immediate()); // Transformer.overrideNewThreadScheduler(Schedulers.immediate()); // } // // @After // public void release() { // Transformer.resetComputationScheduler(); // Transformer.resetIoScheduler(); // Transformer.resetMainThreadScheduler(); // Transformer.resetNewThreadScheduler(); // } // } // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/data/service/TaskServiceTest.java import org.junit.Test; import org.mockito.Mock; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.util.BaseTest; import rx.observers.TestSubscriber; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.service; /** * Created by henrytao on 4/21/16. */ public class TaskServiceTest extends BaseTest { @Mock private LocalAdapter mLocalAdapter; private TaskService mTaskService; @Override public void initialize() { super.initialize(); mTaskService = new TaskService(mLocalAdapter); } @Test public void testActiveError() throws Exception { TestSubscriber<Void> testSubscriber = new TestSubscriber<>();
DataNotFoundException exception = new DataNotFoundException();
henrytao-me/mvvm-life-cycle
sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/Transformer.java // public class Transformer { // // private static SchedulerManager sComputationScheduler = new SchedulerManager(Schedulers::computation); // // private static SchedulerManager sIoScheduler = new SchedulerManager(Schedulers::io); // // private static SchedulerManager sMainThreadScheduler = new SchedulerManager(AndroidSchedulers::mainThread); // // private static SchedulerManager sNewThreadScheduler = new SchedulerManager(Schedulers::newThread); // // public static <T> Observable.Transformer<T, T> applyComputationScheduler() { // return observable -> observable // .subscribeOn(sComputationScheduler.get()) // .observeOn(sMainThreadScheduler.get()); // } // // public static <T> Observable.Transformer<T, T> applyIoScheduler() { // return observable -> observable // .subscribeOn(sIoScheduler.get()) // .observeOn(sMainThreadScheduler.get()); // } // // public static <T> Observable.Transformer<T, T> applyMainThreadScheduler() { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // if (Looper.getMainLooper().isCurrentThread()) { // return observable -> observable; // } // } else { // if (Thread.currentThread() == Looper.getMainLooper().getThread()) { // return observable -> observable; // } // } // return observable -> observable // .subscribeOn(sMainThreadScheduler.get()) // .observeOn(sMainThreadScheduler.get()); // } // // public static <T> Observable.Transformer<T, T> applyNewThreadScheduler() { // return observable -> observable // .subscribeOn(sNewThreadScheduler.get()) // .observeOn(sMainThreadScheduler.get()); // } // // public static Scheduler getComputationScheduler() { // return sComputationScheduler.get(); // } // // public static Scheduler getIoScheduler() { // return sIoScheduler.get(); // } // // public static Scheduler getMainThreadScheduler() { // return sMainThreadScheduler.get(); // } // // public static Scheduler getNewThreadScheduler() { // return sNewThreadScheduler.get(); // } // // public static void overrideComputationScheduler(Scheduler scheduler) { // sComputationScheduler.set(scheduler); // } // // public static void overrideIoScheduler(Scheduler scheduler) { // sIoScheduler.set(scheduler); // } // // public static void overrideMainThreadScheduler(Scheduler scheduler) { // sMainThreadScheduler.set(scheduler); // } // // public static void overrideNewThreadScheduler(Scheduler scheduler) { // sNewThreadScheduler.set(scheduler); // } // // public static void resetComputationScheduler() { // sComputationScheduler.reset(); // } // // public static void resetIoScheduler() { // sIoScheduler.reset(); // } // // public static void resetMainThreadScheduler() { // sMainThreadScheduler.reset(); // } // // public static void resetNewThreadScheduler() { // sNewThreadScheduler.reset(); // } // // private static class SchedulerManager { // // private Callback mDefaultSchedulerCallback; // // private Scheduler mScheduler; // // public SchedulerManager(Callback defaultSchedulerCallback) { // mDefaultSchedulerCallback = defaultSchedulerCallback; // } // // public Scheduler get() { // return mScheduler != null ? mScheduler : mDefaultSchedulerCallback.get(); // } // // public void reset() { // set(null); // } // // public void set(Scheduler scheduler) { // mScheduler = scheduler; // } // // private interface Callback { // // Scheduler get(); // } // } // }
import org.junit.After; import org.junit.Before; import org.mockito.MockitoAnnotations; import me.henrytao.mvvmlifecycle.rx.Transformer; import rx.schedulers.Schedulers;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.util; /** * Created by henrytao on 4/23/16. */ public class BaseTest { @Before public void initialize() { MockitoAnnotations.initMocks(this);
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/Transformer.java // public class Transformer { // // private static SchedulerManager sComputationScheduler = new SchedulerManager(Schedulers::computation); // // private static SchedulerManager sIoScheduler = new SchedulerManager(Schedulers::io); // // private static SchedulerManager sMainThreadScheduler = new SchedulerManager(AndroidSchedulers::mainThread); // // private static SchedulerManager sNewThreadScheduler = new SchedulerManager(Schedulers::newThread); // // public static <T> Observable.Transformer<T, T> applyComputationScheduler() { // return observable -> observable // .subscribeOn(sComputationScheduler.get()) // .observeOn(sMainThreadScheduler.get()); // } // // public static <T> Observable.Transformer<T, T> applyIoScheduler() { // return observable -> observable // .subscribeOn(sIoScheduler.get()) // .observeOn(sMainThreadScheduler.get()); // } // // public static <T> Observable.Transformer<T, T> applyMainThreadScheduler() { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // if (Looper.getMainLooper().isCurrentThread()) { // return observable -> observable; // } // } else { // if (Thread.currentThread() == Looper.getMainLooper().getThread()) { // return observable -> observable; // } // } // return observable -> observable // .subscribeOn(sMainThreadScheduler.get()) // .observeOn(sMainThreadScheduler.get()); // } // // public static <T> Observable.Transformer<T, T> applyNewThreadScheduler() { // return observable -> observable // .subscribeOn(sNewThreadScheduler.get()) // .observeOn(sMainThreadScheduler.get()); // } // // public static Scheduler getComputationScheduler() { // return sComputationScheduler.get(); // } // // public static Scheduler getIoScheduler() { // return sIoScheduler.get(); // } // // public static Scheduler getMainThreadScheduler() { // return sMainThreadScheduler.get(); // } // // public static Scheduler getNewThreadScheduler() { // return sNewThreadScheduler.get(); // } // // public static void overrideComputationScheduler(Scheduler scheduler) { // sComputationScheduler.set(scheduler); // } // // public static void overrideIoScheduler(Scheduler scheduler) { // sIoScheduler.set(scheduler); // } // // public static void overrideMainThreadScheduler(Scheduler scheduler) { // sMainThreadScheduler.set(scheduler); // } // // public static void overrideNewThreadScheduler(Scheduler scheduler) { // sNewThreadScheduler.set(scheduler); // } // // public static void resetComputationScheduler() { // sComputationScheduler.reset(); // } // // public static void resetIoScheduler() { // sIoScheduler.reset(); // } // // public static void resetMainThreadScheduler() { // sMainThreadScheduler.reset(); // } // // public static void resetNewThreadScheduler() { // sNewThreadScheduler.reset(); // } // // private static class SchedulerManager { // // private Callback mDefaultSchedulerCallback; // // private Scheduler mScheduler; // // public SchedulerManager(Callback defaultSchedulerCallback) { // mDefaultSchedulerCallback = defaultSchedulerCallback; // } // // public Scheduler get() { // return mScheduler != null ? mScheduler : mDefaultSchedulerCallback.get(); // } // // public void reset() { // set(null); // } // // public void set(Scheduler scheduler) { // mScheduler = scheduler; // } // // private interface Callback { // // Scheduler get(); // } // } // } // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java import org.junit.After; import org.junit.Before; import org.mockito.MockitoAnnotations; import me.henrytao.mvvmlifecycle.rx.Transformer; import rx.schedulers.Schedulers; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.util; /** * Created by henrytao on 4/23/16. */ public class BaseTest { @Before public void initialize() { MockitoAnnotations.initMocks(this);
Transformer.overrideComputationScheduler(Schedulers.immediate());
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/service/TaskService.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionUtils.java // public class SubscriptionUtils { // // public static <T> void onComplete(Subscriber<T> subscriber) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onCompleted(); // } // } // // public static <T> void onError(Subscriber<T> subscriber, Throwable throwable) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onError(throwable); // } // } // // public static <T> void onNext(Subscriber<T> subscriber, T data) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onNext(data); // } // } // // public static <T> void onNext(Subscriber<T> subscriber) { // onNext(subscriber, null); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber, T data) { // onNext(subscriber, data); // onComplete(subscriber); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber) { // onNextAndComplete(subscriber, null); // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // }
import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionUtils; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import rx.Observable;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.service; /** * Created by henrytao on 4/14/16. */ public class TaskService { private LocalAdapter mLocalAdapter; public TaskService(LocalAdapter localAdapter) { mLocalAdapter = localAdapter; } public Observable<Void> active(String taskId) { return Observable.create(subscriber -> { try { mLocalAdapter.activeTask(taskId);
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionUtils.java // public class SubscriptionUtils { // // public static <T> void onComplete(Subscriber<T> subscriber) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onCompleted(); // } // } // // public static <T> void onError(Subscriber<T> subscriber, Throwable throwable) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onError(throwable); // } // } // // public static <T> void onNext(Subscriber<T> subscriber, T data) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onNext(data); // } // } // // public static <T> void onNext(Subscriber<T> subscriber) { // onNext(subscriber, null); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber, T data) { // onNext(subscriber, data); // onComplete(subscriber); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber) { // onNextAndComplete(subscriber, null); // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/service/TaskService.java import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionUtils; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import rx.Observable; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.service; /** * Created by henrytao on 4/14/16. */ public class TaskService { private LocalAdapter mLocalAdapter; public TaskService(LocalAdapter localAdapter) { mLocalAdapter = localAdapter; } public Observable<Void> active(String taskId) { return Observable.create(subscriber -> { try { mLocalAdapter.activeTask(taskId);
SubscriptionUtils.onNextAndComplete(subscriber);
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/service/TaskService.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionUtils.java // public class SubscriptionUtils { // // public static <T> void onComplete(Subscriber<T> subscriber) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onCompleted(); // } // } // // public static <T> void onError(Subscriber<T> subscriber, Throwable throwable) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onError(throwable); // } // } // // public static <T> void onNext(Subscriber<T> subscriber, T data) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onNext(data); // } // } // // public static <T> void onNext(Subscriber<T> subscriber) { // onNext(subscriber, null); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber, T data) { // onNext(subscriber, data); // onComplete(subscriber); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber) { // onNextAndComplete(subscriber, null); // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // }
import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionUtils; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import rx.Observable;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.service; /** * Created by henrytao on 4/14/16. */ public class TaskService { private LocalAdapter mLocalAdapter; public TaskService(LocalAdapter localAdapter) { mLocalAdapter = localAdapter; } public Observable<Void> active(String taskId) { return Observable.create(subscriber -> { try { mLocalAdapter.activeTask(taskId); SubscriptionUtils.onNextAndComplete(subscriber); } catch (Exception e) { SubscriptionUtils.onError(subscriber, e); } }); } public Observable<Void> complete(String taskId) { return Observable.create(subscriber -> { try { mLocalAdapter.completeTask(taskId); SubscriptionUtils.onNextAndComplete(subscriber); } catch (Exception e) { SubscriptionUtils.onError(subscriber, e); } }); }
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionUtils.java // public class SubscriptionUtils { // // public static <T> void onComplete(Subscriber<T> subscriber) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onCompleted(); // } // } // // public static <T> void onError(Subscriber<T> subscriber, Throwable throwable) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onError(throwable); // } // } // // public static <T> void onNext(Subscriber<T> subscriber, T data) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onNext(data); // } // } // // public static <T> void onNext(Subscriber<T> subscriber) { // onNext(subscriber, null); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber, T data) { // onNext(subscriber, data); // onComplete(subscriber); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber) { // onNextAndComplete(subscriber, null); // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/service/TaskService.java import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionUtils; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import rx.Observable; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.service; /** * Created by henrytao on 4/14/16. */ public class TaskService { private LocalAdapter mLocalAdapter; public TaskService(LocalAdapter localAdapter) { mLocalAdapter = localAdapter; } public Observable<Void> active(String taskId) { return Observable.create(subscriber -> { try { mLocalAdapter.activeTask(taskId); SubscriptionUtils.onNextAndComplete(subscriber); } catch (Exception e) { SubscriptionUtils.onError(subscriber, e); } }); } public Observable<Void> complete(String taskId) { return Observable.create(subscriber -> { try { mLocalAdapter.completeTask(taskId); SubscriptionUtils.onNextAndComplete(subscriber); } catch (Exception e) { SubscriptionUtils.onError(subscriber, e); } }); }
public Observable<Task> create(String title, String description) {
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/service/TaskService.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionUtils.java // public class SubscriptionUtils { // // public static <T> void onComplete(Subscriber<T> subscriber) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onCompleted(); // } // } // // public static <T> void onError(Subscriber<T> subscriber, Throwable throwable) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onError(throwable); // } // } // // public static <T> void onNext(Subscriber<T> subscriber, T data) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onNext(data); // } // } // // public static <T> void onNext(Subscriber<T> subscriber) { // onNext(subscriber, null); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber, T data) { // onNext(subscriber, data); // onComplete(subscriber); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber) { // onNextAndComplete(subscriber, null); // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // }
import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionUtils; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import rx.Observable;
} catch (Exception e) { SubscriptionUtils.onError(subscriber, e); } }); } public Observable<Void> complete(String taskId) { return Observable.create(subscriber -> { try { mLocalAdapter.completeTask(taskId); SubscriptionUtils.onNextAndComplete(subscriber); } catch (Exception e) { SubscriptionUtils.onError(subscriber, e); } }); } public Observable<Task> create(String title, String description) { return Observable.create(subscriber -> { Task task = mLocalAdapter.createTask(title, description); SubscriptionUtils.onNextAndComplete(subscriber, task); }); } public Observable<Task> find(String taskId) { return Observable.create(subscriber -> { Task task = mLocalAdapter.findTask(taskId); if (task != null) { SubscriptionUtils.onNextAndComplete(subscriber, task); } else {
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionUtils.java // public class SubscriptionUtils { // // public static <T> void onComplete(Subscriber<T> subscriber) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onCompleted(); // } // } // // public static <T> void onError(Subscriber<T> subscriber, Throwable throwable) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onError(throwable); // } // } // // public static <T> void onNext(Subscriber<T> subscriber, T data) { // if (subscriber != null && !subscriber.isUnsubscribed()) { // subscriber.onNext(data); // } // } // // public static <T> void onNext(Subscriber<T> subscriber) { // onNext(subscriber, null); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber, T data) { // onNext(subscriber, data); // onComplete(subscriber); // } // // public static <T> void onNextAndComplete(Subscriber<T> subscriber) { // onNextAndComplete(subscriber, null); // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/service/TaskService.java import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionUtils; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import rx.Observable; } catch (Exception e) { SubscriptionUtils.onError(subscriber, e); } }); } public Observable<Void> complete(String taskId) { return Observable.create(subscriber -> { try { mLocalAdapter.completeTask(taskId); SubscriptionUtils.onNextAndComplete(subscriber); } catch (Exception e) { SubscriptionUtils.onError(subscriber, e); } }); } public Observable<Task> create(String title, String description) { return Observable.create(subscriber -> { Task task = mLocalAdapter.createTask(title, description); SubscriptionUtils.onNextAndComplete(subscriber, task); }); } public Observable<Task> find(String taskId) { return Observable.create(subscriber -> { Task task = mLocalAdapter.findTask(taskId); if (task != null) { SubscriptionUtils.onNextAndComplete(subscriber, task); } else {
SubscriptionUtils.onError(subscriber, new DataNotFoundException());
henrytao-me/mvvm-life-cycle
sample/src/test/java/me/henrytao/mvvmlifecycledemo/ui/tasks/TasksViewModelTest.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/event/Event1.java // public class Event1<T> implements Event { // // private static final int LENGTH = 1; // // private final Listener<T> mListener; // // public Event1(Listener<T> listener) { // mListener = listener; // } // // @SuppressWarnings("unchecked") // @Override // public void call(Object o) { // if (mListener != null && o instanceof Object[]) { // Object[] objects = (Object[]) o; // if (objects.length == LENGTH) { // mListener.onEventTrigger((T) objects[0]); // return; // } // throw new InvalidParams(String.format(Locale.US, "Required %d. Found %d", LENGTH, objects.length)); // } // } // // public interface Listener<T> { // // void onEventTrigger(T data); // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/di/Injector.java // public class Injector { // // public static AppComponent component; // // public static AppComponent initialize(Application application) { // component = AppBuilder.build(application); // return component; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // } // // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java // public class BaseTest { // // @Before // public void initialize() { // MockitoAnnotations.initMocks(this); // Transformer.overrideComputationScheduler(Schedulers.immediate()); // Transformer.overrideIoScheduler(Schedulers.immediate()); // Transformer.overrideMainThreadScheduler(Schedulers.immediate()); // Transformer.overrideNewThreadScheduler(Schedulers.immediate()); // } // // @After // public void release() { // Transformer.resetComputationScheduler(); // Transformer.resetIoScheduler(); // Transformer.resetMainThreadScheduler(); // Transformer.resetNewThreadScheduler(); // } // }
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import org.junit.Test; import org.mockito.Mockito; import java.util.List; import me.henrytao.mvvmlifecycle.event.Event1; import me.henrytao.mvvmlifecycledemo.data.model.Task; import me.henrytao.mvvmlifecycledemo.di.Injector; import me.henrytao.mvvmlifecycledemo.ui.base.Constants; import me.henrytao.mvvmlifecycledemo.util.BaseTest; import rx.Observable; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui.tasks; /** * Created by henrytao on 4/23/16. */ public class TasksViewModelTest extends BaseTest { TasksViewModel mTasksViewModel; @Override public void initialize() { super.initialize();
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/event/Event1.java // public class Event1<T> implements Event { // // private static final int LENGTH = 1; // // private final Listener<T> mListener; // // public Event1(Listener<T> listener) { // mListener = listener; // } // // @SuppressWarnings("unchecked") // @Override // public void call(Object o) { // if (mListener != null && o instanceof Object[]) { // Object[] objects = (Object[]) o; // if (objects.length == LENGTH) { // mListener.onEventTrigger((T) objects[0]); // return; // } // throw new InvalidParams(String.format(Locale.US, "Required %d. Found %d", LENGTH, objects.length)); // } // } // // public interface Listener<T> { // // void onEventTrigger(T data); // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/di/Injector.java // public class Injector { // // public static AppComponent component; // // public static AppComponent initialize(Application application) { // component = AppBuilder.build(application); // return component; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/Constants.java // public class Constants { // // public interface Animation { // // int LONG = 600; // int MEDIUM = 400; // int SHORT = 200; // } // // public interface Extra { // // String ID = "ID"; // } // // public interface Key { // // String ID = "ID"; // String INDEX = "INDEX"; // } // } // // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java // public class BaseTest { // // @Before // public void initialize() { // MockitoAnnotations.initMocks(this); // Transformer.overrideComputationScheduler(Schedulers.immediate()); // Transformer.overrideIoScheduler(Schedulers.immediate()); // Transformer.overrideMainThreadScheduler(Schedulers.immediate()); // Transformer.overrideNewThreadScheduler(Schedulers.immediate()); // } // // @After // public void release() { // Transformer.resetComputationScheduler(); // Transformer.resetIoScheduler(); // Transformer.resetMainThreadScheduler(); // Transformer.resetNewThreadScheduler(); // } // } // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/ui/tasks/TasksViewModelTest.java import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import org.junit.Test; import org.mockito.Mockito; import java.util.List; import me.henrytao.mvvmlifecycle.event.Event1; import me.henrytao.mvvmlifecycledemo.data.model.Task; import me.henrytao.mvvmlifecycledemo.di.Injector; import me.henrytao.mvvmlifecycledemo.ui.base.Constants; import me.henrytao.mvvmlifecycledemo.util.BaseTest; import rx.Observable; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui.tasks; /** * Created by henrytao on 4/23/16. */ public class TasksViewModelTest extends BaseTest { TasksViewModel mTasksViewModel; @Override public void initialize() { super.initialize();
Injector.initialize(null);
henrytao-me/mvvm-life-cycle
mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/viewmodel/SimpleViewModel.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMLifeCycle.java // public interface MVVMLifeCycle { // // void onActivityResult(int requestCode, int resultCode, Intent data); // // void onCreate(); // // void onCreateView(); // // void onDestroy(); // // void onDestroyView(); // // void onPause(); // // void onRestoreInstanceState(Bundle savedInstanceState); // // void onResume(); // // void onSaveInstanceState(Bundle outState); // // void onStart(); // // void onStop(); // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // }
import android.content.Intent; import android.databinding.BaseObservable; import android.os.Bundle; import me.henrytao.mvvmlifecycle.MVVMLifeCycle; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle.viewmodel; /** * Created by henrytao on 4/24/16. */ public class SimpleViewModel extends BaseObservable implements MVVMLifeCycle { private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop;
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMLifeCycle.java // public interface MVVMLifeCycle { // // void onActivityResult(int requestCode, int resultCode, Intent data); // // void onCreate(); // // void onCreateView(); // // void onDestroy(); // // void onDestroyView(); // // void onPause(); // // void onRestoreInstanceState(Bundle savedInstanceState); // // void onResume(); // // void onSaveInstanceState(Bundle outState); // // void onStart(); // // void onStop(); // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/viewmodel/SimpleViewModel.java import android.content.Intent; import android.databinding.BaseObservable; import android.os.Bundle; import me.henrytao.mvvmlifecycle.MVVMLifeCycle; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle.viewmodel; /** * Created by henrytao on 4/24/16. */ public class SimpleViewModel extends BaseObservable implements MVVMLifeCycle { private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop;
private SubscriptionManager mSubscriptionManager = new SubscriptionManager();
henrytao-me/mvvm-life-cycle
mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/viewmodel/SimpleViewModel.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMLifeCycle.java // public interface MVVMLifeCycle { // // void onActivityResult(int requestCode, int resultCode, Intent data); // // void onCreate(); // // void onCreateView(); // // void onDestroy(); // // void onDestroyView(); // // void onPause(); // // void onRestoreInstanceState(Bundle savedInstanceState); // // void onResume(); // // void onSaveInstanceState(Bundle outState); // // void onStart(); // // void onStop(); // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // }
import android.content.Intent; import android.databinding.BaseObservable; import android.os.Bundle; import me.henrytao.mvvmlifecycle.MVVMLifeCycle; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle.viewmodel; /** * Created by henrytao on 4/24/16. */ public class SimpleViewModel extends BaseObservable implements MVVMLifeCycle { private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop; private SubscriptionManager mSubscriptionManager = new SubscriptionManager(); @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // do nothing } public void onCreate() { mIsDestroy = false; } public void onCreateView() { mIsDestroyView = false; } public void onDestroy() { mIsDestroy = true;
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMLifeCycle.java // public interface MVVMLifeCycle { // // void onActivityResult(int requestCode, int resultCode, Intent data); // // void onCreate(); // // void onCreateView(); // // void onDestroy(); // // void onDestroyView(); // // void onPause(); // // void onRestoreInstanceState(Bundle savedInstanceState); // // void onResume(); // // void onSaveInstanceState(Bundle outState); // // void onStart(); // // void onStop(); // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/viewmodel/SimpleViewModel.java import android.content.Intent; import android.databinding.BaseObservable; import android.os.Bundle; import me.henrytao.mvvmlifecycle.MVVMLifeCycle; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle.viewmodel; /** * Created by henrytao on 4/24/16. */ public class SimpleViewModel extends BaseObservable implements MVVMLifeCycle { private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop; private SubscriptionManager mSubscriptionManager = new SubscriptionManager(); @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // do nothing } public void onCreate() { mIsDestroy = false; } public void onCreateView() { mIsDestroyView = false; } public void onDestroy() { mIsDestroy = true;
mSubscriptionManager.unsubscribe(UnsubscribeLifeCycle.DESTROY);
henrytao-me/mvvm-life-cycle
mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMObserver.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // }
import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle; /** * Created by henrytao on 2/17/16. */ public interface MVVMObserver { void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException; void addViewModel(MVVMViewModel viewModel);
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMObserver.java import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle; /** * Created by henrytao on 2/17/16. */ public interface MVVMObserver { void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException; void addViewModel(MVVMViewModel viewModel);
void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions);
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/local/LocalAdapter.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // }
import java.util.ArrayList; import java.util.List; import java.util.Locale; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import rx.Observable; import rx.subjects.PublishSubject;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.adapter.local; /** * Created by henrytao on 4/14/16. */ public class LocalAdapter implements me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter { private static final List<Task> sTasks = new ArrayList<>(); static { for (int i = 0; i < 5; i++) { sTasks.add(new Task(String.format(Locale.US, "task %d", i + 1), String.format(Locale.US, "description %d", i + 1))); } } private final PublishSubject<Task> mTaskCreatedSubject = PublishSubject.create(); private final PublishSubject<Task> mTaskRemovedSubject = PublishSubject.create(); private final PublishSubject<Task> mTaskUpdatedSubject = PublishSubject.create(); @Override
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/local/LocalAdapter.java import java.util.ArrayList; import java.util.List; import java.util.Locale; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import rx.Observable; import rx.subjects.PublishSubject; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.adapter.local; /** * Created by henrytao on 4/14/16. */ public class LocalAdapter implements me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter { private static final List<Task> sTasks = new ArrayList<>(); static { for (int i = 0; i < 5; i++) { sTasks.add(new Task(String.format(Locale.US, "task %d", i + 1), String.format(Locale.US, "description %d", i + 1))); } } private final PublishSubject<Task> mTaskCreatedSubject = PublishSubject.create(); private final PublishSubject<Task> mTaskRemovedSubject = PublishSubject.create(); private final PublishSubject<Task> mTaskUpdatedSubject = PublishSubject.create(); @Override
public void activeTask(String taskId) throws DataNotFoundException {
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/tasks/TaskItemViewHolder.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMObserver.java // public interface MVVMObserver { // // void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException; // // void addViewModel(MVVMViewModel viewModel); // // void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions); // // void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void onInitializeViewModels(); // // void unsubscribe(String id); // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/recyclerview/RecyclerViewBindingViewHolder.java // public abstract class RecyclerViewBindingViewHolder<D> extends RecyclerView.ViewHolder implements MVVMObserver { // // public abstract void bind(D data); // // protected MVVMObserver mObserver; // // /** // * This constructor should be extended and set proper layoutId // */ // public RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent) { // this(observer, parent, 0); // } // // protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, View view) { // super(view); // mObserver = observer; // onInitializeViewModels(); // } // // protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, @LayoutRes int layoutId) { // this(observer, parent, LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false)); // } // // @Override // public void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException { // throw new IllegalAccessException("This method should not be called"); // } // // @Override // public void addViewModel(MVVMViewModel viewModel) { // try { // mObserver.addAdapterViewModel(viewModel); // } catch (IllegalAccessException ignore) { // } // } // // @Override // public void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions) { // mObserver.manageSubscription(unsubscribeLifeCycle, subscriptions); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // mObserver.manageSubscription(id, subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // mObserver.manageSubscription(subscription, unsubscribeLifeCycle); // } // // @Override // public void unsubscribe(String id) { // mObserver.unsubscribe(id); // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // }
import android.databinding.DataBindingUtil; import android.view.ViewGroup; import me.henrytao.mvvmlifecycle.MVVMObserver; import me.henrytao.mvvmlifecycle.recyclerview.RecyclerViewBindingViewHolder; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.data.model.Task; import me.henrytao.mvvmlifecycledemo.databinding.TaskItemViewHolderBinding;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui.tasks; /** * Created by henrytao on 4/15/16. */ public class TaskItemViewHolder extends RecyclerViewBindingViewHolder<Task> { private final TaskItemViewHolderBinding mBinding; private TaskItemViewModel mViewModel;
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMObserver.java // public interface MVVMObserver { // // void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException; // // void addViewModel(MVVMViewModel viewModel); // // void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions); // // void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void onInitializeViewModels(); // // void unsubscribe(String id); // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/recyclerview/RecyclerViewBindingViewHolder.java // public abstract class RecyclerViewBindingViewHolder<D> extends RecyclerView.ViewHolder implements MVVMObserver { // // public abstract void bind(D data); // // protected MVVMObserver mObserver; // // /** // * This constructor should be extended and set proper layoutId // */ // public RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent) { // this(observer, parent, 0); // } // // protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, View view) { // super(view); // mObserver = observer; // onInitializeViewModels(); // } // // protected RecyclerViewBindingViewHolder(MVVMObserver observer, ViewGroup parent, @LayoutRes int layoutId) { // this(observer, parent, LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false)); // } // // @Override // public void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException { // throw new IllegalAccessException("This method should not be called"); // } // // @Override // public void addViewModel(MVVMViewModel viewModel) { // try { // mObserver.addAdapterViewModel(viewModel); // } catch (IllegalAccessException ignore) { // } // } // // @Override // public void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions) { // mObserver.manageSubscription(unsubscribeLifeCycle, subscriptions); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // mObserver.manageSubscription(id, subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // mObserver.manageSubscription(subscription, unsubscribeLifeCycle); // } // // @Override // public void unsubscribe(String id) { // mObserver.unsubscribe(id); // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/tasks/TaskItemViewHolder.java import android.databinding.DataBindingUtil; import android.view.ViewGroup; import me.henrytao.mvvmlifecycle.MVVMObserver; import me.henrytao.mvvmlifecycle.recyclerview.RecyclerViewBindingViewHolder; import me.henrytao.mvvmlifecycledemo.R; import me.henrytao.mvvmlifecycledemo.data.model.Task; import me.henrytao.mvvmlifecycledemo.databinding.TaskItemViewHolderBinding; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui.tasks; /** * Created by henrytao on 4/15/16. */ public class TaskItemViewHolder extends RecyclerViewBindingViewHolder<Task> { private final TaskItemViewHolderBinding mBinding; private TaskItemViewModel mViewModel;
public TaskItemViewHolder(MVVMObserver observer, ViewGroup parent) {
henrytao-me/mvvm-life-cycle
mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMFragment.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // }
import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle; /** * Created by henrytao on 11/10/15. * Reference: http://developer.android.com/guide/components/fragments.html */ public abstract class MVVMFragment extends android.support.v4.app.Fragment implements MVVMLifeCycle, MVVMObserver { public abstract View onInflateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState); protected List<MVVMViewModel> mViewModels = new ArrayList<>(); private List<MVVMViewModel> mAdapterViewModels = new ArrayList<>(); private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop; private Bundle mSavedInstanceState; private boolean mShouldRestoreInstanceState; private Constants.State mState;
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMFragment.java import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle; /** * Created by henrytao on 11/10/15. * Reference: http://developer.android.com/guide/components/fragments.html */ public abstract class MVVMFragment extends android.support.v4.app.Fragment implements MVVMLifeCycle, MVVMObserver { public abstract View onInflateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState); protected List<MVVMViewModel> mViewModels = new ArrayList<>(); private List<MVVMViewModel> mAdapterViewModels = new ArrayList<>(); private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop; private Bundle mSavedInstanceState; private boolean mShouldRestoreInstanceState; private Constants.State mState;
private SubscriptionManager mSubscriptionManager = new SubscriptionManager();
henrytao-me/mvvm-life-cycle
mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMFragment.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // }
import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle; /** * Created by henrytao on 11/10/15. * Reference: http://developer.android.com/guide/components/fragments.html */ public abstract class MVVMFragment extends android.support.v4.app.Fragment implements MVVMLifeCycle, MVVMObserver { public abstract View onInflateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState); protected List<MVVMViewModel> mViewModels = new ArrayList<>(); private List<MVVMViewModel> mAdapterViewModels = new ArrayList<>(); private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop; private Bundle mSavedInstanceState; private boolean mShouldRestoreInstanceState; private Constants.State mState; private SubscriptionManager mSubscriptionManager = new SubscriptionManager(); @Override public void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException { addViewModel(viewModel); if (!mAdapterViewModels.contains(viewModel)) { mAdapterViewModels.add(viewModel); } throw new IllegalAccessException("This method should be used with care"); } @Override public void addViewModel(MVVMViewModel viewModel) { if (!mViewModels.contains(viewModel)) { mViewModels.add(viewModel); propagateLifeCycle(viewModel); } } @Override
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMFragment.java import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle; /** * Created by henrytao on 11/10/15. * Reference: http://developer.android.com/guide/components/fragments.html */ public abstract class MVVMFragment extends android.support.v4.app.Fragment implements MVVMLifeCycle, MVVMObserver { public abstract View onInflateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState); protected List<MVVMViewModel> mViewModels = new ArrayList<>(); private List<MVVMViewModel> mAdapterViewModels = new ArrayList<>(); private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop; private Bundle mSavedInstanceState; private boolean mShouldRestoreInstanceState; private Constants.State mState; private SubscriptionManager mSubscriptionManager = new SubscriptionManager(); @Override public void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException { addViewModel(viewModel); if (!mAdapterViewModels.contains(viewModel)) { mAdapterViewModels.add(viewModel); } throw new IllegalAccessException("This method should be used with care"); } @Override public void addViewModel(MVVMViewModel viewModel) { if (!mViewModels.contains(viewModel)) { mViewModels.add(viewModel); propagateLifeCycle(viewModel); } } @Override
public void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions) {
henrytao-me/mvvm-life-cycle
mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMActivity.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // }
import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle; /** * Created by henrytao on 11/10/15. * Reference: http://developer.android.com/training/basics/activity-lifecycle/starting.html */ public abstract class MVVMActivity extends AppCompatActivity implements MVVMLifeCycle, MVVMObserver { public abstract void onSetContentView(Bundle savedInstanceState); protected List<MVVMViewModel> mViewModels = new ArrayList<>(); private List<MVVMViewModel> mAdapterViewModels = new ArrayList<>(); private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop; private Constants.State mState;
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMActivity.java import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle; /** * Created by henrytao on 11/10/15. * Reference: http://developer.android.com/training/basics/activity-lifecycle/starting.html */ public abstract class MVVMActivity extends AppCompatActivity implements MVVMLifeCycle, MVVMObserver { public abstract void onSetContentView(Bundle savedInstanceState); protected List<MVVMViewModel> mViewModels = new ArrayList<>(); private List<MVVMViewModel> mAdapterViewModels = new ArrayList<>(); private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop; private Constants.State mState;
private SubscriptionManager mSubscriptionManager = new SubscriptionManager();
henrytao-me/mvvm-life-cycle
mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMActivity.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // }
import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle; /** * Created by henrytao on 11/10/15. * Reference: http://developer.android.com/training/basics/activity-lifecycle/starting.html */ public abstract class MVVMActivity extends AppCompatActivity implements MVVMLifeCycle, MVVMObserver { public abstract void onSetContentView(Bundle savedInstanceState); protected List<MVVMViewModel> mViewModels = new ArrayList<>(); private List<MVVMViewModel> mAdapterViewModels = new ArrayList<>(); private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop; private Constants.State mState; private SubscriptionManager mSubscriptionManager = new SubscriptionManager(); @Override public void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException { addViewModel(viewModel); if (!mAdapterViewModels.contains(viewModel)) { mAdapterViewModels.add(viewModel); } throw new IllegalAccessException("This method should be used with care"); } @Override public void addViewModel(MVVMViewModel viewModel) { if (!mViewModels.contains(viewModel)) { mViewModels.add(viewModel); propagateLifeCycle(viewModel); } } @Override
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/SubscriptionManager.java // public class SubscriptionManager implements ISubscriptionManager { // // private Map<UnsubscribeLifeCycle, Map<String, Subscription>> mSubscriptions; // // public SubscriptionManager() { // mSubscriptions = new HashMap<>(); // } // // @Override // public void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // manageSubscription(UUID.randomUUID().toString(), subscription, unsubscribeLifeCycle); // } // // @Override // public void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = getSubscriptions(unsubscribeLifeCycle); // if (subscriptions.containsKey(id)) { // unsubscribe(id); // } // subscriptions.put(id, subscription); // } // // @Override // public void unsubscribe(UnsubscribeLifeCycle unsubscribeLifeCycle) { // unsubscribe(getSubscriptions(unsubscribeLifeCycle)); // } // // @Override // public void unsubscribe() { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // mSubscriptions.clear(); // } // // @Override // public void unsubscribe(String id) { // for (Map.Entry<UnsubscribeLifeCycle, Map<String, Subscription>> entry : mSubscriptions.entrySet()) { // unsubscribe(entry.getValue().get(id)); // } // } // // private Map<String, Subscription> getSubscriptions(UnsubscribeLifeCycle unsubscribeLifeCycle) { // Map<String, Subscription> subscriptions = mSubscriptions.get(unsubscribeLifeCycle); // if (subscriptions == null) { // subscriptions = new HashMap<>(); // mSubscriptions.put(unsubscribeLifeCycle, subscriptions); // } // return subscriptions; // } // // private void unsubscribe(Map<String, Subscription> subscriptions) { // for (Map.Entry<String, Subscription> entry : subscriptions.entrySet()) { // unsubscribe(entry.getValue()); // } // subscriptions.clear(); // } // // private void unsubscribe(Subscription subscription) { // if (subscription != null && !subscription.isUnsubscribed()) { // subscription.unsubscribe(); // } // } // } // // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/rx/UnsubscribeLifeCycle.java // public enum UnsubscribeLifeCycle { // PAUSE, // STOP, // DESTROY_VIEW, // DESTROY // } // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMActivity.java import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; import me.henrytao.mvvmlifecycle.rx.SubscriptionManager; import me.henrytao.mvvmlifecycle.rx.UnsubscribeLifeCycle; import rx.Subscription; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle; /** * Created by henrytao on 11/10/15. * Reference: http://developer.android.com/training/basics/activity-lifecycle/starting.html */ public abstract class MVVMActivity extends AppCompatActivity implements MVVMLifeCycle, MVVMObserver { public abstract void onSetContentView(Bundle savedInstanceState); protected List<MVVMViewModel> mViewModels = new ArrayList<>(); private List<MVVMViewModel> mAdapterViewModels = new ArrayList<>(); private boolean mIsDestroy; private boolean mIsDestroyView; private boolean mIsPause; private boolean mIsStop; private Constants.State mState; private SubscriptionManager mSubscriptionManager = new SubscriptionManager(); @Override public void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException { addViewModel(viewModel); if (!mAdapterViewModels.contains(viewModel)) { mAdapterViewModels.add(viewModel); } throw new IllegalAccessException("This method should be used with care"); } @Override public void addViewModel(MVVMViewModel viewModel) { if (!mViewModels.contains(viewModel)) { mViewModels.add(viewModel); propagateLifeCycle(viewModel); } } @Override
public void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions) {
henrytao-me/mvvm-life-cycle
mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/recyclerview/RecyclerViewBindingAdapter.java
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMObserver.java // public interface MVVMObserver { // // void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException; // // void addViewModel(MVVMViewModel viewModel); // // void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions); // // void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void onInitializeViewModels(); // // void unsubscribe(String id); // }
import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import java.lang.reflect.InvocationTargetException; import java.util.List; import me.henrytao.mvvmlifecycle.MVVMObserver;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle.recyclerview; /** * Created by henrytao on 4/15/16. */ public class RecyclerViewBindingAdapter<D, V extends RecyclerViewBindingViewHolder<D>> extends RecyclerView.Adapter<V> { protected final List<D> mData;
// Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/MVVMObserver.java // public interface MVVMObserver { // // void addAdapterViewModel(MVVMViewModel viewModel) throws IllegalAccessException; // // void addViewModel(MVVMViewModel viewModel); // // void manageSubscription(UnsubscribeLifeCycle unsubscribeLifeCycle, Subscription... subscriptions); // // void manageSubscription(String id, Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void manageSubscription(Subscription subscription, UnsubscribeLifeCycle unsubscribeLifeCycle); // // void onInitializeViewModels(); // // void unsubscribe(String id); // } // Path: mvvm-life-cycle/src/main/java/me/henrytao/mvvmlifecycle/recyclerview/RecyclerViewBindingAdapter.java import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import java.lang.reflect.InvocationTargetException; import java.util.List; import me.henrytao.mvvmlifecycle.MVVMObserver; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycle.recyclerview; /** * Created by henrytao on 4/15/16. */ public class RecyclerViewBindingAdapter<D, V extends RecyclerViewBindingViewHolder<D>> extends RecyclerView.Adapter<V> { protected final List<D> mData;
protected final MVVMObserver mObserver;
henrytao-me/mvvm-life-cycle
sample/src/test/java/me/henrytao/mvvmlifecycledemo/data/adapter/local/LocalAdapterTest.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java // public class BaseTest { // // @Before // public void initialize() { // MockitoAnnotations.initMocks(this); // Transformer.overrideComputationScheduler(Schedulers.immediate()); // Transformer.overrideIoScheduler(Schedulers.immediate()); // Transformer.overrideMainThreadScheduler(Schedulers.immediate()); // Transformer.overrideNewThreadScheduler(Schedulers.immediate()); // } // // @After // public void release() { // Transformer.resetComputationScheduler(); // Transformer.resetIoScheduler(); // Transformer.resetMainThreadScheduler(); // Transformer.resetNewThreadScheduler(); // } // }
import org.junit.Test; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import me.henrytao.mvvmlifecycledemo.util.BaseTest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.adapter.local; /** * Created by henrytao on 4/22/16. */ public class LocalAdapterTest extends BaseTest { private LocalAdapter mLocalAdapter; @Override public void initialize() { super.initialize(); mLocalAdapter = spy(new LocalAdapter()); }
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java // public class BaseTest { // // @Before // public void initialize() { // MockitoAnnotations.initMocks(this); // Transformer.overrideComputationScheduler(Schedulers.immediate()); // Transformer.overrideIoScheduler(Schedulers.immediate()); // Transformer.overrideMainThreadScheduler(Schedulers.immediate()); // Transformer.overrideNewThreadScheduler(Schedulers.immediate()); // } // // @After // public void release() { // Transformer.resetComputationScheduler(); // Transformer.resetIoScheduler(); // Transformer.resetMainThreadScheduler(); // Transformer.resetNewThreadScheduler(); // } // } // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/data/adapter/local/LocalAdapterTest.java import org.junit.Test; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import me.henrytao.mvvmlifecycledemo.util.BaseTest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.adapter.local; /** * Created by henrytao on 4/22/16. */ public class LocalAdapterTest extends BaseTest { private LocalAdapter mLocalAdapter; @Override public void initialize() { super.initialize(); mLocalAdapter = spy(new LocalAdapter()); }
@Test(expected = DataNotFoundException.class)
henrytao-me/mvvm-life-cycle
sample/src/test/java/me/henrytao/mvvmlifecycledemo/data/adapter/local/LocalAdapterTest.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java // public class BaseTest { // // @Before // public void initialize() { // MockitoAnnotations.initMocks(this); // Transformer.overrideComputationScheduler(Schedulers.immediate()); // Transformer.overrideIoScheduler(Schedulers.immediate()); // Transformer.overrideMainThreadScheduler(Schedulers.immediate()); // Transformer.overrideNewThreadScheduler(Schedulers.immediate()); // } // // @After // public void release() { // Transformer.resetComputationScheduler(); // Transformer.resetIoScheduler(); // Transformer.resetMainThreadScheduler(); // Transformer.resetNewThreadScheduler(); // } // }
import org.junit.Test; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import me.henrytao.mvvmlifecycledemo.util.BaseTest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.adapter.local; /** * Created by henrytao on 4/22/16. */ public class LocalAdapterTest extends BaseTest { private LocalAdapter mLocalAdapter; @Override public void initialize() { super.initialize(); mLocalAdapter = spy(new LocalAdapter()); } @Test(expected = DataNotFoundException.class) public void testActiveTaskError() throws Exception { doReturn(null).when(mLocalAdapter).findTask(any()); mLocalAdapter.activeTask("taskId"); } @Test public void testActiveTaskSuccess() throws Exception {
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/util/BaseTest.java // public class BaseTest { // // @Before // public void initialize() { // MockitoAnnotations.initMocks(this); // Transformer.overrideComputationScheduler(Schedulers.immediate()); // Transformer.overrideIoScheduler(Schedulers.immediate()); // Transformer.overrideMainThreadScheduler(Schedulers.immediate()); // Transformer.overrideNewThreadScheduler(Schedulers.immediate()); // } // // @After // public void release() { // Transformer.resetComputationScheduler(); // Transformer.resetIoScheduler(); // Transformer.resetMainThreadScheduler(); // Transformer.resetNewThreadScheduler(); // } // } // Path: sample/src/test/java/me/henrytao/mvvmlifecycledemo/data/adapter/local/LocalAdapterTest.java import org.junit.Test; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import me.henrytao.mvvmlifecycledemo.util.BaseTest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.adapter.local; /** * Created by henrytao on 4/22/16. */ public class LocalAdapterTest extends BaseTest { private LocalAdapter mLocalAdapter; @Override public void initialize() { super.initialize(); mLocalAdapter = spy(new LocalAdapter()); } @Test(expected = DataNotFoundException.class) public void testActiveTaskError() throws Exception { doReturn(null).when(mLocalAdapter).findTask(any()); mLocalAdapter.activeTask("taskId"); } @Test public void testActiveTaskSuccess() throws Exception {
Task task = new Task("title", "description");
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/di/AdapterModule.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // }
import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.di; /** * Created by henrytao on 4/15/16. */ @Module public class AdapterModule { @Singleton @Provides
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java // public interface LocalAdapter { // // void activeTask(String taskId) throws DataNotFoundException; // // void completeTask(String taskId) throws DataNotFoundException; // // Task createTask(String title, String description); // // Task findTask(String taskId); // // List<Task> getTasks(); // // Observable<Task> observeTaskCreate(); // // Observable<Task> observeTaskRemove(); // // Observable<Task> observeTaskUpdate(); // // void removeTask(String taskId) throws DataNotFoundException; // // void updateTask(String taskId, String title, String description) throws DataNotFoundException; // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/di/AdapterModule.java import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import me.henrytao.mvvmlifecycledemo.data.adapter.LocalAdapter; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.di; /** * Created by henrytao on 4/15/16. */ @Module public class AdapterModule { @Singleton @Provides
LocalAdapter provideLocalAdapter() {
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/tasks/TaskItemViewModel.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseViewModel.java // public abstract class BaseViewModel<T> extends MVVMViewModel<T> { // // }
import android.databinding.ObservableBoolean; import android.databinding.ObservableField; import me.henrytao.mvvmlifecycledemo.data.model.Task; import me.henrytao.mvvmlifecycledemo.ui.base.BaseViewModel;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui.tasks; /** * Created by henrytao on 4/15/16. */ public class TaskItemViewModel extends BaseViewModel { public ObservableBoolean completed = new ObservableBoolean(); public ObservableField<String> description = new ObservableField<>(); public ObservableField<String> title = new ObservableField<>();
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/base/BaseViewModel.java // public abstract class BaseViewModel<T> extends MVVMViewModel<T> { // // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/ui/tasks/TaskItemViewModel.java import android.databinding.ObservableBoolean; import android.databinding.ObservableField; import me.henrytao.mvvmlifecycledemo.data.model.Task; import me.henrytao.mvvmlifecycledemo.ui.base.BaseViewModel; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.ui.tasks; /** * Created by henrytao on 4/15/16. */ public class TaskItemViewModel extends BaseViewModel { public ObservableBoolean completed = new ObservableBoolean(); public ObservableField<String> description = new ObservableField<>(); public ObservableField<String> title = new ObservableField<>();
private Task mTask;
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/App.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/di/Injector.java // public class Injector { // // public static AppComponent component; // // public static AppComponent initialize(Application application) { // component = AppBuilder.build(application); // return component; // } // }
import android.app.Application; import me.henrytao.mvvmlifecycledemo.di.Injector;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo; /** * Created by henrytao on 4/14/16. */ public class App extends Application { private static App sApp; public static App getInstance() { return sApp; } @Override public void onCreate() { super.onCreate(); sApp = this;
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/di/Injector.java // public class Injector { // // public static AppComponent component; // // public static AppComponent initialize(Application application) { // component = AppBuilder.build(application); // return component; // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/App.java import android.app.Application; import me.henrytao.mvvmlifecycledemo.di.Injector; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo; /** * Created by henrytao on 4/14/16. */ public class App extends Application { private static App sApp; public static App getInstance() { return sApp; } @Override public void onCreate() { super.onCreate(); sApp = this;
Injector.initialize(this);
henrytao-me/mvvm-life-cycle
sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // }
import java.util.List; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import rx.Observable;
/* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.adapter; /** * Created by henrytao on 4/14/16. */ public interface LocalAdapter { void activeTask(String taskId) throws DataNotFoundException; void completeTask(String taskId) throws DataNotFoundException;
// Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/exception/DataNotFoundException.java // public class DataNotFoundException extends Exception { // // } // // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/model/Task.java // public class Task { // // private boolean mCompleted; // // private String mDescription; // // private String mId; // // private String mTitle; // // public Task(String id, String title, String description) { // mId = id; // mTitle = title; // mDescription = description; // } // // protected Task(String id, String title, String description, boolean completed) { // mId = id; // mTitle = title; // mDescription = description; // mCompleted = completed; // } // // public Task(String title, String description) { // this(UUID.randomUUID().toString(), title, description); // } // // @Override // public int hashCode() { // return Objects.hashCode(mId, mTitle, mDescription, mCompleted); // } // // public void active() { // mCompleted = false; // } // // public void complete() { // mCompleted = true; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getId() { // return mId; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public boolean isActive() { // return !isCompleted(); // } // // public boolean isCompleted() { // return mCompleted; // } // // public void setCompleted(boolean completed) { // mCompleted = completed; // } // } // Path: sample/src/main/java/me/henrytao/mvvmlifecycledemo/data/adapter/LocalAdapter.java import java.util.List; import me.henrytao.mvvmlifecycledemo.data.exception.DataNotFoundException; import me.henrytao.mvvmlifecycledemo.data.model.Task; import rx.Observable; /* * Copyright 2016 "Henry Tao <hi@henrytao.me>" * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.henrytao.mvvmlifecycledemo.data.adapter; /** * Created by henrytao on 4/14/16. */ public interface LocalAdapter { void activeTask(String taskId) throws DataNotFoundException; void completeTask(String taskId) throws DataNotFoundException;
Task createTask(String title, String description);
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/wire/GoUserEncoder.java
// Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public class Json { // private static Gson gson = new Gson(); // // public static Map<String, String> toMapOfStrings(String jsonValue) { // Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType(); // return gson.fromJson(jsonValue, mapOfStringToStringType); // } // // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // public static String toJson(Object anything) { // return gson.toJson(anything); // } // }
import com.google.common.collect.ImmutableMap; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.Json;
package com.thoughtworks.go.strongauth.wire; public class GoUserEncoder { public GoPluginApiResponse encode(final String username) { final DefaultGoPluginApiResponse response = new DefaultGoPluginApiResponse(200); final ImmutableMap<String, ImmutableMap<String, String>> map = ImmutableMap.of("user", ImmutableMap.of("username", username));
// Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public class Json { // private static Gson gson = new Gson(); // // public static Map<String, String> toMapOfStrings(String jsonValue) { // Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType(); // return gson.fromJson(jsonValue, mapOfStringToStringType); // } // // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // public static String toJson(Object anything) { // return gson.toJson(anything); // } // } // Path: src/main/java/com/thoughtworks/go/strongauth/wire/GoUserEncoder.java import com.google.common.collect.ImmutableMap; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.Json; package com.thoughtworks.go.strongauth.wire; public class GoUserEncoder { public GoPluginApiResponse encode(final String username) { final DefaultGoPluginApiResponse response = new DefaultGoPluginApiResponse(200); final ImmutableMap<String, ImmutableMap<String, String>> map = ImmutableMap.of("user", ImmutableMap.of("username", username));
response.setResponseBody(Json.toJson(map));
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/authentication/hash/PBESpecHashProvider.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/HashProvider.java // public interface HashProvider { // boolean validateHash(final String password, final PrincipalDetail principalDetail); // // boolean canHandle(String hashConfig); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java // @Value // public class PrincipalDetail { // private final String username; // private final String passwordHash; // private final String salt; // private final String hashConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // // Path: src/main/java/com/thoughtworks/util/Functional.java // public static <T, U> Optional<U> flatMap(Optional<? extends T> maybeValue, final Function<T, Optional<U>> transformation) { // return maybeValue.isPresent() ? transformation.apply(maybeValue.get()) : Optional.<U>absent(); // }
import com.google.common.base.Function; import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.strongauth.authentication.HashProvider; import com.thoughtworks.go.strongauth.authentication.PrincipalDetail; import com.thoughtworks.go.strongauth.util.Constants; import lombok.Value; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.thoughtworks.util.Functional.flatMap; import static java.lang.Integer.parseInt;
package com.thoughtworks.go.strongauth.authentication.hash; public class PBESpecHashProvider implements HashProvider { public final String pluginId = Constants.PLUGIN_ID; private static final Logger LOGGER = Logger.getLoggerFor(PBESpecHashProvider.class); private static final Pattern HASH_CONFIG_PATTERN = Pattern.compile("^(\\w+)\\((\\d+), (\\d+)\\)$"); @Override
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/HashProvider.java // public interface HashProvider { // boolean validateHash(final String password, final PrincipalDetail principalDetail); // // boolean canHandle(String hashConfig); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java // @Value // public class PrincipalDetail { // private final String username; // private final String passwordHash; // private final String salt; // private final String hashConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // // Path: src/main/java/com/thoughtworks/util/Functional.java // public static <T, U> Optional<U> flatMap(Optional<? extends T> maybeValue, final Function<T, Optional<U>> transformation) { // return maybeValue.isPresent() ? transformation.apply(maybeValue.get()) : Optional.<U>absent(); // } // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/hash/PBESpecHashProvider.java import com.google.common.base.Function; import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.strongauth.authentication.HashProvider; import com.thoughtworks.go.strongauth.authentication.PrincipalDetail; import com.thoughtworks.go.strongauth.util.Constants; import lombok.Value; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.thoughtworks.util.Functional.flatMap; import static java.lang.Integer.parseInt; package com.thoughtworks.go.strongauth.authentication.hash; public class PBESpecHashProvider implements HashProvider { public final String pluginId = Constants.PLUGIN_ID; private static final Logger LOGGER = Logger.getLoggerFor(PBESpecHashProvider.class); private static final Pattern HASH_CONFIG_PATTERN = Pattern.compile("^(\\w+)\\((\\d+), (\\d+)\\)$"); @Override
public boolean validateHash(final String password, final PrincipalDetail principalDetail) {
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/handlers/PluginSettingsHandler.java
// Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public class MapBuilder<K, V> { // private final HashMap<K, V> map; // // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // private MapBuilder() { // map = new HashMap<>(); // } // // public MapBuilder<K, V> add(K initialKey, V valueForInitialKey) { // map.put(initialKey, valueForInitialKey); // return this; // } // // public Map<K, V> build() { // return map; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Resources.java // public static String get(String resourceLocation) { // try { // return IOUtils.toString(Resources.class.getResourceAsStream(resourceLocation), "UTF-8"); // } catch (Exception e) { // throw new RuntimeException("Failed to get template from " + resourceLocation); // } // }
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.MapBuilder; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.Json.toMap; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; import static com.thoughtworks.go.strongauth.util.Resources.get;
package com.thoughtworks.go.strongauth.handlers; public class PluginSettingsHandler { public static final String PLUGIN_CONFIG_PASSWORD_FILE_PATH = "PASSWORD_FILE_PATH"; public static final String DISPLAY_NAME_PASSWORD_FILE_PATH = "Password file path"; public static Handler getConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) {
// Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public class MapBuilder<K, V> { // private final HashMap<K, V> map; // // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // private MapBuilder() { // map = new HashMap<>(); // } // // public MapBuilder<K, V> add(K initialKey, V valueForInitialKey) { // map.put(initialKey, valueForInitialKey); // return this; // } // // public Map<K, V> build() { // return map; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Resources.java // public static String get(String resourceLocation) { // try { // return IOUtils.toString(Resources.class.getResourceAsStream(resourceLocation), "UTF-8"); // } catch (Exception e) { // throw new RuntimeException("Failed to get template from " + resourceLocation); // } // } // Path: src/main/java/com/thoughtworks/go/strongauth/handlers/PluginSettingsHandler.java import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.MapBuilder; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.Json.toMap; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; import static com.thoughtworks.go.strongauth.util.Resources.get; package com.thoughtworks.go.strongauth.handlers; public class PluginSettingsHandler { public static final String PLUGIN_CONFIG_PASSWORD_FILE_PATH = "PASSWORD_FILE_PATH"; public static final String DISPLAY_NAME_PASSWORD_FILE_PATH = "Password file path"; public static Handler getConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) {
Map<Object, Object> configResponse = create()
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/handlers/PluginSettingsHandler.java
// Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public class MapBuilder<K, V> { // private final HashMap<K, V> map; // // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // private MapBuilder() { // map = new HashMap<>(); // } // // public MapBuilder<K, V> add(K initialKey, V valueForInitialKey) { // map.put(initialKey, valueForInitialKey); // return this; // } // // public Map<K, V> build() { // return map; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Resources.java // public static String get(String resourceLocation) { // try { // return IOUtils.toString(Resources.class.getResourceAsStream(resourceLocation), "UTF-8"); // } catch (Exception e) { // throw new RuntimeException("Failed to get template from " + resourceLocation); // } // }
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.MapBuilder; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.Json.toMap; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; import static com.thoughtworks.go.strongauth.util.Resources.get;
package com.thoughtworks.go.strongauth.handlers; public class PluginSettingsHandler { public static final String PLUGIN_CONFIG_PASSWORD_FILE_PATH = "PASSWORD_FILE_PATH"; public static final String DISPLAY_NAME_PASSWORD_FILE_PATH = "Password file path"; public static Handler getConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Map<Object, Object> configResponse = create() .add(PLUGIN_CONFIG_PASSWORD_FILE_PATH, create() .add("display-name", DISPLAY_NAME_PASSWORD_FILE_PATH) .add("required", true)) .build();
// Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public class MapBuilder<K, V> { // private final HashMap<K, V> map; // // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // private MapBuilder() { // map = new HashMap<>(); // } // // public MapBuilder<K, V> add(K initialKey, V valueForInitialKey) { // map.put(initialKey, valueForInitialKey); // return this; // } // // public Map<K, V> build() { // return map; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Resources.java // public static String get(String resourceLocation) { // try { // return IOUtils.toString(Resources.class.getResourceAsStream(resourceLocation), "UTF-8"); // } catch (Exception e) { // throw new RuntimeException("Failed to get template from " + resourceLocation); // } // } // Path: src/main/java/com/thoughtworks/go/strongauth/handlers/PluginSettingsHandler.java import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.MapBuilder; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.Json.toMap; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; import static com.thoughtworks.go.strongauth.util.Resources.get; package com.thoughtworks.go.strongauth.handlers; public class PluginSettingsHandler { public static final String PLUGIN_CONFIG_PASSWORD_FILE_PATH = "PASSWORD_FILE_PATH"; public static final String DISPLAY_NAME_PASSWORD_FILE_PATH = "Password file path"; public static Handler getConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Map<Object, Object> configResponse = create() .add(PLUGIN_CONFIG_PASSWORD_FILE_PATH, create() .add("display-name", DISPLAY_NAME_PASSWORD_FILE_PATH) .add("required", true)) .build();
return DefaultGoPluginApiResponse.success(toJson(configResponse));
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/handlers/PluginSettingsHandler.java
// Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public class MapBuilder<K, V> { // private final HashMap<K, V> map; // // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // private MapBuilder() { // map = new HashMap<>(); // } // // public MapBuilder<K, V> add(K initialKey, V valueForInitialKey) { // map.put(initialKey, valueForInitialKey); // return this; // } // // public Map<K, V> build() { // return map; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Resources.java // public static String get(String resourceLocation) { // try { // return IOUtils.toString(Resources.class.getResourceAsStream(resourceLocation), "UTF-8"); // } catch (Exception e) { // throw new RuntimeException("Failed to get template from " + resourceLocation); // } // }
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.MapBuilder; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.Json.toMap; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; import static com.thoughtworks.go.strongauth.util.Resources.get;
package com.thoughtworks.go.strongauth.handlers; public class PluginSettingsHandler { public static final String PLUGIN_CONFIG_PASSWORD_FILE_PATH = "PASSWORD_FILE_PATH"; public static final String DISPLAY_NAME_PASSWORD_FILE_PATH = "Password file path"; public static Handler getConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Map<Object, Object> configResponse = create() .add(PLUGIN_CONFIG_PASSWORD_FILE_PATH, create() .add("display-name", DISPLAY_NAME_PASSWORD_FILE_PATH) .add("required", true)) .build(); return DefaultGoPluginApiResponse.success(toJson(configResponse)); } }; } public static Handler getView() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) {
// Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public class MapBuilder<K, V> { // private final HashMap<K, V> map; // // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // private MapBuilder() { // map = new HashMap<>(); // } // // public MapBuilder<K, V> add(K initialKey, V valueForInitialKey) { // map.put(initialKey, valueForInitialKey); // return this; // } // // public Map<K, V> build() { // return map; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Resources.java // public static String get(String resourceLocation) { // try { // return IOUtils.toString(Resources.class.getResourceAsStream(resourceLocation), "UTF-8"); // } catch (Exception e) { // throw new RuntimeException("Failed to get template from " + resourceLocation); // } // } // Path: src/main/java/com/thoughtworks/go/strongauth/handlers/PluginSettingsHandler.java import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.MapBuilder; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.Json.toMap; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; import static com.thoughtworks.go.strongauth.util.Resources.get; package com.thoughtworks.go.strongauth.handlers; public class PluginSettingsHandler { public static final String PLUGIN_CONFIG_PASSWORD_FILE_PATH = "PASSWORD_FILE_PATH"; public static final String DISPLAY_NAME_PASSWORD_FILE_PATH = "Password file path"; public static Handler getConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Map<Object, Object> configResponse = create() .add(PLUGIN_CONFIG_PASSWORD_FILE_PATH, create() .add("display-name", DISPLAY_NAME_PASSWORD_FILE_PATH) .add("required", true)) .build(); return DefaultGoPluginApiResponse.success(toJson(configResponse)); } }; } public static Handler getView() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) {
Object viewResponse = create().add("template", get("/plugin-settings.template.html")).build();
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/handlers/PluginSettingsHandler.java
// Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public class MapBuilder<K, V> { // private final HashMap<K, V> map; // // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // private MapBuilder() { // map = new HashMap<>(); // } // // public MapBuilder<K, V> add(K initialKey, V valueForInitialKey) { // map.put(initialKey, valueForInitialKey); // return this; // } // // public Map<K, V> build() { // return map; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Resources.java // public static String get(String resourceLocation) { // try { // return IOUtils.toString(Resources.class.getResourceAsStream(resourceLocation), "UTF-8"); // } catch (Exception e) { // throw new RuntimeException("Failed to get template from " + resourceLocation); // } // }
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.MapBuilder; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.Json.toMap; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; import static com.thoughtworks.go.strongauth.util.Resources.get;
package com.thoughtworks.go.strongauth.handlers; public class PluginSettingsHandler { public static final String PLUGIN_CONFIG_PASSWORD_FILE_PATH = "PASSWORD_FILE_PATH"; public static final String DISPLAY_NAME_PASSWORD_FILE_PATH = "Password file path"; public static Handler getConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Map<Object, Object> configResponse = create() .add(PLUGIN_CONFIG_PASSWORD_FILE_PATH, create() .add("display-name", DISPLAY_NAME_PASSWORD_FILE_PATH) .add("required", true)) .build(); return DefaultGoPluginApiResponse.success(toJson(configResponse)); } }; } public static Handler getView() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Object viewResponse = create().add("template", get("/plugin-settings.template.html")).build(); return DefaultGoPluginApiResponse.success(toJson(viewResponse)); } }; } /* Called upon save of the plugin settings in the UI. */ public static Handler validateConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) {
// Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public class MapBuilder<K, V> { // private final HashMap<K, V> map; // // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // private MapBuilder() { // map = new HashMap<>(); // } // // public MapBuilder<K, V> add(K initialKey, V valueForInitialKey) { // map.put(initialKey, valueForInitialKey); // return this; // } // // public Map<K, V> build() { // return map; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Resources.java // public static String get(String resourceLocation) { // try { // return IOUtils.toString(Resources.class.getResourceAsStream(resourceLocation), "UTF-8"); // } catch (Exception e) { // throw new RuntimeException("Failed to get template from " + resourceLocation); // } // } // Path: src/main/java/com/thoughtworks/go/strongauth/handlers/PluginSettingsHandler.java import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.MapBuilder; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.Json.toMap; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; import static com.thoughtworks.go.strongauth.util.Resources.get; package com.thoughtworks.go.strongauth.handlers; public class PluginSettingsHandler { public static final String PLUGIN_CONFIG_PASSWORD_FILE_PATH = "PASSWORD_FILE_PATH"; public static final String DISPLAY_NAME_PASSWORD_FILE_PATH = "Password file path"; public static Handler getConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Map<Object, Object> configResponse = create() .add(PLUGIN_CONFIG_PASSWORD_FILE_PATH, create() .add("display-name", DISPLAY_NAME_PASSWORD_FILE_PATH) .add("required", true)) .build(); return DefaultGoPluginApiResponse.success(toJson(configResponse)); } }; } public static Handler getView() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Object viewResponse = create().add("template", get("/plugin-settings.template.html")).build(); return DefaultGoPluginApiResponse.success(toJson(viewResponse)); } }; } /* Called upon save of the plugin settings in the UI. */ public static Handler validateConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) {
final Map<String, Map<String, String>> settings = (Map<String, Map<String, String>>) toMap(request.requestBody()).get("plugin-settings");
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/handlers/PluginSettingsHandler.java
// Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public class MapBuilder<K, V> { // private final HashMap<K, V> map; // // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // private MapBuilder() { // map = new HashMap<>(); // } // // public MapBuilder<K, V> add(K initialKey, V valueForInitialKey) { // map.put(initialKey, valueForInitialKey); // return this; // } // // public Map<K, V> build() { // return map; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Resources.java // public static String get(String resourceLocation) { // try { // return IOUtils.toString(Resources.class.getResourceAsStream(resourceLocation), "UTF-8"); // } catch (Exception e) { // throw new RuntimeException("Failed to get template from " + resourceLocation); // } // }
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.MapBuilder; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.Json.toMap; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; import static com.thoughtworks.go.strongauth.util.Resources.get;
package com.thoughtworks.go.strongauth.handlers; public class PluginSettingsHandler { public static final String PLUGIN_CONFIG_PASSWORD_FILE_PATH = "PASSWORD_FILE_PATH"; public static final String DISPLAY_NAME_PASSWORD_FILE_PATH = "Password file path"; public static Handler getConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Map<Object, Object> configResponse = create() .add(PLUGIN_CONFIG_PASSWORD_FILE_PATH, create() .add("display-name", DISPLAY_NAME_PASSWORD_FILE_PATH) .add("required", true)) .build(); return DefaultGoPluginApiResponse.success(toJson(configResponse)); } }; } public static Handler getView() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Object viewResponse = create().add("template", get("/plugin-settings.template.html")).build(); return DefaultGoPluginApiResponse.success(toJson(viewResponse)); } }; } /* Called upon save of the plugin settings in the UI. */ public static Handler validateConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { final Map<String, Map<String, String>> settings = (Map<String, Map<String, String>>) toMap(request.requestBody()).get("plugin-settings"); final List<Map<Object, Object>> validationResponse = new ArrayList<>(); if (isEmpty(settings, PLUGIN_CONFIG_PASSWORD_FILE_PATH)) { addValidationError(validationResponse, PLUGIN_CONFIG_PASSWORD_FILE_PATH, "Password file path"); } return DefaultGoPluginApiResponse.success(toJson(validationResponse)); } private boolean isEmpty(Map<String, Map<String, String>> settings, String key) { return !settings.containsKey(key) || settings.get(key) == null || settings.get(key).get("value") == null || "".equals(settings.get(key).get("value").trim()); } private void addValidationError(List<Map<Object, Object>> validationResponse, String key, String userReadableMessagePrefix) { String message = userReadableMessagePrefix + " is required and should not be empty";
// Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public class MapBuilder<K, V> { // private final HashMap<K, V> map; // // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // private MapBuilder() { // map = new HashMap<>(); // } // // public MapBuilder<K, V> add(K initialKey, V valueForInitialKey) { // map.put(initialKey, valueForInitialKey); // return this; // } // // public Map<K, V> build() { // return map; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Resources.java // public static String get(String resourceLocation) { // try { // return IOUtils.toString(Resources.class.getResourceAsStream(resourceLocation), "UTF-8"); // } catch (Exception e) { // throw new RuntimeException("Failed to get template from " + resourceLocation); // } // } // Path: src/main/java/com/thoughtworks/go/strongauth/handlers/PluginSettingsHandler.java import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.util.MapBuilder; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.Json.toMap; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; import static com.thoughtworks.go.strongauth.util.Resources.get; package com.thoughtworks.go.strongauth.handlers; public class PluginSettingsHandler { public static final String PLUGIN_CONFIG_PASSWORD_FILE_PATH = "PASSWORD_FILE_PATH"; public static final String DISPLAY_NAME_PASSWORD_FILE_PATH = "Password file path"; public static Handler getConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Map<Object, Object> configResponse = create() .add(PLUGIN_CONFIG_PASSWORD_FILE_PATH, create() .add("display-name", DISPLAY_NAME_PASSWORD_FILE_PATH) .add("required", true)) .build(); return DefaultGoPluginApiResponse.success(toJson(configResponse)); } }; } public static Handler getView() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { Object viewResponse = create().add("template", get("/plugin-settings.template.html")).build(); return DefaultGoPluginApiResponse.success(toJson(viewResponse)); } }; } /* Called upon save of the plugin settings in the UI. */ public static Handler validateConfiguration() { return new Handler() { @Override public GoPluginApiResponse call(GoPluginApiRequest request) { final Map<String, Map<String, String>> settings = (Map<String, Map<String, String>>) toMap(request.requestBody()).get("plugin-settings"); final List<Map<Object, Object>> validationResponse = new ArrayList<>(); if (isEmpty(settings, PLUGIN_CONFIG_PASSWORD_FILE_PATH)) { addValidationError(validationResponse, PLUGIN_CONFIG_PASSWORD_FILE_PATH, "Password file path"); } return DefaultGoPluginApiResponse.success(toJson(validationResponse)); } private boolean isEmpty(Map<String, Map<String, String>> settings, String key) { return !settings.containsKey(key) || settings.get(key) == null || settings.get(key).get("value") == null || "".equals(settings.get(key).get("value").trim()); } private void addValidationError(List<Map<Object, Object>> validationResponse, String key, String userReadableMessagePrefix) { String message = userReadableMessagePrefix + " is required and should not be empty";
validationResponse.add(MapBuilder.create().add("key", key).add("message", message).build());
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java
// Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public class ChangeMonitor<EVT_TYPE, VALUE_TYPE> { // // private static final long MIN_DELAY = 100; // private static final long MAX_DELAY = 2000; // // private boolean running = true; // private ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate; // private final List<MonitorListener<EVT_TYPE>> changeListeners = new LinkedList<>(); // private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); // // private static final Logger LOGGER = Logger.getLoggerFor(ChangeMonitor.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ChangeMonitor(ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate) { // this.delegate = delegate; // } // // public void start() { // checkForChange(MIN_DELAY, Optional.<VALUE_TYPE>absent()); // } // // private Function<Long, Long> incrementalChange = new Function<Long, Long>() { // @Override // public Long apply(final Long in) { // if (in > MAX_DELAY) { // return MAX_DELAY; // } // return in * 2; // } // }; // // private void checkForChange(final long delay, final Optional<VALUE_TYPE> oldMaybeValue) { // executorService.schedule(new Runnable() { // @Override // public void run() { // try { // final Optional<VALUE_TYPE> newMaybeValue = delegate.newValue(); // final long newDelay; // if (valueChanged(newMaybeValue, oldMaybeValue)) { // LOGGER.info(String.format("Value changed from %s to %s", oldMaybeValue, newMaybeValue)); // LOGGER.info(String.format("Instance: %s", this)); // final EVT_TYPE notifyEvent = delegate.createNotifyEvent(newMaybeValue, oldMaybeValue); // notifyListeners(notifyEvent); // newDelay = MIN_DELAY; // } else { // newDelay = incrementalChange.apply(delay); // } // // if (running) { // checkForChange(newDelay, newMaybeValue); // } // } catch (Exception e) { // LOGGER.error("ChangeMonitor failed.", e); // } // } // // }, delay, TimeUnit.MILLISECONDS); // // } // // private boolean valueChanged(Optional<?> newValue, Optional<?> oldValue) { // return !oldValue.equals(newValue); // } // // public void stop() { // synchronized (changeListeners) { // changeListeners.clear(); // } // running = false; // } // // private void notifyListeners(final EVT_TYPE event) { // final List<MonitorListener<EVT_TYPE>> listeners; // synchronized (changeListeners) { // listeners = new ArrayList<>(changeListeners); // } // // executorService.submit(new Runnable() { // @Override // public void run() { // for (MonitorListener<EVT_TYPE> listener : listeners) { // listener.changed(event); // } // } // }); // } // // public void addChangeListener(MonitorListener<EVT_TYPE> sourceChangeListener) { // synchronized (changeListeners) { // if (!changeListeners.contains(sourceChangeListener)) { // changeListeners.add(sourceChangeListener); // } // } // } // // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // } // // public interface MonitorListener<T> { // void changed(T event); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public interface MonitorListener<T> { // void changed(T event); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // }
import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.util.ChangeMonitor; import com.thoughtworks.go.strongauth.util.ChangeMonitor.ChangeMonitorDelegate; import com.thoughtworks.go.strongauth.util.ChangeMonitor.MonitorListener; import com.thoughtworks.go.strongauth.util.InputStreamSource; import java.io.*; import static java.lang.String.format; import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
package com.thoughtworks.go.strongauth.util.io; public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { private final File file;
// Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public class ChangeMonitor<EVT_TYPE, VALUE_TYPE> { // // private static final long MIN_DELAY = 100; // private static final long MAX_DELAY = 2000; // // private boolean running = true; // private ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate; // private final List<MonitorListener<EVT_TYPE>> changeListeners = new LinkedList<>(); // private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); // // private static final Logger LOGGER = Logger.getLoggerFor(ChangeMonitor.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ChangeMonitor(ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate) { // this.delegate = delegate; // } // // public void start() { // checkForChange(MIN_DELAY, Optional.<VALUE_TYPE>absent()); // } // // private Function<Long, Long> incrementalChange = new Function<Long, Long>() { // @Override // public Long apply(final Long in) { // if (in > MAX_DELAY) { // return MAX_DELAY; // } // return in * 2; // } // }; // // private void checkForChange(final long delay, final Optional<VALUE_TYPE> oldMaybeValue) { // executorService.schedule(new Runnable() { // @Override // public void run() { // try { // final Optional<VALUE_TYPE> newMaybeValue = delegate.newValue(); // final long newDelay; // if (valueChanged(newMaybeValue, oldMaybeValue)) { // LOGGER.info(String.format("Value changed from %s to %s", oldMaybeValue, newMaybeValue)); // LOGGER.info(String.format("Instance: %s", this)); // final EVT_TYPE notifyEvent = delegate.createNotifyEvent(newMaybeValue, oldMaybeValue); // notifyListeners(notifyEvent); // newDelay = MIN_DELAY; // } else { // newDelay = incrementalChange.apply(delay); // } // // if (running) { // checkForChange(newDelay, newMaybeValue); // } // } catch (Exception e) { // LOGGER.error("ChangeMonitor failed.", e); // } // } // // }, delay, TimeUnit.MILLISECONDS); // // } // // private boolean valueChanged(Optional<?> newValue, Optional<?> oldValue) { // return !oldValue.equals(newValue); // } // // public void stop() { // synchronized (changeListeners) { // changeListeners.clear(); // } // running = false; // } // // private void notifyListeners(final EVT_TYPE event) { // final List<MonitorListener<EVT_TYPE>> listeners; // synchronized (changeListeners) { // listeners = new ArrayList<>(changeListeners); // } // // executorService.submit(new Runnable() { // @Override // public void run() { // for (MonitorListener<EVT_TYPE> listener : listeners) { // listener.changed(event); // } // } // }); // } // // public void addChangeListener(MonitorListener<EVT_TYPE> sourceChangeListener) { // synchronized (changeListeners) { // if (!changeListeners.contains(sourceChangeListener)) { // changeListeners.add(sourceChangeListener); // } // } // } // // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // } // // public interface MonitorListener<T> { // void changed(T event); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public interface MonitorListener<T> { // void changed(T event); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.util.ChangeMonitor; import com.thoughtworks.go.strongauth.util.ChangeMonitor.ChangeMonitorDelegate; import com.thoughtworks.go.strongauth.util.ChangeMonitor.MonitorListener; import com.thoughtworks.go.strongauth.util.InputStreamSource; import java.io.*; import static java.lang.String.format; import static org.apache.commons.codec.digest.DigestUtils.md5Hex; package com.thoughtworks.go.strongauth.util.io; public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { private final File file;
private ChangeMonitor<SourceChangeEvent, String> changeMonitor;
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java
// Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public class ChangeMonitor<EVT_TYPE, VALUE_TYPE> { // // private static final long MIN_DELAY = 100; // private static final long MAX_DELAY = 2000; // // private boolean running = true; // private ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate; // private final List<MonitorListener<EVT_TYPE>> changeListeners = new LinkedList<>(); // private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); // // private static final Logger LOGGER = Logger.getLoggerFor(ChangeMonitor.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ChangeMonitor(ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate) { // this.delegate = delegate; // } // // public void start() { // checkForChange(MIN_DELAY, Optional.<VALUE_TYPE>absent()); // } // // private Function<Long, Long> incrementalChange = new Function<Long, Long>() { // @Override // public Long apply(final Long in) { // if (in > MAX_DELAY) { // return MAX_DELAY; // } // return in * 2; // } // }; // // private void checkForChange(final long delay, final Optional<VALUE_TYPE> oldMaybeValue) { // executorService.schedule(new Runnable() { // @Override // public void run() { // try { // final Optional<VALUE_TYPE> newMaybeValue = delegate.newValue(); // final long newDelay; // if (valueChanged(newMaybeValue, oldMaybeValue)) { // LOGGER.info(String.format("Value changed from %s to %s", oldMaybeValue, newMaybeValue)); // LOGGER.info(String.format("Instance: %s", this)); // final EVT_TYPE notifyEvent = delegate.createNotifyEvent(newMaybeValue, oldMaybeValue); // notifyListeners(notifyEvent); // newDelay = MIN_DELAY; // } else { // newDelay = incrementalChange.apply(delay); // } // // if (running) { // checkForChange(newDelay, newMaybeValue); // } // } catch (Exception e) { // LOGGER.error("ChangeMonitor failed.", e); // } // } // // }, delay, TimeUnit.MILLISECONDS); // // } // // private boolean valueChanged(Optional<?> newValue, Optional<?> oldValue) { // return !oldValue.equals(newValue); // } // // public void stop() { // synchronized (changeListeners) { // changeListeners.clear(); // } // running = false; // } // // private void notifyListeners(final EVT_TYPE event) { // final List<MonitorListener<EVT_TYPE>> listeners; // synchronized (changeListeners) { // listeners = new ArrayList<>(changeListeners); // } // // executorService.submit(new Runnable() { // @Override // public void run() { // for (MonitorListener<EVT_TYPE> listener : listeners) { // listener.changed(event); // } // } // }); // } // // public void addChangeListener(MonitorListener<EVT_TYPE> sourceChangeListener) { // synchronized (changeListeners) { // if (!changeListeners.contains(sourceChangeListener)) { // changeListeners.add(sourceChangeListener); // } // } // } // // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // } // // public interface MonitorListener<T> { // void changed(T event); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public interface MonitorListener<T> { // void changed(T event); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // }
import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.util.ChangeMonitor; import com.thoughtworks.go.strongauth.util.ChangeMonitor.ChangeMonitorDelegate; import com.thoughtworks.go.strongauth.util.ChangeMonitor.MonitorListener; import com.thoughtworks.go.strongauth.util.InputStreamSource; import java.io.*; import static java.lang.String.format; import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { return new SourceChangeEvent(contents(), file.getAbsolutePath()); } private InputStream contents() { try { return new FileInputStream(file); } catch (FileNotFoundException e) { return new ByteArrayInputStream(new byte[0]); } } public Optional<String> newValue() { try { return Optional.of(md5Hex(new FileInputStream(file))); } catch (IOException e) { return Optional.absent(); } } public void start() { this.changeMonitor.start(); } public void stop() { this.changeMonitor.stop(); } @Override public void addChangeListener(final SourceChangeListener sourceChangeListener) {
// Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public class ChangeMonitor<EVT_TYPE, VALUE_TYPE> { // // private static final long MIN_DELAY = 100; // private static final long MAX_DELAY = 2000; // // private boolean running = true; // private ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate; // private final List<MonitorListener<EVT_TYPE>> changeListeners = new LinkedList<>(); // private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); // // private static final Logger LOGGER = Logger.getLoggerFor(ChangeMonitor.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ChangeMonitor(ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate) { // this.delegate = delegate; // } // // public void start() { // checkForChange(MIN_DELAY, Optional.<VALUE_TYPE>absent()); // } // // private Function<Long, Long> incrementalChange = new Function<Long, Long>() { // @Override // public Long apply(final Long in) { // if (in > MAX_DELAY) { // return MAX_DELAY; // } // return in * 2; // } // }; // // private void checkForChange(final long delay, final Optional<VALUE_TYPE> oldMaybeValue) { // executorService.schedule(new Runnable() { // @Override // public void run() { // try { // final Optional<VALUE_TYPE> newMaybeValue = delegate.newValue(); // final long newDelay; // if (valueChanged(newMaybeValue, oldMaybeValue)) { // LOGGER.info(String.format("Value changed from %s to %s", oldMaybeValue, newMaybeValue)); // LOGGER.info(String.format("Instance: %s", this)); // final EVT_TYPE notifyEvent = delegate.createNotifyEvent(newMaybeValue, oldMaybeValue); // notifyListeners(notifyEvent); // newDelay = MIN_DELAY; // } else { // newDelay = incrementalChange.apply(delay); // } // // if (running) { // checkForChange(newDelay, newMaybeValue); // } // } catch (Exception e) { // LOGGER.error("ChangeMonitor failed.", e); // } // } // // }, delay, TimeUnit.MILLISECONDS); // // } // // private boolean valueChanged(Optional<?> newValue, Optional<?> oldValue) { // return !oldValue.equals(newValue); // } // // public void stop() { // synchronized (changeListeners) { // changeListeners.clear(); // } // running = false; // } // // private void notifyListeners(final EVT_TYPE event) { // final List<MonitorListener<EVT_TYPE>> listeners; // synchronized (changeListeners) { // listeners = new ArrayList<>(changeListeners); // } // // executorService.submit(new Runnable() { // @Override // public void run() { // for (MonitorListener<EVT_TYPE> listener : listeners) { // listener.changed(event); // } // } // }); // } // // public void addChangeListener(MonitorListener<EVT_TYPE> sourceChangeListener) { // synchronized (changeListeners) { // if (!changeListeners.contains(sourceChangeListener)) { // changeListeners.add(sourceChangeListener); // } // } // } // // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // } // // public interface MonitorListener<T> { // void changed(T event); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public interface MonitorListener<T> { // void changed(T event); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.util.ChangeMonitor; import com.thoughtworks.go.strongauth.util.ChangeMonitor.ChangeMonitorDelegate; import com.thoughtworks.go.strongauth.util.ChangeMonitor.MonitorListener; import com.thoughtworks.go.strongauth.util.InputStreamSource; import java.io.*; import static java.lang.String.format; import static org.apache.commons.codec.digest.DigestUtils.md5Hex; public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { return new SourceChangeEvent(contents(), file.getAbsolutePath()); } private InputStream contents() { try { return new FileInputStream(file); } catch (FileNotFoundException e) { return new ByteArrayInputStream(new byte[0]); } } public Optional<String> newValue() { try { return Optional.of(md5Hex(new FileInputStream(file))); } catch (IOException e) { return Optional.absent(); } } public void start() { this.changeMonitor.start(); } public void stop() { this.changeMonitor.stop(); } @Override public void addChangeListener(final SourceChangeListener sourceChangeListener) {
this.changeMonitor.addChangeListener(new MonitorListener<SourceChangeEvent>() {
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigFileMonitor.java
// Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangeListener.java // public interface ConfigurationChangeListener extends MonitorListener<ConfigurationChangedEvent> {} // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangedEvent.java // @Value // public class ConfigurationChangedEvent { // private final Optional<PluginConfiguration> pluginConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java // public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { // // private final GoAPI goAPI; // private ChangeMonitor<ConfigurationChangedEvent, PluginConfiguration> changeMonitor; // // public ConfigurationMonitor( // final GoAPI goAPI // ) { // this.goAPI = goAPI; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public void start() { // this.changeMonitor.start(); // } // // public void addConfigurationChangeListener(ConfigurationChangeListener listener) { // this.changeMonitor.addChangeListener(listener); // } // // @Override // public ConfigurationChangedEvent createNotifyEvent(Optional<PluginConfiguration> newMaybeValue, Optional<PluginConfiguration> oldMaybeValue) { // return new ConfigurationChangedEvent(newMaybeValue); // } // // @Override // public Optional<PluginConfiguration> newValue() { // return currentConfiguration(); // } // // public Optional<PluginConfiguration> currentConfiguration() { // return Optional.of(goAPI.getPluginConfiguration()); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java // public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { // // private final File file; // // private ChangeMonitor<SourceChangeEvent, String> changeMonitor; // // public FileChangeMonitor(final File file) { // this.file = file; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { // return new SourceChangeEvent(contents(), file.getAbsolutePath()); // } // // private InputStream contents() { // try { // return new FileInputStream(file); // } catch (FileNotFoundException e) { // return new ByteArrayInputStream(new byte[0]); // } // } // // public Optional<String> newValue() { // try { // return Optional.of(md5Hex(new FileInputStream(file))); // } catch (IOException e) { // return Optional.absent(); // } // } // // public void start() { // this.changeMonitor.start(); // } // // public void stop() { // this.changeMonitor.stop(); // } // // @Override // public void addChangeListener(final SourceChangeListener sourceChangeListener) { // this.changeMonitor.addChangeListener(new MonitorListener<SourceChangeEvent>() { // @Override // public void changed(SourceChangeEvent event) { // sourceChangeListener.sourceChanged(event); // } // }); // } // // @Override // public InputStream inputStream() throws IOException { // return new FileInputStream(file); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.config.ConfigurationChangeListener; import com.thoughtworks.go.strongauth.config.ConfigurationChangedEvent; import com.thoughtworks.go.strongauth.config.ConfigurationMonitor; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.FileChangeMonitor; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream;
package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigFileMonitor implements InputStreamSource { private final ConfigurationMonitor configurationMonitor;
// Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangeListener.java // public interface ConfigurationChangeListener extends MonitorListener<ConfigurationChangedEvent> {} // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangedEvent.java // @Value // public class ConfigurationChangedEvent { // private final Optional<PluginConfiguration> pluginConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java // public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { // // private final GoAPI goAPI; // private ChangeMonitor<ConfigurationChangedEvent, PluginConfiguration> changeMonitor; // // public ConfigurationMonitor( // final GoAPI goAPI // ) { // this.goAPI = goAPI; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public void start() { // this.changeMonitor.start(); // } // // public void addConfigurationChangeListener(ConfigurationChangeListener listener) { // this.changeMonitor.addChangeListener(listener); // } // // @Override // public ConfigurationChangedEvent createNotifyEvent(Optional<PluginConfiguration> newMaybeValue, Optional<PluginConfiguration> oldMaybeValue) { // return new ConfigurationChangedEvent(newMaybeValue); // } // // @Override // public Optional<PluginConfiguration> newValue() { // return currentConfiguration(); // } // // public Optional<PluginConfiguration> currentConfiguration() { // return Optional.of(goAPI.getPluginConfiguration()); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java // public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { // // private final File file; // // private ChangeMonitor<SourceChangeEvent, String> changeMonitor; // // public FileChangeMonitor(final File file) { // this.file = file; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { // return new SourceChangeEvent(contents(), file.getAbsolutePath()); // } // // private InputStream contents() { // try { // return new FileInputStream(file); // } catch (FileNotFoundException e) { // return new ByteArrayInputStream(new byte[0]); // } // } // // public Optional<String> newValue() { // try { // return Optional.of(md5Hex(new FileInputStream(file))); // } catch (IOException e) { // return Optional.absent(); // } // } // // public void start() { // this.changeMonitor.start(); // } // // public void stop() { // this.changeMonitor.stop(); // } // // @Override // public void addChangeListener(final SourceChangeListener sourceChangeListener) { // this.changeMonitor.addChangeListener(new MonitorListener<SourceChangeEvent>() { // @Override // public void changed(SourceChangeEvent event) { // sourceChangeListener.sourceChanged(event); // } // }); // } // // @Override // public InputStream inputStream() throws IOException { // return new FileInputStream(file); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigFileMonitor.java import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.config.ConfigurationChangeListener; import com.thoughtworks.go.strongauth.config.ConfigurationChangedEvent; import com.thoughtworks.go.strongauth.config.ConfigurationMonitor; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.FileChangeMonitor; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigFileMonitor implements InputStreamSource { private final ConfigurationMonitor configurationMonitor;
private Optional<FileChangeMonitor> maybeFileChangeMonitor = Optional.absent();
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigFileMonitor.java
// Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangeListener.java // public interface ConfigurationChangeListener extends MonitorListener<ConfigurationChangedEvent> {} // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangedEvent.java // @Value // public class ConfigurationChangedEvent { // private final Optional<PluginConfiguration> pluginConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java // public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { // // private final GoAPI goAPI; // private ChangeMonitor<ConfigurationChangedEvent, PluginConfiguration> changeMonitor; // // public ConfigurationMonitor( // final GoAPI goAPI // ) { // this.goAPI = goAPI; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public void start() { // this.changeMonitor.start(); // } // // public void addConfigurationChangeListener(ConfigurationChangeListener listener) { // this.changeMonitor.addChangeListener(listener); // } // // @Override // public ConfigurationChangedEvent createNotifyEvent(Optional<PluginConfiguration> newMaybeValue, Optional<PluginConfiguration> oldMaybeValue) { // return new ConfigurationChangedEvent(newMaybeValue); // } // // @Override // public Optional<PluginConfiguration> newValue() { // return currentConfiguration(); // } // // public Optional<PluginConfiguration> currentConfiguration() { // return Optional.of(goAPI.getPluginConfiguration()); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java // public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { // // private final File file; // // private ChangeMonitor<SourceChangeEvent, String> changeMonitor; // // public FileChangeMonitor(final File file) { // this.file = file; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { // return new SourceChangeEvent(contents(), file.getAbsolutePath()); // } // // private InputStream contents() { // try { // return new FileInputStream(file); // } catch (FileNotFoundException e) { // return new ByteArrayInputStream(new byte[0]); // } // } // // public Optional<String> newValue() { // try { // return Optional.of(md5Hex(new FileInputStream(file))); // } catch (IOException e) { // return Optional.absent(); // } // } // // public void start() { // this.changeMonitor.start(); // } // // public void stop() { // this.changeMonitor.stop(); // } // // @Override // public void addChangeListener(final SourceChangeListener sourceChangeListener) { // this.changeMonitor.addChangeListener(new MonitorListener<SourceChangeEvent>() { // @Override // public void changed(SourceChangeEvent event) { // sourceChangeListener.sourceChanged(event); // } // }); // } // // @Override // public InputStream inputStream() throws IOException { // return new FileInputStream(file); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.config.ConfigurationChangeListener; import com.thoughtworks.go.strongauth.config.ConfigurationChangedEvent; import com.thoughtworks.go.strongauth.config.ConfigurationMonitor; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.FileChangeMonitor; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream;
package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigFileMonitor implements InputStreamSource { private final ConfigurationMonitor configurationMonitor; private Optional<FileChangeMonitor> maybeFileChangeMonitor = Optional.absent();
// Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangeListener.java // public interface ConfigurationChangeListener extends MonitorListener<ConfigurationChangedEvent> {} // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangedEvent.java // @Value // public class ConfigurationChangedEvent { // private final Optional<PluginConfiguration> pluginConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java // public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { // // private final GoAPI goAPI; // private ChangeMonitor<ConfigurationChangedEvent, PluginConfiguration> changeMonitor; // // public ConfigurationMonitor( // final GoAPI goAPI // ) { // this.goAPI = goAPI; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public void start() { // this.changeMonitor.start(); // } // // public void addConfigurationChangeListener(ConfigurationChangeListener listener) { // this.changeMonitor.addChangeListener(listener); // } // // @Override // public ConfigurationChangedEvent createNotifyEvent(Optional<PluginConfiguration> newMaybeValue, Optional<PluginConfiguration> oldMaybeValue) { // return new ConfigurationChangedEvent(newMaybeValue); // } // // @Override // public Optional<PluginConfiguration> newValue() { // return currentConfiguration(); // } // // public Optional<PluginConfiguration> currentConfiguration() { // return Optional.of(goAPI.getPluginConfiguration()); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java // public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { // // private final File file; // // private ChangeMonitor<SourceChangeEvent, String> changeMonitor; // // public FileChangeMonitor(final File file) { // this.file = file; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { // return new SourceChangeEvent(contents(), file.getAbsolutePath()); // } // // private InputStream contents() { // try { // return new FileInputStream(file); // } catch (FileNotFoundException e) { // return new ByteArrayInputStream(new byte[0]); // } // } // // public Optional<String> newValue() { // try { // return Optional.of(md5Hex(new FileInputStream(file))); // } catch (IOException e) { // return Optional.absent(); // } // } // // public void start() { // this.changeMonitor.start(); // } // // public void stop() { // this.changeMonitor.stop(); // } // // @Override // public void addChangeListener(final SourceChangeListener sourceChangeListener) { // this.changeMonitor.addChangeListener(new MonitorListener<SourceChangeEvent>() { // @Override // public void changed(SourceChangeEvent event) { // sourceChangeListener.sourceChanged(event); // } // }); // } // // @Override // public InputStream inputStream() throws IOException { // return new FileInputStream(file); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigFileMonitor.java import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.config.ConfigurationChangeListener; import com.thoughtworks.go.strongauth.config.ConfigurationChangedEvent; import com.thoughtworks.go.strongauth.config.ConfigurationMonitor; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.FileChangeMonitor; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigFileMonitor implements InputStreamSource { private final ConfigurationMonitor configurationMonitor; private Optional<FileChangeMonitor> maybeFileChangeMonitor = Optional.absent();
private SourceChangeListener sourceChangeListener;
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigFileMonitor.java
// Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangeListener.java // public interface ConfigurationChangeListener extends MonitorListener<ConfigurationChangedEvent> {} // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangedEvent.java // @Value // public class ConfigurationChangedEvent { // private final Optional<PluginConfiguration> pluginConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java // public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { // // private final GoAPI goAPI; // private ChangeMonitor<ConfigurationChangedEvent, PluginConfiguration> changeMonitor; // // public ConfigurationMonitor( // final GoAPI goAPI // ) { // this.goAPI = goAPI; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public void start() { // this.changeMonitor.start(); // } // // public void addConfigurationChangeListener(ConfigurationChangeListener listener) { // this.changeMonitor.addChangeListener(listener); // } // // @Override // public ConfigurationChangedEvent createNotifyEvent(Optional<PluginConfiguration> newMaybeValue, Optional<PluginConfiguration> oldMaybeValue) { // return new ConfigurationChangedEvent(newMaybeValue); // } // // @Override // public Optional<PluginConfiguration> newValue() { // return currentConfiguration(); // } // // public Optional<PluginConfiguration> currentConfiguration() { // return Optional.of(goAPI.getPluginConfiguration()); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java // public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { // // private final File file; // // private ChangeMonitor<SourceChangeEvent, String> changeMonitor; // // public FileChangeMonitor(final File file) { // this.file = file; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { // return new SourceChangeEvent(contents(), file.getAbsolutePath()); // } // // private InputStream contents() { // try { // return new FileInputStream(file); // } catch (FileNotFoundException e) { // return new ByteArrayInputStream(new byte[0]); // } // } // // public Optional<String> newValue() { // try { // return Optional.of(md5Hex(new FileInputStream(file))); // } catch (IOException e) { // return Optional.absent(); // } // } // // public void start() { // this.changeMonitor.start(); // } // // public void stop() { // this.changeMonitor.stop(); // } // // @Override // public void addChangeListener(final SourceChangeListener sourceChangeListener) { // this.changeMonitor.addChangeListener(new MonitorListener<SourceChangeEvent>() { // @Override // public void changed(SourceChangeEvent event) { // sourceChangeListener.sourceChanged(event); // } // }); // } // // @Override // public InputStream inputStream() throws IOException { // return new FileInputStream(file); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.config.ConfigurationChangeListener; import com.thoughtworks.go.strongauth.config.ConfigurationChangedEvent; import com.thoughtworks.go.strongauth.config.ConfigurationMonitor; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.FileChangeMonitor; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream;
package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigFileMonitor implements InputStreamSource { private final ConfigurationMonitor configurationMonitor; private Optional<FileChangeMonitor> maybeFileChangeMonitor = Optional.absent(); private SourceChangeListener sourceChangeListener; public ConfigFileMonitor( ConfigurationMonitor configurationMonitor ) { this.configurationMonitor = configurationMonitor;
// Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangeListener.java // public interface ConfigurationChangeListener extends MonitorListener<ConfigurationChangedEvent> {} // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangedEvent.java // @Value // public class ConfigurationChangedEvent { // private final Optional<PluginConfiguration> pluginConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java // public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { // // private final GoAPI goAPI; // private ChangeMonitor<ConfigurationChangedEvent, PluginConfiguration> changeMonitor; // // public ConfigurationMonitor( // final GoAPI goAPI // ) { // this.goAPI = goAPI; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public void start() { // this.changeMonitor.start(); // } // // public void addConfigurationChangeListener(ConfigurationChangeListener listener) { // this.changeMonitor.addChangeListener(listener); // } // // @Override // public ConfigurationChangedEvent createNotifyEvent(Optional<PluginConfiguration> newMaybeValue, Optional<PluginConfiguration> oldMaybeValue) { // return new ConfigurationChangedEvent(newMaybeValue); // } // // @Override // public Optional<PluginConfiguration> newValue() { // return currentConfiguration(); // } // // public Optional<PluginConfiguration> currentConfiguration() { // return Optional.of(goAPI.getPluginConfiguration()); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java // public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { // // private final File file; // // private ChangeMonitor<SourceChangeEvent, String> changeMonitor; // // public FileChangeMonitor(final File file) { // this.file = file; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { // return new SourceChangeEvent(contents(), file.getAbsolutePath()); // } // // private InputStream contents() { // try { // return new FileInputStream(file); // } catch (FileNotFoundException e) { // return new ByteArrayInputStream(new byte[0]); // } // } // // public Optional<String> newValue() { // try { // return Optional.of(md5Hex(new FileInputStream(file))); // } catch (IOException e) { // return Optional.absent(); // } // } // // public void start() { // this.changeMonitor.start(); // } // // public void stop() { // this.changeMonitor.stop(); // } // // @Override // public void addChangeListener(final SourceChangeListener sourceChangeListener) { // this.changeMonitor.addChangeListener(new MonitorListener<SourceChangeEvent>() { // @Override // public void changed(SourceChangeEvent event) { // sourceChangeListener.sourceChanged(event); // } // }); // } // // @Override // public InputStream inputStream() throws IOException { // return new FileInputStream(file); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigFileMonitor.java import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.config.ConfigurationChangeListener; import com.thoughtworks.go.strongauth.config.ConfigurationChangedEvent; import com.thoughtworks.go.strongauth.config.ConfigurationMonitor; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.FileChangeMonitor; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigFileMonitor implements InputStreamSource { private final ConfigurationMonitor configurationMonitor; private Optional<FileChangeMonitor> maybeFileChangeMonitor = Optional.absent(); private SourceChangeListener sourceChangeListener; public ConfigFileMonitor( ConfigurationMonitor configurationMonitor ) { this.configurationMonitor = configurationMonitor;
this.configurationMonitor.addConfigurationChangeListener(new ConfigurationChangeListener() {
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigFileMonitor.java
// Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangeListener.java // public interface ConfigurationChangeListener extends MonitorListener<ConfigurationChangedEvent> {} // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangedEvent.java // @Value // public class ConfigurationChangedEvent { // private final Optional<PluginConfiguration> pluginConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java // public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { // // private final GoAPI goAPI; // private ChangeMonitor<ConfigurationChangedEvent, PluginConfiguration> changeMonitor; // // public ConfigurationMonitor( // final GoAPI goAPI // ) { // this.goAPI = goAPI; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public void start() { // this.changeMonitor.start(); // } // // public void addConfigurationChangeListener(ConfigurationChangeListener listener) { // this.changeMonitor.addChangeListener(listener); // } // // @Override // public ConfigurationChangedEvent createNotifyEvent(Optional<PluginConfiguration> newMaybeValue, Optional<PluginConfiguration> oldMaybeValue) { // return new ConfigurationChangedEvent(newMaybeValue); // } // // @Override // public Optional<PluginConfiguration> newValue() { // return currentConfiguration(); // } // // public Optional<PluginConfiguration> currentConfiguration() { // return Optional.of(goAPI.getPluginConfiguration()); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java // public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { // // private final File file; // // private ChangeMonitor<SourceChangeEvent, String> changeMonitor; // // public FileChangeMonitor(final File file) { // this.file = file; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { // return new SourceChangeEvent(contents(), file.getAbsolutePath()); // } // // private InputStream contents() { // try { // return new FileInputStream(file); // } catch (FileNotFoundException e) { // return new ByteArrayInputStream(new byte[0]); // } // } // // public Optional<String> newValue() { // try { // return Optional.of(md5Hex(new FileInputStream(file))); // } catch (IOException e) { // return Optional.absent(); // } // } // // public void start() { // this.changeMonitor.start(); // } // // public void stop() { // this.changeMonitor.stop(); // } // // @Override // public void addChangeListener(final SourceChangeListener sourceChangeListener) { // this.changeMonitor.addChangeListener(new MonitorListener<SourceChangeEvent>() { // @Override // public void changed(SourceChangeEvent event) { // sourceChangeListener.sourceChanged(event); // } // }); // } // // @Override // public InputStream inputStream() throws IOException { // return new FileInputStream(file); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.config.ConfigurationChangeListener; import com.thoughtworks.go.strongauth.config.ConfigurationChangedEvent; import com.thoughtworks.go.strongauth.config.ConfigurationMonitor; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.FileChangeMonitor; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream;
package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigFileMonitor implements InputStreamSource { private final ConfigurationMonitor configurationMonitor; private Optional<FileChangeMonitor> maybeFileChangeMonitor = Optional.absent(); private SourceChangeListener sourceChangeListener; public ConfigFileMonitor( ConfigurationMonitor configurationMonitor ) { this.configurationMonitor = configurationMonitor; this.configurationMonitor.addConfigurationChangeListener(new ConfigurationChangeListener() { @Override
// Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangeListener.java // public interface ConfigurationChangeListener extends MonitorListener<ConfigurationChangedEvent> {} // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangedEvent.java // @Value // public class ConfigurationChangedEvent { // private final Optional<PluginConfiguration> pluginConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java // public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { // // private final GoAPI goAPI; // private ChangeMonitor<ConfigurationChangedEvent, PluginConfiguration> changeMonitor; // // public ConfigurationMonitor( // final GoAPI goAPI // ) { // this.goAPI = goAPI; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public void start() { // this.changeMonitor.start(); // } // // public void addConfigurationChangeListener(ConfigurationChangeListener listener) { // this.changeMonitor.addChangeListener(listener); // } // // @Override // public ConfigurationChangedEvent createNotifyEvent(Optional<PluginConfiguration> newMaybeValue, Optional<PluginConfiguration> oldMaybeValue) { // return new ConfigurationChangedEvent(newMaybeValue); // } // // @Override // public Optional<PluginConfiguration> newValue() { // return currentConfiguration(); // } // // public Optional<PluginConfiguration> currentConfiguration() { // return Optional.of(goAPI.getPluginConfiguration()); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java // public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { // // private final File file; // // private ChangeMonitor<SourceChangeEvent, String> changeMonitor; // // public FileChangeMonitor(final File file) { // this.file = file; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { // return new SourceChangeEvent(contents(), file.getAbsolutePath()); // } // // private InputStream contents() { // try { // return new FileInputStream(file); // } catch (FileNotFoundException e) { // return new ByteArrayInputStream(new byte[0]); // } // } // // public Optional<String> newValue() { // try { // return Optional.of(md5Hex(new FileInputStream(file))); // } catch (IOException e) { // return Optional.absent(); // } // } // // public void start() { // this.changeMonitor.start(); // } // // public void stop() { // this.changeMonitor.stop(); // } // // @Override // public void addChangeListener(final SourceChangeListener sourceChangeListener) { // this.changeMonitor.addChangeListener(new MonitorListener<SourceChangeEvent>() { // @Override // public void changed(SourceChangeEvent event) { // sourceChangeListener.sourceChanged(event); // } // }); // } // // @Override // public InputStream inputStream() throws IOException { // return new FileInputStream(file); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigFileMonitor.java import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.config.ConfigurationChangeListener; import com.thoughtworks.go.strongauth.config.ConfigurationChangedEvent; import com.thoughtworks.go.strongauth.config.ConfigurationMonitor; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.FileChangeMonitor; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigFileMonitor implements InputStreamSource { private final ConfigurationMonitor configurationMonitor; private Optional<FileChangeMonitor> maybeFileChangeMonitor = Optional.absent(); private SourceChangeListener sourceChangeListener; public ConfigFileMonitor( ConfigurationMonitor configurationMonitor ) { this.configurationMonitor = configurationMonitor; this.configurationMonitor.addConfigurationChangeListener(new ConfigurationChangeListener() { @Override
public void changed(ConfigurationChangedEvent event) {
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigFileMonitor.java
// Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangeListener.java // public interface ConfigurationChangeListener extends MonitorListener<ConfigurationChangedEvent> {} // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangedEvent.java // @Value // public class ConfigurationChangedEvent { // private final Optional<PluginConfiguration> pluginConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java // public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { // // private final GoAPI goAPI; // private ChangeMonitor<ConfigurationChangedEvent, PluginConfiguration> changeMonitor; // // public ConfigurationMonitor( // final GoAPI goAPI // ) { // this.goAPI = goAPI; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public void start() { // this.changeMonitor.start(); // } // // public void addConfigurationChangeListener(ConfigurationChangeListener listener) { // this.changeMonitor.addChangeListener(listener); // } // // @Override // public ConfigurationChangedEvent createNotifyEvent(Optional<PluginConfiguration> newMaybeValue, Optional<PluginConfiguration> oldMaybeValue) { // return new ConfigurationChangedEvent(newMaybeValue); // } // // @Override // public Optional<PluginConfiguration> newValue() { // return currentConfiguration(); // } // // public Optional<PluginConfiguration> currentConfiguration() { // return Optional.of(goAPI.getPluginConfiguration()); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java // public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { // // private final File file; // // private ChangeMonitor<SourceChangeEvent, String> changeMonitor; // // public FileChangeMonitor(final File file) { // this.file = file; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { // return new SourceChangeEvent(contents(), file.getAbsolutePath()); // } // // private InputStream contents() { // try { // return new FileInputStream(file); // } catch (FileNotFoundException e) { // return new ByteArrayInputStream(new byte[0]); // } // } // // public Optional<String> newValue() { // try { // return Optional.of(md5Hex(new FileInputStream(file))); // } catch (IOException e) { // return Optional.absent(); // } // } // // public void start() { // this.changeMonitor.start(); // } // // public void stop() { // this.changeMonitor.stop(); // } // // @Override // public void addChangeListener(final SourceChangeListener sourceChangeListener) { // this.changeMonitor.addChangeListener(new MonitorListener<SourceChangeEvent>() { // @Override // public void changed(SourceChangeEvent event) { // sourceChangeListener.sourceChanged(event); // } // }); // } // // @Override // public InputStream inputStream() throws IOException { // return new FileInputStream(file); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.config.ConfigurationChangeListener; import com.thoughtworks.go.strongauth.config.ConfigurationChangedEvent; import com.thoughtworks.go.strongauth.config.ConfigurationMonitor; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.FileChangeMonitor; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream;
package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigFileMonitor implements InputStreamSource { private final ConfigurationMonitor configurationMonitor; private Optional<FileChangeMonitor> maybeFileChangeMonitor = Optional.absent(); private SourceChangeListener sourceChangeListener; public ConfigFileMonitor( ConfigurationMonitor configurationMonitor ) { this.configurationMonitor = configurationMonitor; this.configurationMonitor.addConfigurationChangeListener(new ConfigurationChangeListener() { @Override public void changed(ConfigurationChangedEvent event) {
// Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangeListener.java // public interface ConfigurationChangeListener extends MonitorListener<ConfigurationChangedEvent> {} // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationChangedEvent.java // @Value // public class ConfigurationChangedEvent { // private final Optional<PluginConfiguration> pluginConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java // public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { // // private final GoAPI goAPI; // private ChangeMonitor<ConfigurationChangedEvent, PluginConfiguration> changeMonitor; // // public ConfigurationMonitor( // final GoAPI goAPI // ) { // this.goAPI = goAPI; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public void start() { // this.changeMonitor.start(); // } // // public void addConfigurationChangeListener(ConfigurationChangeListener listener) { // this.changeMonitor.addChangeListener(listener); // } // // @Override // public ConfigurationChangedEvent createNotifyEvent(Optional<PluginConfiguration> newMaybeValue, Optional<PluginConfiguration> oldMaybeValue) { // return new ConfigurationChangedEvent(newMaybeValue); // } // // @Override // public Optional<PluginConfiguration> newValue() { // return currentConfiguration(); // } // // public Optional<PluginConfiguration> currentConfiguration() { // return Optional.of(goAPI.getPluginConfiguration()); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/FileChangeMonitor.java // public class FileChangeMonitor implements InputStreamSource, ChangeMonitorDelegate<SourceChangeEvent, String> { // // private final File file; // // private ChangeMonitor<SourceChangeEvent, String> changeMonitor; // // public FileChangeMonitor(final File file) { // this.file = file; // this.changeMonitor = new ChangeMonitor<>(this); // } // // public SourceChangeEvent createNotifyEvent(Optional<String> newMaybeValue, Optional<String> oldMaybeValue) { // return new SourceChangeEvent(contents(), file.getAbsolutePath()); // } // // private InputStream contents() { // try { // return new FileInputStream(file); // } catch (FileNotFoundException e) { // return new ByteArrayInputStream(new byte[0]); // } // } // // public Optional<String> newValue() { // try { // return Optional.of(md5Hex(new FileInputStream(file))); // } catch (IOException e) { // return Optional.absent(); // } // } // // public void start() { // this.changeMonitor.start(); // } // // public void stop() { // this.changeMonitor.stop(); // } // // @Override // public void addChangeListener(final SourceChangeListener sourceChangeListener) { // this.changeMonitor.addChangeListener(new MonitorListener<SourceChangeEvent>() { // @Override // public void changed(SourceChangeEvent event) { // sourceChangeListener.sourceChanged(event); // } // }); // } // // @Override // public InputStream inputStream() throws IOException { // return new FileInputStream(file); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigFileMonitor.java import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.config.ConfigurationChangeListener; import com.thoughtworks.go.strongauth.config.ConfigurationChangedEvent; import com.thoughtworks.go.strongauth.config.ConfigurationMonitor; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.FileChangeMonitor; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigFileMonitor implements InputStreamSource { private final ConfigurationMonitor configurationMonitor; private Optional<FileChangeMonitor> maybeFileChangeMonitor = Optional.absent(); private SourceChangeListener sourceChangeListener; public ConfigFileMonitor( ConfigurationMonitor configurationMonitor ) { this.configurationMonitor = configurationMonitor; this.configurationMonitor.addConfigurationChangeListener(new ConfigurationChangeListener() { @Override public void changed(ConfigurationChangedEvent event) {
final Optional<PluginConfiguration> maybePluginConfiguration = event.getPluginConfiguration();
danielsomerfield/go-strong-auth-plugin
src/test/java/com/thoughtworks/go/strongauth/handlers/AuthenticationHandlerTest.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/AuthenticationRequest.java // @Value // public class AuthenticationRequest { // private final String username; // private final String password; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/Authenticator.java // public class Authenticator { // // public final String pluginId = Constants.PLUGIN_ID; // private static final Logger LOGGER = Logger.getLoggerFor(Authenticator.class); // private final List<? extends HashProvider> hashProviders; // // public Authenticator( // final PrincipalDetailSource principalDetailSource, // final List<? extends HashProvider> hashProviders // ) { // this.principalDetailSource = principalDetailSource; // this.hashProviders = hashProviders; // } // // private PrincipalDetailSource principalDetailSource; // // public Optional<Principal> authenticate(final String username, final String password) { // LOGGER.info(format("Login attempt for user %s", username)); // Optional<Principal> maybePrincipal = flatMap(principalDetailSource.byUsername(username), new Function<PrincipalDetail, Optional<Principal>>() { // @Override // public Optional<Principal> apply(PrincipalDetail principalDetail) { // return toPrincipal(principalDetail, password); // } // }); // // if (!maybePrincipal.isPresent()) { // LOGGER.warn(format("Login attempt for user %s failed.", username)); // } // return maybePrincipal; // } // // private Optional<Principal> toPrincipal(final PrincipalDetail principalDetail, final String password) { // Optional<? extends HashProvider> maybeHashProvider = getHashProvider(principalDetail.getHashConfiguration()); // // return flatMap( // maybeHashProvider, // new Function<HashProvider, Optional<Principal>>() { // @Override // public Optional<Principal> apply(HashProvider hashProvider) { // return hashProvider.validateHash(password, principalDetail) ? // Optional.of(new Principal(principalDetail.getUsername())) : // Optional.<Principal>absent(); // } // } // ); // } // // // private Optional<? extends HashProvider> getHashProvider(final String hashConfig) { // for (HashProvider provider : hashProviders) { // if (provider.canHandle(hashConfig)) { // return Optional.of(provider); // } // } // return Optional.absent(); // } // // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/Principal.java // @Value // public class Principal { // private final String id; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/wire/GoAuthenticationRequestDecoder.java // public class GoAuthenticationRequestDecoder { // // public final String pluginId = Constants.PLUGIN_ID; // private static final Logger LOGGER = Logger.getLoggerFor(GoAuthenticationRequestDecoder.class); // // private static Gson gson = new GsonBuilder().registerTypeAdapter( // AuthenticationRequest.class, new JsonDeserializer<AuthenticationRequest>() { // @Override // public AuthenticationRequest deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) // throws JsonParseException { // if (!json.isJsonObject()) { // throw new JsonParseException("Malformed json for AuthenticationRequest"); // } // // return new AuthenticationRequest( // getAsStringOrFail(json.getAsJsonObject(), "username"), // getAsStringOrFail(json.getAsJsonObject(), "password") // ); // // } // }).create(); // // public static String getAsStringOrFail(JsonObject object, String fieldName) throws JsonParseException { // JsonElement username = object.get(fieldName); // if (username != null && username.isJsonPrimitive()) { // return username.getAsString(); // } else { // throw new JsonParseException(format("Expected a string value for field %s", fieldName)); // } // } // // public Optional<AuthenticationRequest> decode(GoPluginApiRequest goRequest) { // try { // AuthenticationRequest request = gson.getAdapter(AuthenticationRequest.class).fromJson(goRequest.requestBody()); // return hasRequiredFields(request) ? Optional.of(request) : Optional.<AuthenticationRequest>absent(); // } catch (IOException e) { // LOGGER.warn("IOException when parsing incoming authentication request.", e); // return Optional.absent(); // } catch (JsonParseException e) { // LOGGER.warn("Failure when parsing incoming authentication request.", e); // return Optional.absent(); // } // } // // private boolean hasRequiredFields(AuthenticationRequest request) { // return request.getPassword() != null && request.getUsername() != null; // } // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/wire/GoUserEncoder.java // public class GoUserEncoder { // // public GoPluginApiResponse encode(final String username) { // final DefaultGoPluginApiResponse response = new DefaultGoPluginApiResponse(200); // final ImmutableMap<String, ImmutableMap<String, String>> map = // ImmutableMap.of("user", ImmutableMap.of("username", username)); // response.setResponseBody(Json.toJson(map)); // return response; // } // // public GoPluginApiResponse noUser() { // return new DefaultGoPluginApiResponse(200); // } // // }
import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.authentication.AuthenticationRequest; import com.thoughtworks.go.strongauth.authentication.Authenticator; import com.thoughtworks.go.strongauth.authentication.Principal; import com.thoughtworks.go.strongauth.wire.GoAuthenticationRequestDecoder; import com.thoughtworks.go.strongauth.wire.GoUserEncoder; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package com.thoughtworks.go.strongauth.handlers; public class AuthenticationHandlerTest { private GoAuthenticationRequestDecoder requestDecoder = mock(GoAuthenticationRequestDecoder.class);
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/AuthenticationRequest.java // @Value // public class AuthenticationRequest { // private final String username; // private final String password; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/Authenticator.java // public class Authenticator { // // public final String pluginId = Constants.PLUGIN_ID; // private static final Logger LOGGER = Logger.getLoggerFor(Authenticator.class); // private final List<? extends HashProvider> hashProviders; // // public Authenticator( // final PrincipalDetailSource principalDetailSource, // final List<? extends HashProvider> hashProviders // ) { // this.principalDetailSource = principalDetailSource; // this.hashProviders = hashProviders; // } // // private PrincipalDetailSource principalDetailSource; // // public Optional<Principal> authenticate(final String username, final String password) { // LOGGER.info(format("Login attempt for user %s", username)); // Optional<Principal> maybePrincipal = flatMap(principalDetailSource.byUsername(username), new Function<PrincipalDetail, Optional<Principal>>() { // @Override // public Optional<Principal> apply(PrincipalDetail principalDetail) { // return toPrincipal(principalDetail, password); // } // }); // // if (!maybePrincipal.isPresent()) { // LOGGER.warn(format("Login attempt for user %s failed.", username)); // } // return maybePrincipal; // } // // private Optional<Principal> toPrincipal(final PrincipalDetail principalDetail, final String password) { // Optional<? extends HashProvider> maybeHashProvider = getHashProvider(principalDetail.getHashConfiguration()); // // return flatMap( // maybeHashProvider, // new Function<HashProvider, Optional<Principal>>() { // @Override // public Optional<Principal> apply(HashProvider hashProvider) { // return hashProvider.validateHash(password, principalDetail) ? // Optional.of(new Principal(principalDetail.getUsername())) : // Optional.<Principal>absent(); // } // } // ); // } // // // private Optional<? extends HashProvider> getHashProvider(final String hashConfig) { // for (HashProvider provider : hashProviders) { // if (provider.canHandle(hashConfig)) { // return Optional.of(provider); // } // } // return Optional.absent(); // } // // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/Principal.java // @Value // public class Principal { // private final String id; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/wire/GoAuthenticationRequestDecoder.java // public class GoAuthenticationRequestDecoder { // // public final String pluginId = Constants.PLUGIN_ID; // private static final Logger LOGGER = Logger.getLoggerFor(GoAuthenticationRequestDecoder.class); // // private static Gson gson = new GsonBuilder().registerTypeAdapter( // AuthenticationRequest.class, new JsonDeserializer<AuthenticationRequest>() { // @Override // public AuthenticationRequest deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) // throws JsonParseException { // if (!json.isJsonObject()) { // throw new JsonParseException("Malformed json for AuthenticationRequest"); // } // // return new AuthenticationRequest( // getAsStringOrFail(json.getAsJsonObject(), "username"), // getAsStringOrFail(json.getAsJsonObject(), "password") // ); // // } // }).create(); // // public static String getAsStringOrFail(JsonObject object, String fieldName) throws JsonParseException { // JsonElement username = object.get(fieldName); // if (username != null && username.isJsonPrimitive()) { // return username.getAsString(); // } else { // throw new JsonParseException(format("Expected a string value for field %s", fieldName)); // } // } // // public Optional<AuthenticationRequest> decode(GoPluginApiRequest goRequest) { // try { // AuthenticationRequest request = gson.getAdapter(AuthenticationRequest.class).fromJson(goRequest.requestBody()); // return hasRequiredFields(request) ? Optional.of(request) : Optional.<AuthenticationRequest>absent(); // } catch (IOException e) { // LOGGER.warn("IOException when parsing incoming authentication request.", e); // return Optional.absent(); // } catch (JsonParseException e) { // LOGGER.warn("Failure when parsing incoming authentication request.", e); // return Optional.absent(); // } // } // // private boolean hasRequiredFields(AuthenticationRequest request) { // return request.getPassword() != null && request.getUsername() != null; // } // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/wire/GoUserEncoder.java // public class GoUserEncoder { // // public GoPluginApiResponse encode(final String username) { // final DefaultGoPluginApiResponse response = new DefaultGoPluginApiResponse(200); // final ImmutableMap<String, ImmutableMap<String, String>> map = // ImmutableMap.of("user", ImmutableMap.of("username", username)); // response.setResponseBody(Json.toJson(map)); // return response; // } // // public GoPluginApiResponse noUser() { // return new DefaultGoPluginApiResponse(200); // } // // } // Path: src/test/java/com/thoughtworks/go/strongauth/handlers/AuthenticationHandlerTest.java import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.authentication.AuthenticationRequest; import com.thoughtworks.go.strongauth.authentication.Authenticator; import com.thoughtworks.go.strongauth.authentication.Principal; import com.thoughtworks.go.strongauth.wire.GoAuthenticationRequestDecoder; import com.thoughtworks.go.strongauth.wire.GoUserEncoder; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package com.thoughtworks.go.strongauth.handlers; public class AuthenticationHandlerTest { private GoAuthenticationRequestDecoder requestDecoder = mock(GoAuthenticationRequestDecoder.class);
private Authenticator authenticator = mock(Authenticator.class);
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java
// Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public class ChangeMonitor<EVT_TYPE, VALUE_TYPE> { // // private static final long MIN_DELAY = 100; // private static final long MAX_DELAY = 2000; // // private boolean running = true; // private ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate; // private final List<MonitorListener<EVT_TYPE>> changeListeners = new LinkedList<>(); // private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); // // private static final Logger LOGGER = Logger.getLoggerFor(ChangeMonitor.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ChangeMonitor(ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate) { // this.delegate = delegate; // } // // public void start() { // checkForChange(MIN_DELAY, Optional.<VALUE_TYPE>absent()); // } // // private Function<Long, Long> incrementalChange = new Function<Long, Long>() { // @Override // public Long apply(final Long in) { // if (in > MAX_DELAY) { // return MAX_DELAY; // } // return in * 2; // } // }; // // private void checkForChange(final long delay, final Optional<VALUE_TYPE> oldMaybeValue) { // executorService.schedule(new Runnable() { // @Override // public void run() { // try { // final Optional<VALUE_TYPE> newMaybeValue = delegate.newValue(); // final long newDelay; // if (valueChanged(newMaybeValue, oldMaybeValue)) { // LOGGER.info(String.format("Value changed from %s to %s", oldMaybeValue, newMaybeValue)); // LOGGER.info(String.format("Instance: %s", this)); // final EVT_TYPE notifyEvent = delegate.createNotifyEvent(newMaybeValue, oldMaybeValue); // notifyListeners(notifyEvent); // newDelay = MIN_DELAY; // } else { // newDelay = incrementalChange.apply(delay); // } // // if (running) { // checkForChange(newDelay, newMaybeValue); // } // } catch (Exception e) { // LOGGER.error("ChangeMonitor failed.", e); // } // } // // }, delay, TimeUnit.MILLISECONDS); // // } // // private boolean valueChanged(Optional<?> newValue, Optional<?> oldValue) { // return !oldValue.equals(newValue); // } // // public void stop() { // synchronized (changeListeners) { // changeListeners.clear(); // } // running = false; // } // // private void notifyListeners(final EVT_TYPE event) { // final List<MonitorListener<EVT_TYPE>> listeners; // synchronized (changeListeners) { // listeners = new ArrayList<>(changeListeners); // } // // executorService.submit(new Runnable() { // @Override // public void run() { // for (MonitorListener<EVT_TYPE> listener : listeners) { // listener.changed(event); // } // } // }); // } // // public void addChangeListener(MonitorListener<EVT_TYPE> sourceChangeListener) { // synchronized (changeListeners) { // if (!changeListeners.contains(sourceChangeListener)) { // changeListeners.add(sourceChangeListener); // } // } // } // // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // } // // public interface MonitorListener<T> { // void changed(T event); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // }
import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.util.ChangeMonitor; import com.thoughtworks.go.strongauth.util.ChangeMonitor.ChangeMonitorDelegate;
package com.thoughtworks.go.strongauth.config; public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { private final GoAPI goAPI;
// Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public class ChangeMonitor<EVT_TYPE, VALUE_TYPE> { // // private static final long MIN_DELAY = 100; // private static final long MAX_DELAY = 2000; // // private boolean running = true; // private ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate; // private final List<MonitorListener<EVT_TYPE>> changeListeners = new LinkedList<>(); // private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); // // private static final Logger LOGGER = Logger.getLoggerFor(ChangeMonitor.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ChangeMonitor(ChangeMonitorDelegate<? extends EVT_TYPE, VALUE_TYPE> delegate) { // this.delegate = delegate; // } // // public void start() { // checkForChange(MIN_DELAY, Optional.<VALUE_TYPE>absent()); // } // // private Function<Long, Long> incrementalChange = new Function<Long, Long>() { // @Override // public Long apply(final Long in) { // if (in > MAX_DELAY) { // return MAX_DELAY; // } // return in * 2; // } // }; // // private void checkForChange(final long delay, final Optional<VALUE_TYPE> oldMaybeValue) { // executorService.schedule(new Runnable() { // @Override // public void run() { // try { // final Optional<VALUE_TYPE> newMaybeValue = delegate.newValue(); // final long newDelay; // if (valueChanged(newMaybeValue, oldMaybeValue)) { // LOGGER.info(String.format("Value changed from %s to %s", oldMaybeValue, newMaybeValue)); // LOGGER.info(String.format("Instance: %s", this)); // final EVT_TYPE notifyEvent = delegate.createNotifyEvent(newMaybeValue, oldMaybeValue); // notifyListeners(notifyEvent); // newDelay = MIN_DELAY; // } else { // newDelay = incrementalChange.apply(delay); // } // // if (running) { // checkForChange(newDelay, newMaybeValue); // } // } catch (Exception e) { // LOGGER.error("ChangeMonitor failed.", e); // } // } // // }, delay, TimeUnit.MILLISECONDS); // // } // // private boolean valueChanged(Optional<?> newValue, Optional<?> oldValue) { // return !oldValue.equals(newValue); // } // // public void stop() { // synchronized (changeListeners) { // changeListeners.clear(); // } // running = false; // } // // private void notifyListeners(final EVT_TYPE event) { // final List<MonitorListener<EVT_TYPE>> listeners; // synchronized (changeListeners) { // listeners = new ArrayList<>(changeListeners); // } // // executorService.submit(new Runnable() { // @Override // public void run() { // for (MonitorListener<EVT_TYPE> listener : listeners) { // listener.changed(event); // } // } // }); // } // // public void addChangeListener(MonitorListener<EVT_TYPE> sourceChangeListener) { // synchronized (changeListeners) { // if (!changeListeners.contains(sourceChangeListener)) { // changeListeners.add(sourceChangeListener); // } // } // } // // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // } // // public interface MonitorListener<T> { // void changed(T event); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/ChangeMonitor.java // public interface ChangeMonitorDelegate<EVENT_TYPE, VALUE_TYPE> { // EVENT_TYPE createNotifyEvent(Optional<VALUE_TYPE> newMaybeValue, Optional<VALUE_TYPE> oldMaybeValue); // // Optional<VALUE_TYPE> newValue(); // } // Path: src/main/java/com/thoughtworks/go/strongauth/config/ConfigurationMonitor.java import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.util.ChangeMonitor; import com.thoughtworks.go.strongauth.util.ChangeMonitor.ChangeMonitorDelegate; package com.thoughtworks.go.strongauth.config; public class ConfigurationMonitor implements ChangeMonitorDelegate<ConfigurationChangedEvent, PluginConfiguration> { private final GoAPI goAPI;
private ChangeMonitor<ConfigurationChangedEvent, PluginConfiguration> changeMonitor;
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/StrongAuthPlugin.java
// Path: src/main/java/com/thoughtworks/go/strongauth/handlers/Handlers.java // public class Handlers { // // private final Map<String, Handler> handlers; // // public Handlers(final Map<String, Handler> handlers) { // this.handlers = handlers; // } // // public Handler get(String requestName) { // if (handlers.containsKey(requestName)) { // return handlers.get(requestName); // } // throw new RuntimeException(format("Handler for request of type: %s is not implemented", requestName)); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // }
import com.thoughtworks.go.plugin.api.GoApplicationAccessor; import com.thoughtworks.go.plugin.api.GoPlugin; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.plugin.api.annotation.Extension; import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.handlers.Handlers; import com.thoughtworks.go.strongauth.util.Constants; import static java.util.Arrays.asList;
package com.thoughtworks.go.strongauth; @Extension public class StrongAuthPlugin implements GoPlugin {
// Path: src/main/java/com/thoughtworks/go/strongauth/handlers/Handlers.java // public class Handlers { // // private final Map<String, Handler> handlers; // // public Handlers(final Map<String, Handler> handlers) { // this.handlers = handlers; // } // // public Handler get(String requestName) { // if (handlers.containsKey(requestName)) { // return handlers.get(requestName); // } // throw new RuntimeException(format("Handler for request of type: %s is not implemented", requestName)); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // Path: src/main/java/com/thoughtworks/go/strongauth/StrongAuthPlugin.java import com.thoughtworks.go.plugin.api.GoApplicationAccessor; import com.thoughtworks.go.plugin.api.GoPlugin; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.plugin.api.annotation.Extension; import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.handlers.Handlers; import com.thoughtworks.go.strongauth.util.Constants; import static java.util.Arrays.asList; package com.thoughtworks.go.strongauth; @Extension public class StrongAuthPlugin implements GoPlugin {
public final String pluginId = Constants.PLUGIN_ID;
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/StrongAuthPlugin.java
// Path: src/main/java/com/thoughtworks/go/strongauth/handlers/Handlers.java // public class Handlers { // // private final Map<String, Handler> handlers; // // public Handlers(final Map<String, Handler> handlers) { // this.handlers = handlers; // } // // public Handler get(String requestName) { // if (handlers.containsKey(requestName)) { // return handlers.get(requestName); // } // throw new RuntimeException(format("Handler for request of type: %s is not implemented", requestName)); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // }
import com.thoughtworks.go.plugin.api.GoApplicationAccessor; import com.thoughtworks.go.plugin.api.GoPlugin; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.plugin.api.annotation.Extension; import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.handlers.Handlers; import com.thoughtworks.go.strongauth.util.Constants; import static java.util.Arrays.asList;
package com.thoughtworks.go.strongauth; @Extension public class StrongAuthPlugin implements GoPlugin { public final String pluginId = Constants.PLUGIN_ID; private static final Logger LOGGER = Logger.getLoggerFor(StrongAuthPlugin.class); private ComponentFactory componentFactory; private GoPluginIdentifier goPluginIdentifier = new GoPluginIdentifier("authentication", asList("1.0"));
// Path: src/main/java/com/thoughtworks/go/strongauth/handlers/Handlers.java // public class Handlers { // // private final Map<String, Handler> handlers; // // public Handlers(final Map<String, Handler> handlers) { // this.handlers = handlers; // } // // public Handler get(String requestName) { // if (handlers.containsKey(requestName)) { // return handlers.get(requestName); // } // throw new RuntimeException(format("Handler for request of type: %s is not implemented", requestName)); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // Path: src/main/java/com/thoughtworks/go/strongauth/StrongAuthPlugin.java import com.thoughtworks.go.plugin.api.GoApplicationAccessor; import com.thoughtworks.go.plugin.api.GoPlugin; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.plugin.api.annotation.Extension; import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import com.thoughtworks.go.strongauth.handlers.Handlers; import com.thoughtworks.go.strongauth.util.Constants; import static java.util.Arrays.asList; package com.thoughtworks.go.strongauth; @Extension public class StrongAuthPlugin implements GoPlugin { public final String pluginId = Constants.PLUGIN_ID; private static final Logger LOGGER = Logger.getLoggerFor(StrongAuthPlugin.class); private ComponentFactory componentFactory; private GoPluginIdentifier goPluginIdentifier = new GoPluginIdentifier("authentication", asList("1.0"));
private Handlers handlers;
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java // @Value // public class PrincipalDetail { // private final String username; // private final String passwordHash; // private final String salt; // private final String hashConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetailSource.java // public interface PrincipalDetailSource { // Optional<PrincipalDetail> byUsername(String username); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeEvent.java // @Value // public class SourceChangeEvent { // // private InputStream inputStream; // private String description; // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.strongauth.authentication.PrincipalDetail; import com.thoughtworks.go.strongauth.authentication.PrincipalDetailSource; import com.thoughtworks.go.strongauth.util.Constants; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeEvent; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static org.apache.commons.io.IOUtils.toBufferedReader;
package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class);
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java // @Value // public class PrincipalDetail { // private final String username; // private final String passwordHash; // private final String salt; // private final String hashConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetailSource.java // public interface PrincipalDetailSource { // Optional<PrincipalDetail> byUsername(String username); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeEvent.java // @Value // public class SourceChangeEvent { // // private InputStream inputStream; // private String description; // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.strongauth.authentication.PrincipalDetail; import com.thoughtworks.go.strongauth.authentication.PrincipalDetailSource; import com.thoughtworks.go.strongauth.util.Constants; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeEvent; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static org.apache.commons.io.IOUtils.toBufferedReader; package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class);
public final String pluginId = Constants.PLUGIN_ID;
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java // @Value // public class PrincipalDetail { // private final String username; // private final String passwordHash; // private final String salt; // private final String hashConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetailSource.java // public interface PrincipalDetailSource { // Optional<PrincipalDetail> byUsername(String username); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeEvent.java // @Value // public class SourceChangeEvent { // // private InputStream inputStream; // private String description; // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.strongauth.authentication.PrincipalDetail; import com.thoughtworks.go.strongauth.authentication.PrincipalDetailSource; import com.thoughtworks.go.strongauth.util.Constants; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeEvent; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static org.apache.commons.io.IOUtils.toBufferedReader;
package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); public final String pluginId = Constants.PLUGIN_ID;
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java // @Value // public class PrincipalDetail { // private final String username; // private final String passwordHash; // private final String salt; // private final String hashConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetailSource.java // public interface PrincipalDetailSource { // Optional<PrincipalDetail> byUsername(String username); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeEvent.java // @Value // public class SourceChangeEvent { // // private InputStream inputStream; // private String description; // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.strongauth.authentication.PrincipalDetail; import com.thoughtworks.go.strongauth.authentication.PrincipalDetailSource; import com.thoughtworks.go.strongauth.util.Constants; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeEvent; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static org.apache.commons.io.IOUtils.toBufferedReader; package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); public final String pluginId = Constants.PLUGIN_ID;
public ConfigurableUserPrincipalDetailSource(InputStreamSource passwordSource) {
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java // @Value // public class PrincipalDetail { // private final String username; // private final String passwordHash; // private final String salt; // private final String hashConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetailSource.java // public interface PrincipalDetailSource { // Optional<PrincipalDetail> byUsername(String username); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeEvent.java // @Value // public class SourceChangeEvent { // // private InputStream inputStream; // private String description; // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.strongauth.authentication.PrincipalDetail; import com.thoughtworks.go.strongauth.authentication.PrincipalDetailSource; import com.thoughtworks.go.strongauth.util.Constants; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeEvent; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static org.apache.commons.io.IOUtils.toBufferedReader;
package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); public final String pluginId = Constants.PLUGIN_ID; public ConfigurableUserPrincipalDetailSource(InputStreamSource passwordSource) { try { loadSource(passwordSource.inputStream()); } catch (IOException e) { LOGGER.warn("Missing password file. No credentials loaded."); }
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java // @Value // public class PrincipalDetail { // private final String username; // private final String passwordHash; // private final String salt; // private final String hashConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetailSource.java // public interface PrincipalDetailSource { // Optional<PrincipalDetail> byUsername(String username); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeEvent.java // @Value // public class SourceChangeEvent { // // private InputStream inputStream; // private String description; // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.strongauth.authentication.PrincipalDetail; import com.thoughtworks.go.strongauth.authentication.PrincipalDetailSource; import com.thoughtworks.go.strongauth.util.Constants; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeEvent; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static org.apache.commons.io.IOUtils.toBufferedReader; package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); public final String pluginId = Constants.PLUGIN_ID; public ConfigurableUserPrincipalDetailSource(InputStreamSource passwordSource) { try { loadSource(passwordSource.inputStream()); } catch (IOException e) { LOGGER.warn("Missing password file. No credentials loaded."); }
passwordSource.addChangeListener(new SourceChangeListener() {
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java // @Value // public class PrincipalDetail { // private final String username; // private final String passwordHash; // private final String salt; // private final String hashConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetailSource.java // public interface PrincipalDetailSource { // Optional<PrincipalDetail> byUsername(String username); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeEvent.java // @Value // public class SourceChangeEvent { // // private InputStream inputStream; // private String description; // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.strongauth.authentication.PrincipalDetail; import com.thoughtworks.go.strongauth.authentication.PrincipalDetailSource; import com.thoughtworks.go.strongauth.util.Constants; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeEvent; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static org.apache.commons.io.IOUtils.toBufferedReader;
package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); public final String pluginId = Constants.PLUGIN_ID; public ConfigurableUserPrincipalDetailSource(InputStreamSource passwordSource) { try { loadSource(passwordSource.inputStream()); } catch (IOException e) { LOGGER.warn("Missing password file. No credentials loaded."); } passwordSource.addChangeListener(new SourceChangeListener() { @Override
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetail.java // @Value // public class PrincipalDetail { // private final String username; // private final String passwordHash; // private final String salt; // private final String hashConfiguration; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/PrincipalDetailSource.java // public interface PrincipalDetailSource { // Optional<PrincipalDetail> byUsername(String username); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeEvent.java // @Value // public class SourceChangeEvent { // // private InputStream inputStream; // private String description; // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java import com.google.common.base.Optional; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.strongauth.authentication.PrincipalDetail; import com.thoughtworks.go.strongauth.authentication.PrincipalDetailSource; import com.thoughtworks.go.strongauth.util.Constants; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeEvent; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static org.apache.commons.io.IOUtils.toBufferedReader; package com.thoughtworks.go.strongauth.authentication.principalDetailSources; public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); public final String pluginId = Constants.PLUGIN_ID; public ConfigurableUserPrincipalDetailSource(InputStreamSource passwordSource) { try { loadSource(passwordSource.inputStream()); } catch (IOException e) { LOGGER.warn("Missing password file. No credentials loaded."); } passwordSource.addChangeListener(new SourceChangeListener() { @Override
public void sourceChanged(SourceChangeEvent event) {
danielsomerfield/go-strong-auth-plugin
src/test/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoderTest.java
// Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public class Json { // private static Gson gson = new Gson(); // // public static Map<String, String> toMapOfStrings(String jsonValue) { // Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType(); // return gson.fromJson(jsonValue, mapOfStringToStringType); // } // // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // public static String toJson(Object anything) { // return gson.toJson(anything); // } // }
import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.Json; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.thoughtworks.go.strongauth.wire; public class PluginConfigurationDecoderTest { @Test public void testValidConfiguration() { DefaultGoApiResponse response = new DefaultGoApiResponse(200);
// Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public class Json { // private static Gson gson = new Gson(); // // public static Map<String, String> toMapOfStrings(String jsonValue) { // Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType(); // return gson.fromJson(jsonValue, mapOfStringToStringType); // } // // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // public static String toJson(Object anything) { // return gson.toJson(anything); // } // } // Path: src/test/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoderTest.java import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.Json; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.thoughtworks.go.strongauth.wire; public class PluginConfigurationDecoderTest { @Test public void testValidConfiguration() { DefaultGoApiResponse response = new DefaultGoApiResponse(200);
response.setResponseBody(Json.toJson(ImmutableMap.of("PASSWORD_FILE_PATH", "/foo/bar")));
danielsomerfield/go-strong-auth-plugin
src/test/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoderTest.java
// Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public class Json { // private static Gson gson = new Gson(); // // public static Map<String, String> toMapOfStrings(String jsonValue) { // Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType(); // return gson.fromJson(jsonValue, mapOfStringToStringType); // } // // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // public static String toJson(Object anything) { // return gson.toJson(anything); // } // }
import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.Json; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.thoughtworks.go.strongauth.wire; public class PluginConfigurationDecoderTest { @Test public void testValidConfiguration() { DefaultGoApiResponse response = new DefaultGoApiResponse(200); response.setResponseBody(Json.toJson(ImmutableMap.of("PASSWORD_FILE_PATH", "/foo/bar")));
// Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public class Json { // private static Gson gson = new Gson(); // // public static Map<String, String> toMapOfStrings(String jsonValue) { // Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType(); // return gson.fromJson(jsonValue, mapOfStringToStringType); // } // // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // public static String toJson(Object anything) { // return gson.toJson(anything); // } // } // Path: src/test/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoderTest.java import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.Json; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.thoughtworks.go.strongauth.wire; public class PluginConfigurationDecoderTest { @Test public void testValidConfiguration() { DefaultGoApiResponse response = new DefaultGoApiResponse(200); response.setResponseBody(Json.toJson(ImmutableMap.of("PASSWORD_FILE_PATH", "/foo/bar")));
PluginConfiguration configuration = new PluginConfigurationDecoder().decode(response);
danielsomerfield/go-strong-auth-plugin
src/test/java/com/thoughtworks/go/strongauth/config/GoAPITest.java
// Path: src/main/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoder.java // public class PluginConfigurationDecoder { // public PluginConfiguration decode(GoApiResponse response) { // if (response.responseCode() == 200) { // return parseConfiguration(response.responseBody()); // } else { // return defaultConfiguration(); // } // } // // private PluginConfiguration parseConfiguration(String body) { // if (body == null) { // return defaultConfiguration(); // } else { // return fromMap(Json.toMapOfStrings(body)); // } // } // // private PluginConfiguration fromMap(Map<String, String> configMap) { // return new PluginConfiguration(configMap.get("PASSWORD_FILE_PATH")); // } // // public PluginConfiguration defaultConfiguration() { // return new PluginConfiguration(); // } // }
import com.thoughtworks.go.plugin.api.GoApplicationAccessor; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.plugin.api.request.GoApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse; import com.thoughtworks.go.strongauth.wire.PluginConfigurationDecoder; import org.hamcrest.CustomMatcher; import org.json.JSONObject; import org.junit.Test; import org.skyscreamer.jsonassert.JSONCompareMode; import java.io.File; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.skyscreamer.jsonassert.JSONCompare.compareJSON;
package com.thoughtworks.go.strongauth.config; public class GoAPITest { final GoPluginIdentifier goPluginIdentifier = new GoPluginIdentifier("authentication", singletonList("1.0")); final GoApplicationAccessor goApplicationAccessor = mock(GoApplicationAccessor.class);
// Path: src/main/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoder.java // public class PluginConfigurationDecoder { // public PluginConfiguration decode(GoApiResponse response) { // if (response.responseCode() == 200) { // return parseConfiguration(response.responseBody()); // } else { // return defaultConfiguration(); // } // } // // private PluginConfiguration parseConfiguration(String body) { // if (body == null) { // return defaultConfiguration(); // } else { // return fromMap(Json.toMapOfStrings(body)); // } // } // // private PluginConfiguration fromMap(Map<String, String> configMap) { // return new PluginConfiguration(configMap.get("PASSWORD_FILE_PATH")); // } // // public PluginConfiguration defaultConfiguration() { // return new PluginConfiguration(); // } // } // Path: src/test/java/com/thoughtworks/go/strongauth/config/GoAPITest.java import com.thoughtworks.go.plugin.api.GoApplicationAccessor; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.plugin.api.request.GoApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse; import com.thoughtworks.go.strongauth.wire.PluginConfigurationDecoder; import org.hamcrest.CustomMatcher; import org.json.JSONObject; import org.junit.Test; import org.skyscreamer.jsonassert.JSONCompareMode; import java.io.File; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.skyscreamer.jsonassert.JSONCompare.compareJSON; package com.thoughtworks.go.strongauth.config; public class GoAPITest { final GoPluginIdentifier goPluginIdentifier = new GoPluginIdentifier("authentication", singletonList("1.0")); final GoApplicationAccessor goApplicationAccessor = mock(GoApplicationAccessor.class);
final PluginConfigurationDecoder pluginConfigurationDecoder = new PluginConfigurationDecoder();
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/handlers/PluginConfigurationHandler.java
// Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // }
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.MapBuilder.create;
package com.thoughtworks.go.strongauth.handlers; public class PluginConfigurationHandler implements Handler { private static final String CONFIG_WEB_AUTH = "supports-web-based-authentication"; private static final String CONFIG_PASSWORD_AUTH = "supports-password-based-authentication"; @Override public GoPluginApiResponse call(GoPluginApiRequest request) {
// Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // Path: src/main/java/com/thoughtworks/go/strongauth/handlers/PluginConfigurationHandler.java import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; package com.thoughtworks.go.strongauth.handlers; public class PluginConfigurationHandler implements Handler { private static final String CONFIG_WEB_AUTH = "supports-web-based-authentication"; private static final String CONFIG_PASSWORD_AUTH = "supports-password-based-authentication"; @Override public GoPluginApiResponse call(GoPluginApiRequest request) {
String responseBody = toJson(create()
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/handlers/PluginConfigurationHandler.java
// Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // }
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.MapBuilder.create;
package com.thoughtworks.go.strongauth.handlers; public class PluginConfigurationHandler implements Handler { private static final String CONFIG_WEB_AUTH = "supports-web-based-authentication"; private static final String CONFIG_PASSWORD_AUTH = "supports-password-based-authentication"; @Override public GoPluginApiResponse call(GoPluginApiRequest request) {
// Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public static String toJson(Object anything) { // return gson.toJson(anything); // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/MapBuilder.java // public static <KeyType, ValueType> MapBuilder<KeyType, ValueType> create() { // return new MapBuilder<>(); // } // Path: src/main/java/com/thoughtworks/go/strongauth/handlers/PluginConfigurationHandler.java import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import static com.thoughtworks.go.strongauth.util.Json.toJson; import static com.thoughtworks.go.strongauth.util.MapBuilder.create; package com.thoughtworks.go.strongauth.handlers; public class PluginConfigurationHandler implements Handler { private static final String CONFIG_WEB_AUTH = "supports-web-based-authentication"; private static final String CONFIG_PASSWORD_AUTH = "supports-password-based-authentication"; @Override public GoPluginApiResponse call(GoPluginApiRequest request) {
String responseBody = toJson(create()
danielsomerfield/go-strong-auth-plugin
src/test/java/com/thoughtworks/go/strongauth/authentication/AuthenticatorIntegrationTest.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/hash/BCryptProvider.java // public class BCryptProvider implements HashProvider { // @Override // public boolean validateHash(String password, PrincipalDetail principalDetail) { // return BCrypt.checkpw(password, principalDetail.getPasswordHash()); // } // // @Override // public boolean canHandle(String hashConfig) { // return hashConfig.equals("bcrypt"); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/hash/PBESpecHashProvider.java // public class PBESpecHashProvider implements HashProvider { // public final String pluginId = Constants.PLUGIN_ID; // private static final Logger LOGGER = Logger.getLoggerFor(PBESpecHashProvider.class); // // private static final Pattern HASH_CONFIG_PATTERN = Pattern.compile("^(\\w+)\\((\\d+), (\\d+)\\)$"); // // @Override // public boolean validateHash(final String password, final PrincipalDetail principalDetail) { // Optional<HashConfig> maybeHashConfig = parseHashConfig(principalDetail.getHashConfiguration()); // return maybeHashConfig.transform(new Function<HashConfig, Boolean>() { // @Override // public Boolean apply(HashConfig hashConfig) { // PBEKeySpec spec = new PBEKeySpec( // password.toCharArray(), // Base64.decodeBase64(principalDetail.getSalt()), // hashConfig.getIterations(), // hashConfig.getKeySize()); // try { // String encoded = Hex.encodeHexString(SecretKeyFactory.getInstance(hashConfig.getAlgorithm()).generateSecret(spec).getEncoded()); // return encoded.equals(principalDetail.getPasswordHash()); // } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { // LOGGER.warn("build hash", e); // return false; // } // } // }).or(false); // } // // @Override // public boolean canHandle(String hashConfig) { // return parseHashConfig(hashConfig).isPresent(); // } // // private static Optional<HashConfig> parseHashConfig(String configString) { // final Matcher matcher = HASH_CONFIG_PATTERN.matcher(configString); // if (matcher.find()) { // return Optional.of(new HashConfig( // matcher.group(1), // parseInt(matcher.group(2)), // parseInt(matcher.group(3))) // ); // } else { // return Optional.absent(); // } // } // // @Value // private static class HashConfig { // private final String algorithm; // private final int iterations; // private final int keySize; // } // }
import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.thoughtworks.go.strongauth.authentication.hash.BCryptProvider; import com.thoughtworks.go.strongauth.authentication.hash.PBESpecHashProvider; import lombok.SneakyThrows; import org.apache.commons.codec.binary.Base64; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package com.thoughtworks.go.strongauth.authentication; public class AuthenticatorIntegrationTest { private PrincipalDetailSource principalDetailSource = mock(PrincipalDetailSource.class); private List<? extends HashProvider> hashProviders = ImmutableList.of(
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/hash/BCryptProvider.java // public class BCryptProvider implements HashProvider { // @Override // public boolean validateHash(String password, PrincipalDetail principalDetail) { // return BCrypt.checkpw(password, principalDetail.getPasswordHash()); // } // // @Override // public boolean canHandle(String hashConfig) { // return hashConfig.equals("bcrypt"); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/hash/PBESpecHashProvider.java // public class PBESpecHashProvider implements HashProvider { // public final String pluginId = Constants.PLUGIN_ID; // private static final Logger LOGGER = Logger.getLoggerFor(PBESpecHashProvider.class); // // private static final Pattern HASH_CONFIG_PATTERN = Pattern.compile("^(\\w+)\\((\\d+), (\\d+)\\)$"); // // @Override // public boolean validateHash(final String password, final PrincipalDetail principalDetail) { // Optional<HashConfig> maybeHashConfig = parseHashConfig(principalDetail.getHashConfiguration()); // return maybeHashConfig.transform(new Function<HashConfig, Boolean>() { // @Override // public Boolean apply(HashConfig hashConfig) { // PBEKeySpec spec = new PBEKeySpec( // password.toCharArray(), // Base64.decodeBase64(principalDetail.getSalt()), // hashConfig.getIterations(), // hashConfig.getKeySize()); // try { // String encoded = Hex.encodeHexString(SecretKeyFactory.getInstance(hashConfig.getAlgorithm()).generateSecret(spec).getEncoded()); // return encoded.equals(principalDetail.getPasswordHash()); // } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { // LOGGER.warn("build hash", e); // return false; // } // } // }).or(false); // } // // @Override // public boolean canHandle(String hashConfig) { // return parseHashConfig(hashConfig).isPresent(); // } // // private static Optional<HashConfig> parseHashConfig(String configString) { // final Matcher matcher = HASH_CONFIG_PATTERN.matcher(configString); // if (matcher.find()) { // return Optional.of(new HashConfig( // matcher.group(1), // parseInt(matcher.group(2)), // parseInt(matcher.group(3))) // ); // } else { // return Optional.absent(); // } // } // // @Value // private static class HashConfig { // private final String algorithm; // private final int iterations; // private final int keySize; // } // } // Path: src/test/java/com/thoughtworks/go/strongauth/authentication/AuthenticatorIntegrationTest.java import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.thoughtworks.go.strongauth.authentication.hash.BCryptProvider; import com.thoughtworks.go.strongauth.authentication.hash.PBESpecHashProvider; import lombok.SneakyThrows; import org.apache.commons.codec.binary.Base64; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package com.thoughtworks.go.strongauth.authentication; public class AuthenticatorIntegrationTest { private PrincipalDetailSource principalDetailSource = mock(PrincipalDetailSource.class); private List<? extends HashProvider> hashProviders = ImmutableList.of(
new PBESpecHashProvider(),
danielsomerfield/go-strong-auth-plugin
src/test/java/com/thoughtworks/go/strongauth/authentication/AuthenticatorIntegrationTest.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/hash/BCryptProvider.java // public class BCryptProvider implements HashProvider { // @Override // public boolean validateHash(String password, PrincipalDetail principalDetail) { // return BCrypt.checkpw(password, principalDetail.getPasswordHash()); // } // // @Override // public boolean canHandle(String hashConfig) { // return hashConfig.equals("bcrypt"); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/hash/PBESpecHashProvider.java // public class PBESpecHashProvider implements HashProvider { // public final String pluginId = Constants.PLUGIN_ID; // private static final Logger LOGGER = Logger.getLoggerFor(PBESpecHashProvider.class); // // private static final Pattern HASH_CONFIG_PATTERN = Pattern.compile("^(\\w+)\\((\\d+), (\\d+)\\)$"); // // @Override // public boolean validateHash(final String password, final PrincipalDetail principalDetail) { // Optional<HashConfig> maybeHashConfig = parseHashConfig(principalDetail.getHashConfiguration()); // return maybeHashConfig.transform(new Function<HashConfig, Boolean>() { // @Override // public Boolean apply(HashConfig hashConfig) { // PBEKeySpec spec = new PBEKeySpec( // password.toCharArray(), // Base64.decodeBase64(principalDetail.getSalt()), // hashConfig.getIterations(), // hashConfig.getKeySize()); // try { // String encoded = Hex.encodeHexString(SecretKeyFactory.getInstance(hashConfig.getAlgorithm()).generateSecret(spec).getEncoded()); // return encoded.equals(principalDetail.getPasswordHash()); // } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { // LOGGER.warn("build hash", e); // return false; // } // } // }).or(false); // } // // @Override // public boolean canHandle(String hashConfig) { // return parseHashConfig(hashConfig).isPresent(); // } // // private static Optional<HashConfig> parseHashConfig(String configString) { // final Matcher matcher = HASH_CONFIG_PATTERN.matcher(configString); // if (matcher.find()) { // return Optional.of(new HashConfig( // matcher.group(1), // parseInt(matcher.group(2)), // parseInt(matcher.group(3))) // ); // } else { // return Optional.absent(); // } // } // // @Value // private static class HashConfig { // private final String algorithm; // private final int iterations; // private final int keySize; // } // }
import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.thoughtworks.go.strongauth.authentication.hash.BCryptProvider; import com.thoughtworks.go.strongauth.authentication.hash.PBESpecHashProvider; import lombok.SneakyThrows; import org.apache.commons.codec.binary.Base64; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package com.thoughtworks.go.strongauth.authentication; public class AuthenticatorIntegrationTest { private PrincipalDetailSource principalDetailSource = mock(PrincipalDetailSource.class); private List<? extends HashProvider> hashProviders = ImmutableList.of( new PBESpecHashProvider(),
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/hash/BCryptProvider.java // public class BCryptProvider implements HashProvider { // @Override // public boolean validateHash(String password, PrincipalDetail principalDetail) { // return BCrypt.checkpw(password, principalDetail.getPasswordHash()); // } // // @Override // public boolean canHandle(String hashConfig) { // return hashConfig.equals("bcrypt"); // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/authentication/hash/PBESpecHashProvider.java // public class PBESpecHashProvider implements HashProvider { // public final String pluginId = Constants.PLUGIN_ID; // private static final Logger LOGGER = Logger.getLoggerFor(PBESpecHashProvider.class); // // private static final Pattern HASH_CONFIG_PATTERN = Pattern.compile("^(\\w+)\\((\\d+), (\\d+)\\)$"); // // @Override // public boolean validateHash(final String password, final PrincipalDetail principalDetail) { // Optional<HashConfig> maybeHashConfig = parseHashConfig(principalDetail.getHashConfiguration()); // return maybeHashConfig.transform(new Function<HashConfig, Boolean>() { // @Override // public Boolean apply(HashConfig hashConfig) { // PBEKeySpec spec = new PBEKeySpec( // password.toCharArray(), // Base64.decodeBase64(principalDetail.getSalt()), // hashConfig.getIterations(), // hashConfig.getKeySize()); // try { // String encoded = Hex.encodeHexString(SecretKeyFactory.getInstance(hashConfig.getAlgorithm()).generateSecret(spec).getEncoded()); // return encoded.equals(principalDetail.getPasswordHash()); // } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { // LOGGER.warn("build hash", e); // return false; // } // } // }).or(false); // } // // @Override // public boolean canHandle(String hashConfig) { // return parseHashConfig(hashConfig).isPresent(); // } // // private static Optional<HashConfig> parseHashConfig(String configString) { // final Matcher matcher = HASH_CONFIG_PATTERN.matcher(configString); // if (matcher.find()) { // return Optional.of(new HashConfig( // matcher.group(1), // parseInt(matcher.group(2)), // parseInt(matcher.group(3))) // ); // } else { // return Optional.absent(); // } // } // // @Value // private static class HashConfig { // private final String algorithm; // private final int iterations; // private final int keySize; // } // } // Path: src/test/java/com/thoughtworks/go/strongauth/authentication/AuthenticatorIntegrationTest.java import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.thoughtworks.go.strongauth.authentication.hash.BCryptProvider; import com.thoughtworks.go.strongauth.authentication.hash.PBESpecHashProvider; import lombok.SneakyThrows; import org.apache.commons.codec.binary.Base64; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package com.thoughtworks.go.strongauth.authentication; public class AuthenticatorIntegrationTest { private PrincipalDetailSource principalDetailSource = mock(PrincipalDetailSource.class); private List<? extends HashProvider> hashProviders = ImmutableList.of( new PBESpecHashProvider(),
new BCryptProvider()
danielsomerfield/go-strong-auth-plugin
e2e/src/test/java/com/thoughtworks/go/strongauth/glue/StrongAuthGlue.java
// Path: e2e/src/test/java/com/thoughtworks/go/TestHelpers.java // public class TestHelpers { // // @SneakyThrows // public void enableAuth() { // executeHelper("enable-auth.py"); // } // // @SneakyThrows // public void disableAuth() { // executeHelper("disable-auth.py"); // } // // @SneakyThrows // public void clearAuthFile() { // executeHelper("clear-password-file.py"); // } // // @SneakyThrows // public void executeHelper(String helperName, String... params) { // List<String> command = Lists.newArrayList(format("/tmp/test-helpers/%s", helperName)); // command.addAll(asList(params)); // executeDockerCommand(command); // } // // @SneakyThrows // private void executeDockerCommand(List<String> commands) { // List<String> commandList = Lists.newArrayList("./bin/execute-docker-command.sh"); // commandList.addAll(commands); // int response = new ProcessBuilder().command(commandList).inheritIO().start().waitFor(); // if (response != 0) { // throw new RuntimeException(format("Failed to execute %s", commandList.toString())); // } // } // // public void createPBKDF2PasswordEntryFor(String username, String password) { // int iterations = 10000; // int keyLength = 256; // byte[] salt = createSalt(); // String saltString = Base64.encodeBase64String(salt); // String hash = createHash(salt, password, iterations, keyLength); // String entry = format("%s:%s:%s:%s(%s, %s)", username, hash, saltString, "PBKDF2WithHmacSHA1", String.valueOf(iterations), String.valueOf(keyLength)); // executeHelper("insert-password-entry.py", entry); // } // // public void createBCryptPasswordEntryFor(String username, String password) { // String saltString = BCrypt.gensalt(); // String hash = BCrypt.hashpw(password, saltString); // String entry = format("%s:%s::%s", username, hash, "bcrypt"); // executeHelper("insert-password-entry.py", entry); // } // // @SneakyThrows // private String createHash(byte[] salt, String password, int iterations, int keyLength) { // PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, keyLength); // byte[] key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).getEncoded(); // return Hex.encodeHexString(key); // } // // private byte[] createSalt() { // byte[] salt = new byte[16]; // new SecureRandom().nextBytes(salt); // return salt; // } // }
import com.thoughtworks.go.TestHelpers; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.ProtocolException; import org.apache.http.client.CookieStore; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultRedirectStrategy; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpContext; import java.io.IOException; import static java.lang.String.format; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat;
package com.thoughtworks.go.strongauth.glue; public class StrongAuthGlue { private HttpResponse response;
// Path: e2e/src/test/java/com/thoughtworks/go/TestHelpers.java // public class TestHelpers { // // @SneakyThrows // public void enableAuth() { // executeHelper("enable-auth.py"); // } // // @SneakyThrows // public void disableAuth() { // executeHelper("disable-auth.py"); // } // // @SneakyThrows // public void clearAuthFile() { // executeHelper("clear-password-file.py"); // } // // @SneakyThrows // public void executeHelper(String helperName, String... params) { // List<String> command = Lists.newArrayList(format("/tmp/test-helpers/%s", helperName)); // command.addAll(asList(params)); // executeDockerCommand(command); // } // // @SneakyThrows // private void executeDockerCommand(List<String> commands) { // List<String> commandList = Lists.newArrayList("./bin/execute-docker-command.sh"); // commandList.addAll(commands); // int response = new ProcessBuilder().command(commandList).inheritIO().start().waitFor(); // if (response != 0) { // throw new RuntimeException(format("Failed to execute %s", commandList.toString())); // } // } // // public void createPBKDF2PasswordEntryFor(String username, String password) { // int iterations = 10000; // int keyLength = 256; // byte[] salt = createSalt(); // String saltString = Base64.encodeBase64String(salt); // String hash = createHash(salt, password, iterations, keyLength); // String entry = format("%s:%s:%s:%s(%s, %s)", username, hash, saltString, "PBKDF2WithHmacSHA1", String.valueOf(iterations), String.valueOf(keyLength)); // executeHelper("insert-password-entry.py", entry); // } // // public void createBCryptPasswordEntryFor(String username, String password) { // String saltString = BCrypt.gensalt(); // String hash = BCrypt.hashpw(password, saltString); // String entry = format("%s:%s::%s", username, hash, "bcrypt"); // executeHelper("insert-password-entry.py", entry); // } // // @SneakyThrows // private String createHash(byte[] salt, String password, int iterations, int keyLength) { // PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, keyLength); // byte[] key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).getEncoded(); // return Hex.encodeHexString(key); // } // // private byte[] createSalt() { // byte[] salt = new byte[16]; // new SecureRandom().nextBytes(salt); // return salt; // } // } // Path: e2e/src/test/java/com/thoughtworks/go/strongauth/glue/StrongAuthGlue.java import com.thoughtworks.go.TestHelpers; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.ProtocolException; import org.apache.http.client.CookieStore; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultRedirectStrategy; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpContext; import java.io.IOException; import static java.lang.String.format; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; package com.thoughtworks.go.strongauth.glue; public class StrongAuthGlue { private HttpResponse response;
private TestHelpers testHelpers = new TestHelpers();
danielsomerfield/go-strong-auth-plugin
src/test/java/com/thoughtworks/go/strongauth/authentication/ConfigurableUserPrincipalDetailSourceTest.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java // public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { // private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); // public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); // // private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ConfigurableUserPrincipalDetailSource(InputStreamSource passwordSource) { // try { // loadSource(passwordSource.inputStream()); // } catch (IOException e) { // LOGGER.warn("Missing password file. No credentials loaded."); // } // // passwordSource.addChangeListener(new SourceChangeListener() { // @Override // public void sourceChanged(SourceChangeEvent event) { // try { // loadSource(event.getInputStream()); // } catch (IOException e) { // LOGGER.error("Missing password file. No credentials loaded."); // } // } // }); // } // // private void loadSource(InputStream passwordFile) throws IOException { // principalDetails.clear(); // String line; // final BufferedReader bufferedReader = toBufferedReader(new InputStreamReader(passwordFile)); // while ((line = bufferedReader.readLine()) != null) { // Optional<PrincipalDetail> maybeDetail = parse(line); // if (maybeDetail.isPresent()) { // PrincipalDetail detail = maybeDetail.get(); // principalDetails.put(detail.getUsername(), detail); // } // } // } // // private Optional<PrincipalDetail> parse(final String line) { // final Matcher matcher = DETAIL_PATTERN.matcher(line); // if (matcher.find()) { // return Optional.of(new PrincipalDetail( // matcher.group(1), // matcher.group(2), // matcher.group(3), // matcher.group(4)) // ); // } else { // LOGGER.warn(format("Failed to parse password file line %s", line)); // return Optional.absent(); // } // } // // @Override // public Optional<PrincipalDetail> byUsername(String username) { // return Optional.fromNullable(principalDetails.get(username)); // } // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.authentication.principalDetailSources.ConfigurableUserPrincipalDetailSource; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import org.apache.commons.io.IOUtils; import org.junit.Test; import java.io.InputStream; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.thoughtworks.go.strongauth.authentication; public class ConfigurableUserPrincipalDetailSourceTest { @Test public void testFindExistingUser() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh:salty:PBKDF2WithHmacSHA1(5000, 64)");
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java // public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { // private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); // public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); // // private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ConfigurableUserPrincipalDetailSource(InputStreamSource passwordSource) { // try { // loadSource(passwordSource.inputStream()); // } catch (IOException e) { // LOGGER.warn("Missing password file. No credentials loaded."); // } // // passwordSource.addChangeListener(new SourceChangeListener() { // @Override // public void sourceChanged(SourceChangeEvent event) { // try { // loadSource(event.getInputStream()); // } catch (IOException e) { // LOGGER.error("Missing password file. No credentials loaded."); // } // } // }); // } // // private void loadSource(InputStream passwordFile) throws IOException { // principalDetails.clear(); // String line; // final BufferedReader bufferedReader = toBufferedReader(new InputStreamReader(passwordFile)); // while ((line = bufferedReader.readLine()) != null) { // Optional<PrincipalDetail> maybeDetail = parse(line); // if (maybeDetail.isPresent()) { // PrincipalDetail detail = maybeDetail.get(); // principalDetails.put(detail.getUsername(), detail); // } // } // } // // private Optional<PrincipalDetail> parse(final String line) { // final Matcher matcher = DETAIL_PATTERN.matcher(line); // if (matcher.find()) { // return Optional.of(new PrincipalDetail( // matcher.group(1), // matcher.group(2), // matcher.group(3), // matcher.group(4)) // ); // } else { // LOGGER.warn(format("Failed to parse password file line %s", line)); // return Optional.absent(); // } // } // // @Override // public Optional<PrincipalDetail> byUsername(String username) { // return Optional.fromNullable(principalDetails.get(username)); // } // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/test/java/com/thoughtworks/go/strongauth/authentication/ConfigurableUserPrincipalDetailSourceTest.java import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.authentication.principalDetailSources.ConfigurableUserPrincipalDetailSource; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import org.apache.commons.io.IOUtils; import org.junit.Test; import java.io.InputStream; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.thoughtworks.go.strongauth.authentication; public class ConfigurableUserPrincipalDetailSourceTest { @Test public void testFindExistingUser() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh:salty:PBKDF2WithHmacSHA1(5000, 64)");
PrincipalDetailSource principalDetailSource = new ConfigurableUserPrincipalDetailSource(new BasicInputStreamSource(passwordFile));
danielsomerfield/go-strong-auth-plugin
src/test/java/com/thoughtworks/go/strongauth/authentication/ConfigurableUserPrincipalDetailSourceTest.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java // public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { // private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); // public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); // // private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ConfigurableUserPrincipalDetailSource(InputStreamSource passwordSource) { // try { // loadSource(passwordSource.inputStream()); // } catch (IOException e) { // LOGGER.warn("Missing password file. No credentials loaded."); // } // // passwordSource.addChangeListener(new SourceChangeListener() { // @Override // public void sourceChanged(SourceChangeEvent event) { // try { // loadSource(event.getInputStream()); // } catch (IOException e) { // LOGGER.error("Missing password file. No credentials loaded."); // } // } // }); // } // // private void loadSource(InputStream passwordFile) throws IOException { // principalDetails.clear(); // String line; // final BufferedReader bufferedReader = toBufferedReader(new InputStreamReader(passwordFile)); // while ((line = bufferedReader.readLine()) != null) { // Optional<PrincipalDetail> maybeDetail = parse(line); // if (maybeDetail.isPresent()) { // PrincipalDetail detail = maybeDetail.get(); // principalDetails.put(detail.getUsername(), detail); // } // } // } // // private Optional<PrincipalDetail> parse(final String line) { // final Matcher matcher = DETAIL_PATTERN.matcher(line); // if (matcher.find()) { // return Optional.of(new PrincipalDetail( // matcher.group(1), // matcher.group(2), // matcher.group(3), // matcher.group(4)) // ); // } else { // LOGGER.warn(format("Failed to parse password file line %s", line)); // return Optional.absent(); // } // } // // @Override // public Optional<PrincipalDetail> byUsername(String username) { // return Optional.fromNullable(principalDetails.get(username)); // } // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.authentication.principalDetailSources.ConfigurableUserPrincipalDetailSource; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import org.apache.commons.io.IOUtils; import org.junit.Test; import java.io.InputStream; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.thoughtworks.go.strongauth.authentication; public class ConfigurableUserPrincipalDetailSourceTest { @Test public void testFindExistingUser() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh:salty:PBKDF2WithHmacSHA1(5000, 64)"); PrincipalDetailSource principalDetailSource = new ConfigurableUserPrincipalDetailSource(new BasicInputStreamSource(passwordFile)); Optional<PrincipalDetail> maybePrincipalDetail = principalDetailSource.byUsername("username1"); assertThat(maybePrincipalDetail, is(Optional.of( new PrincipalDetail("username1", "hazsh", "salty", "PBKDF2WithHmacSHA1(5000, 64)")))); } @Test public void testFindExistingUserWithNotSalt() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh::PBKDF2WithHmacSHA1(5000, 64)"); PrincipalDetailSource principalDetailSource = new ConfigurableUserPrincipalDetailSource(new BasicInputStreamSource(passwordFile)); Optional<PrincipalDetail> maybePrincipalDetail = principalDetailSource.byUsername("username1"); assertThat(maybePrincipalDetail, is(Optional.of( new PrincipalDetail("username1", "hazsh", "", "PBKDF2WithHmacSHA1(5000, 64)")))); } @Test public void testFindMissingUser() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh:salty:PBKDF2WithHmacSHA1(5000, 64)"); PrincipalDetailSource principalDetailSource = new ConfigurableUserPrincipalDetailSource(new BasicInputStreamSource(passwordFile)); Optional<PrincipalDetail> maybePrincipalDetail = principalDetailSource.byUsername("missingUser"); assertThat(maybePrincipalDetail, is(Optional.<PrincipalDetail>absent())); }
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java // public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { // private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); // public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); // // private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ConfigurableUserPrincipalDetailSource(InputStreamSource passwordSource) { // try { // loadSource(passwordSource.inputStream()); // } catch (IOException e) { // LOGGER.warn("Missing password file. No credentials loaded."); // } // // passwordSource.addChangeListener(new SourceChangeListener() { // @Override // public void sourceChanged(SourceChangeEvent event) { // try { // loadSource(event.getInputStream()); // } catch (IOException e) { // LOGGER.error("Missing password file. No credentials loaded."); // } // } // }); // } // // private void loadSource(InputStream passwordFile) throws IOException { // principalDetails.clear(); // String line; // final BufferedReader bufferedReader = toBufferedReader(new InputStreamReader(passwordFile)); // while ((line = bufferedReader.readLine()) != null) { // Optional<PrincipalDetail> maybeDetail = parse(line); // if (maybeDetail.isPresent()) { // PrincipalDetail detail = maybeDetail.get(); // principalDetails.put(detail.getUsername(), detail); // } // } // } // // private Optional<PrincipalDetail> parse(final String line) { // final Matcher matcher = DETAIL_PATTERN.matcher(line); // if (matcher.find()) { // return Optional.of(new PrincipalDetail( // matcher.group(1), // matcher.group(2), // matcher.group(3), // matcher.group(4)) // ); // } else { // LOGGER.warn(format("Failed to parse password file line %s", line)); // return Optional.absent(); // } // } // // @Override // public Optional<PrincipalDetail> byUsername(String username) { // return Optional.fromNullable(principalDetails.get(username)); // } // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/test/java/com/thoughtworks/go/strongauth/authentication/ConfigurableUserPrincipalDetailSourceTest.java import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.authentication.principalDetailSources.ConfigurableUserPrincipalDetailSource; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import org.apache.commons.io.IOUtils; import org.junit.Test; import java.io.InputStream; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package com.thoughtworks.go.strongauth.authentication; public class ConfigurableUserPrincipalDetailSourceTest { @Test public void testFindExistingUser() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh:salty:PBKDF2WithHmacSHA1(5000, 64)"); PrincipalDetailSource principalDetailSource = new ConfigurableUserPrincipalDetailSource(new BasicInputStreamSource(passwordFile)); Optional<PrincipalDetail> maybePrincipalDetail = principalDetailSource.byUsername("username1"); assertThat(maybePrincipalDetail, is(Optional.of( new PrincipalDetail("username1", "hazsh", "salty", "PBKDF2WithHmacSHA1(5000, 64)")))); } @Test public void testFindExistingUserWithNotSalt() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh::PBKDF2WithHmacSHA1(5000, 64)"); PrincipalDetailSource principalDetailSource = new ConfigurableUserPrincipalDetailSource(new BasicInputStreamSource(passwordFile)); Optional<PrincipalDetail> maybePrincipalDetail = principalDetailSource.byUsername("username1"); assertThat(maybePrincipalDetail, is(Optional.of( new PrincipalDetail("username1", "hazsh", "", "PBKDF2WithHmacSHA1(5000, 64)")))); } @Test public void testFindMissingUser() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh:salty:PBKDF2WithHmacSHA1(5000, 64)"); PrincipalDetailSource principalDetailSource = new ConfigurableUserPrincipalDetailSource(new BasicInputStreamSource(passwordFile)); Optional<PrincipalDetail> maybePrincipalDetail = principalDetailSource.byUsername("missingUser"); assertThat(maybePrincipalDetail, is(Optional.<PrincipalDetail>absent())); }
public static class BasicInputStreamSource implements InputStreamSource {
danielsomerfield/go-strong-auth-plugin
src/test/java/com/thoughtworks/go/strongauth/authentication/ConfigurableUserPrincipalDetailSourceTest.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java // public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { // private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); // public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); // // private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ConfigurableUserPrincipalDetailSource(InputStreamSource passwordSource) { // try { // loadSource(passwordSource.inputStream()); // } catch (IOException e) { // LOGGER.warn("Missing password file. No credentials loaded."); // } // // passwordSource.addChangeListener(new SourceChangeListener() { // @Override // public void sourceChanged(SourceChangeEvent event) { // try { // loadSource(event.getInputStream()); // } catch (IOException e) { // LOGGER.error("Missing password file. No credentials loaded."); // } // } // }); // } // // private void loadSource(InputStream passwordFile) throws IOException { // principalDetails.clear(); // String line; // final BufferedReader bufferedReader = toBufferedReader(new InputStreamReader(passwordFile)); // while ((line = bufferedReader.readLine()) != null) { // Optional<PrincipalDetail> maybeDetail = parse(line); // if (maybeDetail.isPresent()) { // PrincipalDetail detail = maybeDetail.get(); // principalDetails.put(detail.getUsername(), detail); // } // } // } // // private Optional<PrincipalDetail> parse(final String line) { // final Matcher matcher = DETAIL_PATTERN.matcher(line); // if (matcher.find()) { // return Optional.of(new PrincipalDetail( // matcher.group(1), // matcher.group(2), // matcher.group(3), // matcher.group(4)) // ); // } else { // LOGGER.warn(format("Failed to parse password file line %s", line)); // return Optional.absent(); // } // } // // @Override // public Optional<PrincipalDetail> byUsername(String username) { // return Optional.fromNullable(principalDetails.get(username)); // } // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // }
import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.authentication.principalDetailSources.ConfigurableUserPrincipalDetailSource; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import org.apache.commons.io.IOUtils; import org.junit.Test; import java.io.InputStream; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
assertThat(maybePrincipalDetail, is(Optional.of( new PrincipalDetail("username1", "hazsh", "salty", "PBKDF2WithHmacSHA1(5000, 64)")))); } @Test public void testFindExistingUserWithNotSalt() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh::PBKDF2WithHmacSHA1(5000, 64)"); PrincipalDetailSource principalDetailSource = new ConfigurableUserPrincipalDetailSource(new BasicInputStreamSource(passwordFile)); Optional<PrincipalDetail> maybePrincipalDetail = principalDetailSource.byUsername("username1"); assertThat(maybePrincipalDetail, is(Optional.of( new PrincipalDetail("username1", "hazsh", "", "PBKDF2WithHmacSHA1(5000, 64)")))); } @Test public void testFindMissingUser() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh:salty:PBKDF2WithHmacSHA1(5000, 64)"); PrincipalDetailSource principalDetailSource = new ConfigurableUserPrincipalDetailSource(new BasicInputStreamSource(passwordFile)); Optional<PrincipalDetail> maybePrincipalDetail = principalDetailSource.byUsername("missingUser"); assertThat(maybePrincipalDetail, is(Optional.<PrincipalDetail>absent())); } public static class BasicInputStreamSource implements InputStreamSource { private InputStream inputStream; public BasicInputStreamSource(InputStream inputStream) { this.inputStream = inputStream; } @Override
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/principalDetailSources/ConfigurableUserPrincipalDetailSource.java // public class ConfigurableUserPrincipalDetailSource implements PrincipalDetailSource { // private final Map<String, PrincipalDetail> principalDetails = new HashMap<>(); // public static final Pattern DETAIL_PATTERN = Pattern.compile("^([^:]+):([^:]+):([^:]*):([^:]+)$"); // // private static final Logger LOGGER = Logger.getLoggerFor(ConfigurableUserPrincipalDetailSource.class); // public final String pluginId = Constants.PLUGIN_ID; // // public ConfigurableUserPrincipalDetailSource(InputStreamSource passwordSource) { // try { // loadSource(passwordSource.inputStream()); // } catch (IOException e) { // LOGGER.warn("Missing password file. No credentials loaded."); // } // // passwordSource.addChangeListener(new SourceChangeListener() { // @Override // public void sourceChanged(SourceChangeEvent event) { // try { // loadSource(event.getInputStream()); // } catch (IOException e) { // LOGGER.error("Missing password file. No credentials loaded."); // } // } // }); // } // // private void loadSource(InputStream passwordFile) throws IOException { // principalDetails.clear(); // String line; // final BufferedReader bufferedReader = toBufferedReader(new InputStreamReader(passwordFile)); // while ((line = bufferedReader.readLine()) != null) { // Optional<PrincipalDetail> maybeDetail = parse(line); // if (maybeDetail.isPresent()) { // PrincipalDetail detail = maybeDetail.get(); // principalDetails.put(detail.getUsername(), detail); // } // } // } // // private Optional<PrincipalDetail> parse(final String line) { // final Matcher matcher = DETAIL_PATTERN.matcher(line); // if (matcher.find()) { // return Optional.of(new PrincipalDetail( // matcher.group(1), // matcher.group(2), // matcher.group(3), // matcher.group(4)) // ); // } else { // LOGGER.warn(format("Failed to parse password file line %s", line)); // return Optional.absent(); // } // } // // @Override // public Optional<PrincipalDetail> byUsername(String username) { // return Optional.fromNullable(principalDetails.get(username)); // } // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/InputStreamSource.java // public interface InputStreamSource { // // void addChangeListener(SourceChangeListener sourceChangeListener); // // InputStream inputStream() throws IOException; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/io/SourceChangeListener.java // public interface SourceChangeListener { // void sourceChanged(final SourceChangeEvent event); // } // Path: src/test/java/com/thoughtworks/go/strongauth/authentication/ConfigurableUserPrincipalDetailSourceTest.java import com.google.common.base.Optional; import com.thoughtworks.go.strongauth.authentication.principalDetailSources.ConfigurableUserPrincipalDetailSource; import com.thoughtworks.go.strongauth.util.InputStreamSource; import com.thoughtworks.go.strongauth.util.io.SourceChangeListener; import org.apache.commons.io.IOUtils; import org.junit.Test; import java.io.InputStream; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; assertThat(maybePrincipalDetail, is(Optional.of( new PrincipalDetail("username1", "hazsh", "salty", "PBKDF2WithHmacSHA1(5000, 64)")))); } @Test public void testFindExistingUserWithNotSalt() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh::PBKDF2WithHmacSHA1(5000, 64)"); PrincipalDetailSource principalDetailSource = new ConfigurableUserPrincipalDetailSource(new BasicInputStreamSource(passwordFile)); Optional<PrincipalDetail> maybePrincipalDetail = principalDetailSource.byUsername("username1"); assertThat(maybePrincipalDetail, is(Optional.of( new PrincipalDetail("username1", "hazsh", "", "PBKDF2WithHmacSHA1(5000, 64)")))); } @Test public void testFindMissingUser() { InputStream passwordFile = IOUtils.toInputStream("username1:hazsh:salty:PBKDF2WithHmacSHA1(5000, 64)"); PrincipalDetailSource principalDetailSource = new ConfigurableUserPrincipalDetailSource(new BasicInputStreamSource(passwordFile)); Optional<PrincipalDetail> maybePrincipalDetail = principalDetailSource.byUsername("missingUser"); assertThat(maybePrincipalDetail, is(Optional.<PrincipalDetail>absent())); } public static class BasicInputStreamSource implements InputStreamSource { private InputStream inputStream; public BasicInputStreamSource(InputStream inputStream) { this.inputStream = inputStream; } @Override
public void addChangeListener(SourceChangeListener sourceChangeListener) {
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoder.java
// Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public class Json { // private static Gson gson = new Gson(); // // public static Map<String, String> toMapOfStrings(String jsonValue) { // Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType(); // return gson.fromJson(jsonValue, mapOfStringToStringType); // } // // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // public static String toJson(Object anything) { // return gson.toJson(anything); // } // }
import com.thoughtworks.go.plugin.api.response.GoApiResponse; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.Json; import java.util.Map;
package com.thoughtworks.go.strongauth.wire; public class PluginConfigurationDecoder { public PluginConfiguration decode(GoApiResponse response) { if (response.responseCode() == 200) { return parseConfiguration(response.responseBody()); } else { return defaultConfiguration(); } } private PluginConfiguration parseConfiguration(String body) { if (body == null) { return defaultConfiguration(); } else {
// Path: src/main/java/com/thoughtworks/go/strongauth/config/PluginConfiguration.java // @Value // public class PluginConfiguration { // // public static final String DEFAULT_SOURCE_FILE_PATH = "/etc/go/passwd"; // private final File principalSourceFile; // // public PluginConfiguration() { // this(DEFAULT_SOURCE_FILE_PATH); // } // // public PluginConfiguration(final String principalSourceFilePath) { // this.principalSourceFile = principalSourceFilePath != null ? // new File(principalSourceFilePath) : // new File(DEFAULT_SOURCE_FILE_PATH); // } // // @Override // public String toString() { // return "PluginConfiguration{" + // "principalSourceFilePath='" + principalSourceFile + '\'' + // '}'; // } // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Json.java // public class Json { // private static Gson gson = new Gson(); // // public static Map<String, String> toMapOfStrings(String jsonValue) { // Type mapOfStringToStringType = new TypeToken<LinkedTreeMap<String, String>>() {}.getType(); // return gson.fromJson(jsonValue, mapOfStringToStringType); // } // // public static Map toMap(String jsonValue) { // return gson.fromJson(jsonValue, Map.class); // } // // public static String toJson(Object anything) { // return gson.toJson(anything); // } // } // Path: src/main/java/com/thoughtworks/go/strongauth/wire/PluginConfigurationDecoder.java import com.thoughtworks.go.plugin.api.response.GoApiResponse; import com.thoughtworks.go.strongauth.config.PluginConfiguration; import com.thoughtworks.go.strongauth.util.Json; import java.util.Map; package com.thoughtworks.go.strongauth.wire; public class PluginConfigurationDecoder { public PluginConfiguration decode(GoApiResponse response) { if (response.responseCode() == 200) { return parseConfiguration(response.responseBody()); } else { return defaultConfiguration(); } } private PluginConfiguration parseConfiguration(String body) { if (body == null) { return defaultConfiguration(); } else {
return fromMap(Json.toMapOfStrings(body));
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/wire/GoAuthenticationRequestDecoder.java
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/AuthenticationRequest.java // @Value // public class AuthenticationRequest { // private final String username; // private final String password; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // }
import com.google.common.base.Optional; import com.google.gson.*; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.strongauth.authentication.AuthenticationRequest; import com.thoughtworks.go.strongauth.util.Constants; import java.io.IOException; import java.lang.reflect.Type; import static java.lang.String.format;
package com.thoughtworks.go.strongauth.wire; public class GoAuthenticationRequestDecoder { public final String pluginId = Constants.PLUGIN_ID; private static final Logger LOGGER = Logger.getLoggerFor(GoAuthenticationRequestDecoder.class); private static Gson gson = new GsonBuilder().registerTypeAdapter(
// Path: src/main/java/com/thoughtworks/go/strongauth/authentication/AuthenticationRequest.java // @Value // public class AuthenticationRequest { // private final String username; // private final String password; // } // // Path: src/main/java/com/thoughtworks/go/strongauth/util/Constants.java // public class Constants { // public static final String PLUGIN_ID = "strongauth"; // } // Path: src/main/java/com/thoughtworks/go/strongauth/wire/GoAuthenticationRequestDecoder.java import com.google.common.base.Optional; import com.google.gson.*; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.strongauth.authentication.AuthenticationRequest; import com.thoughtworks.go.strongauth.util.Constants; import java.io.IOException; import java.lang.reflect.Type; import static java.lang.String.format; package com.thoughtworks.go.strongauth.wire; public class GoAuthenticationRequestDecoder { public final String pluginId = Constants.PLUGIN_ID; private static final Logger LOGGER = Logger.getLoggerFor(GoAuthenticationRequestDecoder.class); private static Gson gson = new GsonBuilder().registerTypeAdapter(
AuthenticationRequest.class, new JsonDeserializer<AuthenticationRequest>() {
danielsomerfield/go-strong-auth-plugin
src/main/java/com/thoughtworks/go/strongauth/ComponentFactory.java
// Path: src/main/java/com/thoughtworks/go/strongauth/config/Config.java // @Configuration // public class Config { // // private static final String CALL_FROM_SERVER_GET_CONFIGURATION = "go.plugin-settings.get-configuration"; // private static final String CALL_FROM_SERVER_AUTHENTICATE_USER = "go.authentication.authenticate-user"; // private static final String CALL_FROM_SERVER_PLUGIN_CONFIGURATION = "go.authentication.plugin-configuration"; // private static final String CALL_FROM_SERVER_GET_VIEW = "go.plugin-settings.get-view"; // private static final String CALL_FROM_SERVER_VALIDATE_CONFIGURATION = "go.plugin-settings.validate-configuration"; // // @Bean // Handlers handlers(final AuthenticationHandler authenticationHandler) { // return new Handlers( // ImmutableMap.of( // CALL_FROM_SERVER_GET_CONFIGURATION, PluginSettingsHandler.getConfiguration(), // CALL_FROM_SERVER_GET_VIEW, PluginSettingsHandler.getView(), // CALL_FROM_SERVER_VALIDATE_CONFIGURATION, PluginSettingsHandler.validateConfiguration(), // CALL_FROM_SERVER_PLUGIN_CONFIGURATION, new PluginConfigurationHandler(), // CALL_FROM_SERVER_AUTHENTICATE_USER, authenticationHandler // // CALL_FROM_SERVER_SEARCH_USER, new SearchUserHandler(), // // CALL_FROM_SERVER_INDEX, new PluginIndexRequestHandler(accessorWrapper, goPluginIdentifier) // ) // ); // } // // @Bean // AuthenticationHandler authenticationHandler(final Authenticator authenticator) { // return new AuthenticationHandler( // new GoAuthenticationRequestDecoder(), // authenticator, // new GoUserEncoder() // ); // } // // @Bean // Authenticator authenticator( // final PrincipalDetailSource principalDetailSource) { // return new Authenticator(principalDetailSource, hashProviders()); // } // // @Bean // List<? extends HashProvider> hashProviders() { // return ImmutableList.of( // new PBESpecHashProvider(), // new BCryptProvider() // ); // } // // @Bean // ComponentFactory componentFactory(final Handlers handlers) { // return new ComponentFactory(handlers); // } // // @Bean // PrincipalDetailSource principalSource(final InputStreamSource inputStreamSource) { // return new ConfigurableUserPrincipalDetailSource(inputStreamSource); // } // // @Bean // ConfigurationMonitor configurationMonitor(final GoAPI goAPI) { // return new ConfigurationMonitor(goAPI); // } // // @Bean // InputStreamSource inputStreamSource(final ConfigurationMonitor configurationMonitor) { // return new ConfigFileMonitor(configurationMonitor); // } // // @Bean // GoAPI goAPI(@SuppressWarnings("SpringJavaAutowiringInspection") final GoPluginIdentifier goPluginIdentifier, // @SuppressWarnings("SpringJavaAutowiringInspection") final GoApplicationAccessor goApplicationAccessor, // final PluginConfigurationDecoder pluginConfigurationDecoder // // ) { // return new GoAPI(goPluginIdentifier, goApplicationAccessor, pluginConfigurationDecoder); // } // // @Bean // PluginConfigurationDecoder pluginConfigurationDecoder() { // return new PluginConfigurationDecoder(); // } // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/handlers/Handlers.java // public class Handlers { // // private final Map<String, Handler> handlers; // // public Handlers(final Map<String, Handler> handlers) { // this.handlers = handlers; // } // // public Handler get(String requestName) { // if (handlers.containsKey(requestName)) { // return handlers.get(requestName); // } // throw new RuntimeException(format("Handler for request of type: %s is not implemented", requestName)); // } // }
import com.thoughtworks.go.plugin.api.GoApplicationAccessor; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.strongauth.config.Config; import com.thoughtworks.go.strongauth.handlers.Handlers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
package com.thoughtworks.go.strongauth; public class ComponentFactory { private final Handlers handlers; @Autowired public ComponentFactory(Handlers handlers) { this.handlers = handlers; } public static ComponentFactory create(GoApplicationAccessor goApplicationAccessor, GoPluginIdentifier goPluginIdentifier) { try { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.setClassLoader(ComponentFactory.class.getClassLoader());
// Path: src/main/java/com/thoughtworks/go/strongauth/config/Config.java // @Configuration // public class Config { // // private static final String CALL_FROM_SERVER_GET_CONFIGURATION = "go.plugin-settings.get-configuration"; // private static final String CALL_FROM_SERVER_AUTHENTICATE_USER = "go.authentication.authenticate-user"; // private static final String CALL_FROM_SERVER_PLUGIN_CONFIGURATION = "go.authentication.plugin-configuration"; // private static final String CALL_FROM_SERVER_GET_VIEW = "go.plugin-settings.get-view"; // private static final String CALL_FROM_SERVER_VALIDATE_CONFIGURATION = "go.plugin-settings.validate-configuration"; // // @Bean // Handlers handlers(final AuthenticationHandler authenticationHandler) { // return new Handlers( // ImmutableMap.of( // CALL_FROM_SERVER_GET_CONFIGURATION, PluginSettingsHandler.getConfiguration(), // CALL_FROM_SERVER_GET_VIEW, PluginSettingsHandler.getView(), // CALL_FROM_SERVER_VALIDATE_CONFIGURATION, PluginSettingsHandler.validateConfiguration(), // CALL_FROM_SERVER_PLUGIN_CONFIGURATION, new PluginConfigurationHandler(), // CALL_FROM_SERVER_AUTHENTICATE_USER, authenticationHandler // // CALL_FROM_SERVER_SEARCH_USER, new SearchUserHandler(), // // CALL_FROM_SERVER_INDEX, new PluginIndexRequestHandler(accessorWrapper, goPluginIdentifier) // ) // ); // } // // @Bean // AuthenticationHandler authenticationHandler(final Authenticator authenticator) { // return new AuthenticationHandler( // new GoAuthenticationRequestDecoder(), // authenticator, // new GoUserEncoder() // ); // } // // @Bean // Authenticator authenticator( // final PrincipalDetailSource principalDetailSource) { // return new Authenticator(principalDetailSource, hashProviders()); // } // // @Bean // List<? extends HashProvider> hashProviders() { // return ImmutableList.of( // new PBESpecHashProvider(), // new BCryptProvider() // ); // } // // @Bean // ComponentFactory componentFactory(final Handlers handlers) { // return new ComponentFactory(handlers); // } // // @Bean // PrincipalDetailSource principalSource(final InputStreamSource inputStreamSource) { // return new ConfigurableUserPrincipalDetailSource(inputStreamSource); // } // // @Bean // ConfigurationMonitor configurationMonitor(final GoAPI goAPI) { // return new ConfigurationMonitor(goAPI); // } // // @Bean // InputStreamSource inputStreamSource(final ConfigurationMonitor configurationMonitor) { // return new ConfigFileMonitor(configurationMonitor); // } // // @Bean // GoAPI goAPI(@SuppressWarnings("SpringJavaAutowiringInspection") final GoPluginIdentifier goPluginIdentifier, // @SuppressWarnings("SpringJavaAutowiringInspection") final GoApplicationAccessor goApplicationAccessor, // final PluginConfigurationDecoder pluginConfigurationDecoder // // ) { // return new GoAPI(goPluginIdentifier, goApplicationAccessor, pluginConfigurationDecoder); // } // // @Bean // PluginConfigurationDecoder pluginConfigurationDecoder() { // return new PluginConfigurationDecoder(); // } // // } // // Path: src/main/java/com/thoughtworks/go/strongauth/handlers/Handlers.java // public class Handlers { // // private final Map<String, Handler> handlers; // // public Handlers(final Map<String, Handler> handlers) { // this.handlers = handlers; // } // // public Handler get(String requestName) { // if (handlers.containsKey(requestName)) { // return handlers.get(requestName); // } // throw new RuntimeException(format("Handler for request of type: %s is not implemented", requestName)); // } // } // Path: src/main/java/com/thoughtworks/go/strongauth/ComponentFactory.java import com.thoughtworks.go.plugin.api.GoApplicationAccessor; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.strongauth.config.Config; import com.thoughtworks.go.strongauth.handlers.Handlers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext; package com.thoughtworks.go.strongauth; public class ComponentFactory { private final Handlers handlers; @Autowired public ComponentFactory(Handlers handlers) { this.handlers = handlers; } public static ComponentFactory create(GoApplicationAccessor goApplicationAccessor, GoPluginIdentifier goPluginIdentifier) { try { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.setClassLoader(ComponentFactory.class.getClassLoader());
ctx.register(Config.class);