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
jnoessner/rockIt
src/main/java/com/googlecode/rockit/javaAPI/predicates/Predicate.java
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/types/Type.java // public class Type implements Comparable<Type> // { // private String name; // // private Predicate groundValuesPredicate = null; // // // // private int groundValueSize = 0; // // public Type() // { // } // // // public Type(String name) // { // this.setName(name); // } // // // public Type(String name, Predicate groundValuesPredicate) throws ParseException // { // this.setName(name); // this.setGroundValuesPredicate(groundValuesPredicate); // } // // // /** // * Sets the ground values of the current type to those of the given predicate. // * // * If the predicate has more than one "row" in ground values (e.g. more than one Type assignment), // * an exception is thrown. // * // * @param predicate // * @throws ParseException // */ // public void setGroundValuesPredicate(Predicate predicate) throws ParseException // { // if(predicate == null) { throw new ParseException("Predicates must not equal null when added to type. You tried to add a null predicate to type " + this.getName()); } // if(predicate.getTypes().size() > 1) { throw new ParseException("Predicates which are used to set ground values must not have more than one type. This happens when trying to assign predicate " + predicate.getName() + " to type " + this.getName()); } // this.groundValuesPredicate = predicate; // } // // // public ArrayList<String[]> getGroundValues() // { // return groundValuesPredicate.getGroundValues(); // } // // // public Predicate getGroundValuesPredicate() // { // return groundValuesPredicate; // } // // // @Override // public boolean equals(Object obj) // { // if(obj.getClass() == Type.class) { // Type t = (Type) obj; // return t.getName().equals(this.getName()); // } else { // return false; // } // } // // // public String getId() // { // // return this.getClass().getName(); // } // // // public String toLongString() // { // StringBuilder sb = new StringBuilder(); // sb.append("> type ").append(this.getName()).append("\n"); // if(this.groundValuesPredicate != null) { // for(String[] s : this.groundValuesPredicate.getGroundValues()) { // sb.append("\"" + s[0] + "\"\n"); // } // } // return sb.toString(); // } // // // public String output() // { // String result = "Type " + this.getName() + "T = new Type(\"" + this.getName() + "\");\n"; // if(this.groundValuesPredicate != null) { // result = result + this.getName() + ".values = " + this.getGroundValuesPredicate().getName(); // } // return result; // // } // // // public void setName(String name) // { // this.name = name; // } // // // public String getName() // { // return name; // } // // // public String toString() // { // return name; // } // // // public String toMediumString() // { // return "type " + name + ";"; // } // // // @Override // public int compareTo(Type arg0) // { // return this.name.compareTo(arg0.getName()); // } // // /* // * public int getGroundValueSize() throws ParseException { // * if(this.groundValuesPredicate==null){ // * throw new ParseException("Can not determine the size if no ground values predicate is set. Type name: " + this.name); // * } // * if(groundValueSize==0){ // * for(String[] p:groundValuesPredicate.getGroundValues()){ // * groundValueSize = Math.max(groundValueSize, p[0].length()); // * } // * } // * return groundValueSize; // * } // */ // }
import java.util.ArrayList; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.javaAPI.types.Type;
package com.googlecode.rockit.javaAPI.predicates; public class Predicate extends PredicateAbstract { public Predicate() { }
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/types/Type.java // public class Type implements Comparable<Type> // { // private String name; // // private Predicate groundValuesPredicate = null; // // // // private int groundValueSize = 0; // // public Type() // { // } // // // public Type(String name) // { // this.setName(name); // } // // // public Type(String name, Predicate groundValuesPredicate) throws ParseException // { // this.setName(name); // this.setGroundValuesPredicate(groundValuesPredicate); // } // // // /** // * Sets the ground values of the current type to those of the given predicate. // * // * If the predicate has more than one "row" in ground values (e.g. more than one Type assignment), // * an exception is thrown. // * // * @param predicate // * @throws ParseException // */ // public void setGroundValuesPredicate(Predicate predicate) throws ParseException // { // if(predicate == null) { throw new ParseException("Predicates must not equal null when added to type. You tried to add a null predicate to type " + this.getName()); } // if(predicate.getTypes().size() > 1) { throw new ParseException("Predicates which are used to set ground values must not have more than one type. This happens when trying to assign predicate " + predicate.getName() + " to type " + this.getName()); } // this.groundValuesPredicate = predicate; // } // // // public ArrayList<String[]> getGroundValues() // { // return groundValuesPredicate.getGroundValues(); // } // // // public Predicate getGroundValuesPredicate() // { // return groundValuesPredicate; // } // // // @Override // public boolean equals(Object obj) // { // if(obj.getClass() == Type.class) { // Type t = (Type) obj; // return t.getName().equals(this.getName()); // } else { // return false; // } // } // // // public String getId() // { // // return this.getClass().getName(); // } // // // public String toLongString() // { // StringBuilder sb = new StringBuilder(); // sb.append("> type ").append(this.getName()).append("\n"); // if(this.groundValuesPredicate != null) { // for(String[] s : this.groundValuesPredicate.getGroundValues()) { // sb.append("\"" + s[0] + "\"\n"); // } // } // return sb.toString(); // } // // // public String output() // { // String result = "Type " + this.getName() + "T = new Type(\"" + this.getName() + "\");\n"; // if(this.groundValuesPredicate != null) { // result = result + this.getName() + ".values = " + this.getGroundValuesPredicate().getName(); // } // return result; // // } // // // public void setName(String name) // { // this.name = name; // } // // // public String getName() // { // return name; // } // // // public String toString() // { // return name; // } // // // public String toMediumString() // { // return "type " + name + ";"; // } // // // @Override // public int compareTo(Type arg0) // { // return this.name.compareTo(arg0.getName()); // } // // /* // * public int getGroundValueSize() throws ParseException { // * if(this.groundValuesPredicate==null){ // * throw new ParseException("Can not determine the size if no ground values predicate is set. Type name: " + this.name); // * } // * if(groundValueSize==0){ // * for(String[] p:groundValuesPredicate.getGroundValues()){ // * groundValueSize = Math.max(groundValueSize, p[0].length()); // * } // * } // * return groundValueSize; // * } // */ // } // Path: src/main/java/com/googlecode/rockit/javaAPI/predicates/Predicate.java import java.util.ArrayList; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.javaAPI.types.Type; package com.googlecode.rockit.javaAPI.predicates; public class Predicate extends PredicateAbstract { public Predicate() { }
public Predicate(String name, boolean hidden, Type... types) throws ParseException
jnoessner/rockIt
src/main/java/com/googlecode/rockit/javaAPI/formulas/FormulaAbstract.java
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableType.java // public class VariableType extends VariableAbstract // { // private Type type; // // // public VariableType() // { // } // // // public VariableType(String name, Type type) // { // this.setName(name); // this.type = type; // } // // // public VariableType(String name) // { // this.setName(name); // } // // // public void setType(Type type) // { // this.type = type; // // } // // // public Type getType() // { // return type; // } // // // public String toString() // { // return getName(); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/types/Type.java // public class Type implements Comparable<Type> // { // private String name; // // private Predicate groundValuesPredicate = null; // // // // private int groundValueSize = 0; // // public Type() // { // } // // // public Type(String name) // { // this.setName(name); // } // // // public Type(String name, Predicate groundValuesPredicate) throws ParseException // { // this.setName(name); // this.setGroundValuesPredicate(groundValuesPredicate); // } // // // /** // * Sets the ground values of the current type to those of the given predicate. // * // * If the predicate has more than one "row" in ground values (e.g. more than one Type assignment), // * an exception is thrown. // * // * @param predicate // * @throws ParseException // */ // public void setGroundValuesPredicate(Predicate predicate) throws ParseException // { // if(predicate == null) { throw new ParseException("Predicates must not equal null when added to type. You tried to add a null predicate to type " + this.getName()); } // if(predicate.getTypes().size() > 1) { throw new ParseException("Predicates which are used to set ground values must not have more than one type. This happens when trying to assign predicate " + predicate.getName() + " to type " + this.getName()); } // this.groundValuesPredicate = predicate; // } // // // public ArrayList<String[]> getGroundValues() // { // return groundValuesPredicate.getGroundValues(); // } // // // public Predicate getGroundValuesPredicate() // { // return groundValuesPredicate; // } // // // @Override // public boolean equals(Object obj) // { // if(obj.getClass() == Type.class) { // Type t = (Type) obj; // return t.getName().equals(this.getName()); // } else { // return false; // } // } // // // public String getId() // { // // return this.getClass().getName(); // } // // // public String toLongString() // { // StringBuilder sb = new StringBuilder(); // sb.append("> type ").append(this.getName()).append("\n"); // if(this.groundValuesPredicate != null) { // for(String[] s : this.groundValuesPredicate.getGroundValues()) { // sb.append("\"" + s[0] + "\"\n"); // } // } // return sb.toString(); // } // // // public String output() // { // String result = "Type " + this.getName() + "T = new Type(\"" + this.getName() + "\");\n"; // if(this.groundValuesPredicate != null) { // result = result + this.getName() + ".values = " + this.getGroundValuesPredicate().getName(); // } // return result; // // } // // // public void setName(String name) // { // this.name = name; // } // // // public String getName() // { // return name; // } // // // public String toString() // { // return name; // } // // // public String toMediumString() // { // return "type " + name + ";"; // } // // // @Override // public int compareTo(Type arg0) // { // return this.name.compareTo(arg0.getName()); // } // // /* // * public int getGroundValueSize() throws ParseException { // * if(this.groundValuesPredicate==null){ // * throw new ParseException("Can not determine the size if no ground values predicate is set. Type name: " + this.name); // * } // * if(groundValueSize==0){ // * for(String[] p:groundValuesPredicate.getGroundValues()){ // * groundValueSize = Math.max(groundValueSize, p[0].length()); // * } // * } // * return groundValueSize; // * } // */ // }
import java.util.ArrayList; import java.util.HashSet; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.javaAPI.formulas.expressions.IfExpression; import com.googlecode.rockit.javaAPI.formulas.expressions.impl.PredicateExpression; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableType; import com.googlecode.rockit.javaAPI.predicates.PredicateAbstract; import com.googlecode.rockit.javaAPI.types.Type;
package com.googlecode.rockit.javaAPI.formulas; /** * The basic class of all formular. * * Defines the For- and the If-part of every formular. * * @author jan * */ public abstract class FormulaAbstract implements Comparable<FormulaAbstract> {
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableType.java // public class VariableType extends VariableAbstract // { // private Type type; // // // public VariableType() // { // } // // // public VariableType(String name, Type type) // { // this.setName(name); // this.type = type; // } // // // public VariableType(String name) // { // this.setName(name); // } // // // public void setType(Type type) // { // this.type = type; // // } // // // public Type getType() // { // return type; // } // // // public String toString() // { // return getName(); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/types/Type.java // public class Type implements Comparable<Type> // { // private String name; // // private Predicate groundValuesPredicate = null; // // // // private int groundValueSize = 0; // // public Type() // { // } // // // public Type(String name) // { // this.setName(name); // } // // // public Type(String name, Predicate groundValuesPredicate) throws ParseException // { // this.setName(name); // this.setGroundValuesPredicate(groundValuesPredicate); // } // // // /** // * Sets the ground values of the current type to those of the given predicate. // * // * If the predicate has more than one "row" in ground values (e.g. more than one Type assignment), // * an exception is thrown. // * // * @param predicate // * @throws ParseException // */ // public void setGroundValuesPredicate(Predicate predicate) throws ParseException // { // if(predicate == null) { throw new ParseException("Predicates must not equal null when added to type. You tried to add a null predicate to type " + this.getName()); } // if(predicate.getTypes().size() > 1) { throw new ParseException("Predicates which are used to set ground values must not have more than one type. This happens when trying to assign predicate " + predicate.getName() + " to type " + this.getName()); } // this.groundValuesPredicate = predicate; // } // // // public ArrayList<String[]> getGroundValues() // { // return groundValuesPredicate.getGroundValues(); // } // // // public Predicate getGroundValuesPredicate() // { // return groundValuesPredicate; // } // // // @Override // public boolean equals(Object obj) // { // if(obj.getClass() == Type.class) { // Type t = (Type) obj; // return t.getName().equals(this.getName()); // } else { // return false; // } // } // // // public String getId() // { // // return this.getClass().getName(); // } // // // public String toLongString() // { // StringBuilder sb = new StringBuilder(); // sb.append("> type ").append(this.getName()).append("\n"); // if(this.groundValuesPredicate != null) { // for(String[] s : this.groundValuesPredicate.getGroundValues()) { // sb.append("\"" + s[0] + "\"\n"); // } // } // return sb.toString(); // } // // // public String output() // { // String result = "Type " + this.getName() + "T = new Type(\"" + this.getName() + "\");\n"; // if(this.groundValuesPredicate != null) { // result = result + this.getName() + ".values = " + this.getGroundValuesPredicate().getName(); // } // return result; // // } // // // public void setName(String name) // { // this.name = name; // } // // // public String getName() // { // return name; // } // // // public String toString() // { // return name; // } // // // public String toMediumString() // { // return "type " + name + ";"; // } // // // @Override // public int compareTo(Type arg0) // { // return this.name.compareTo(arg0.getName()); // } // // /* // * public int getGroundValueSize() throws ParseException { // * if(this.groundValuesPredicate==null){ // * throw new ParseException("Can not determine the size if no ground values predicate is set. Type name: " + this.name); // * } // * if(groundValueSize==0){ // * for(String[] p:groundValuesPredicate.getGroundValues()){ // * groundValueSize = Math.max(groundValueSize, p[0].length()); // * } // * } // * return groundValueSize; // * } // */ // } // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/FormulaAbstract.java import java.util.ArrayList; import java.util.HashSet; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.javaAPI.formulas.expressions.IfExpression; import com.googlecode.rockit.javaAPI.formulas.expressions.impl.PredicateExpression; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableType; import com.googlecode.rockit.javaAPI.predicates.PredicateAbstract; import com.googlecode.rockit.javaAPI.types.Type; package com.googlecode.rockit.javaAPI.formulas; /** * The basic class of all formular. * * Defines the For- and the If-part of every formular. * * @author jan * */ public abstract class FormulaAbstract implements Comparable<FormulaAbstract> {
private HashSet<VariableType> forVariables = new HashSet<VariableType>();
jnoessner/rockIt
src/main/java/com/googlecode/rockit/app/solver/aggregate/simple/AggregatedConstraint.java
// Path: src/main/java/com/googlecode/rockit/app/solver/pojo/Literal.java // public class Literal // { // private boolean positive; // private String name; // // private GRBVar var; // private int id = -1; // // // public Literal() // { // } // // // public Literal(String name, boolean positive) // { // this.name = name; // this.positive = positive; // } // // // public String getName() // { // return name; // } // // // public void setName(String name) // { // this.name = name; // } // // // public boolean isPositive() // { // return positive; // } // // // public void setPositive(boolean positive) // { // this.positive = positive; // } // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // // @Override // public boolean equals(Object obj) // { // if(this == obj) // return true; // if(obj == null) // return false; // if(getClass() != obj.getClass()) // return false; // Literal other = (Literal) obj; // if(name == null) { // if(other.name != null) // return false; // } else if(!name.equals(other.name)) // return false; // return true; // } // // // // public GRBVar getVar() { // // return var; // // } // // // public void setVar(GRBVar var) { // // this.var = var; // // } // // @Override // public String toString() // { // StringBuilder builder = new StringBuilder(); // builder.append("["); // if(!positive) // builder.append("! "); // builder.append(name); // builder.append("]"); // return builder.toString(); // } // // // public int getId() // { // return id; // } // // // public void setId(int id) // { // this.id = id; // } // // } // // Path: src/main/java/com/googlecode/rockit/exception/ILPException.java // public class ILPException extends SolveException // { // /** // * When the ilp is infeasible, this exception occurs. // */ // private static final long serialVersionUID = -4390221337485101364L; // // // public ILPException() // { // } // // // public ILPException(String msg) // { // super(msg); // } // }
import java.util.ArrayList; import com.googlecode.rockit.app.solver.pojo.Literal; import com.googlecode.rockit.conn.ilp.ILPConnector; import com.googlecode.rockit.exception.ILPException;
package com.googlecode.rockit.app.solver.aggregate.simple; public class AggregatedConstraint { private String id;
// Path: src/main/java/com/googlecode/rockit/app/solver/pojo/Literal.java // public class Literal // { // private boolean positive; // private String name; // // private GRBVar var; // private int id = -1; // // // public Literal() // { // } // // // public Literal(String name, boolean positive) // { // this.name = name; // this.positive = positive; // } // // // public String getName() // { // return name; // } // // // public void setName(String name) // { // this.name = name; // } // // // public boolean isPositive() // { // return positive; // } // // // public void setPositive(boolean positive) // { // this.positive = positive; // } // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // // @Override // public boolean equals(Object obj) // { // if(this == obj) // return true; // if(obj == null) // return false; // if(getClass() != obj.getClass()) // return false; // Literal other = (Literal) obj; // if(name == null) { // if(other.name != null) // return false; // } else if(!name.equals(other.name)) // return false; // return true; // } // // // // public GRBVar getVar() { // // return var; // // } // // // public void setVar(GRBVar var) { // // this.var = var; // // } // // @Override // public String toString() // { // StringBuilder builder = new StringBuilder(); // builder.append("["); // if(!positive) // builder.append("! "); // builder.append(name); // builder.append("]"); // return builder.toString(); // } // // // public int getId() // { // return id; // } // // // public void setId(int id) // { // this.id = id; // } // // } // // Path: src/main/java/com/googlecode/rockit/exception/ILPException.java // public class ILPException extends SolveException // { // /** // * When the ilp is infeasible, this exception occurs. // */ // private static final long serialVersionUID = -4390221337485101364L; // // // public ILPException() // { // } // // // public ILPException(String msg) // { // super(msg); // } // } // Path: src/main/java/com/googlecode/rockit/app/solver/aggregate/simple/AggregatedConstraint.java import java.util.ArrayList; import com.googlecode.rockit.app.solver.pojo.Literal; import com.googlecode.rockit.conn.ilp.ILPConnector; import com.googlecode.rockit.exception.ILPException; package com.googlecode.rockit.app.solver.aggregate.simple; public class AggregatedConstraint { private String id;
private ArrayList<Literal> aggregatedVars = new ArrayList<Literal>();
jnoessner/rockIt
src/main/java/com/googlecode/rockit/app/solver/aggregate/simple/AggregatedConstraint.java
// Path: src/main/java/com/googlecode/rockit/app/solver/pojo/Literal.java // public class Literal // { // private boolean positive; // private String name; // // private GRBVar var; // private int id = -1; // // // public Literal() // { // } // // // public Literal(String name, boolean positive) // { // this.name = name; // this.positive = positive; // } // // // public String getName() // { // return name; // } // // // public void setName(String name) // { // this.name = name; // } // // // public boolean isPositive() // { // return positive; // } // // // public void setPositive(boolean positive) // { // this.positive = positive; // } // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // // @Override // public boolean equals(Object obj) // { // if(this == obj) // return true; // if(obj == null) // return false; // if(getClass() != obj.getClass()) // return false; // Literal other = (Literal) obj; // if(name == null) { // if(other.name != null) // return false; // } else if(!name.equals(other.name)) // return false; // return true; // } // // // // public GRBVar getVar() { // // return var; // // } // // // public void setVar(GRBVar var) { // // this.var = var; // // } // // @Override // public String toString() // { // StringBuilder builder = new StringBuilder(); // builder.append("["); // if(!positive) // builder.append("! "); // builder.append(name); // builder.append("]"); // return builder.toString(); // } // // // public int getId() // { // return id; // } // // // public void setId(int id) // { // this.id = id; // } // // } // // Path: src/main/java/com/googlecode/rockit/exception/ILPException.java // public class ILPException extends SolveException // { // /** // * When the ilp is infeasible, this exception occurs. // */ // private static final long serialVersionUID = -4390221337485101364L; // // // public ILPException() // { // } // // // public ILPException(String msg) // { // super(msg); // } // }
import java.util.ArrayList; import com.googlecode.rockit.app.solver.pojo.Literal; import com.googlecode.rockit.conn.ilp.ILPConnector; import com.googlecode.rockit.exception.ILPException;
package com.googlecode.rockit.app.solver.aggregate.simple; public class AggregatedConstraint { private String id; private ArrayList<Literal> aggregatedVars = new ArrayList<Literal>(); private ArrayList<Literal> singleVars = new ArrayList<Literal>(); private double weight; private boolean conjunction; // private ArrayList<GRBConstr> oldConstraints = new ArrayList<GRBConstr>(); // private boolean deleteConstr =true; public AggregatedConstraint(String id, ArrayList<Literal> aggregatedVars, boolean conjunction, double weight) { this.id = id; // this.zVariable=zVariable; this.aggregatedVars = aggregatedVars; this.weight = weight; this.conjunction = conjunction; // this.oldConstraints=new ArrayList<GRBConstr>(); // this.deleteConstr=true; } public void addSingleVar(Literal singleVar) { this.singleVars.add(singleVar); // this.deleteConstr=true; } public double getWeight() { return this.weight; }
// Path: src/main/java/com/googlecode/rockit/app/solver/pojo/Literal.java // public class Literal // { // private boolean positive; // private String name; // // private GRBVar var; // private int id = -1; // // // public Literal() // { // } // // // public Literal(String name, boolean positive) // { // this.name = name; // this.positive = positive; // } // // // public String getName() // { // return name; // } // // // public void setName(String name) // { // this.name = name; // } // // // public boolean isPositive() // { // return positive; // } // // // public void setPositive(boolean positive) // { // this.positive = positive; // } // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // // @Override // public boolean equals(Object obj) // { // if(this == obj) // return true; // if(obj == null) // return false; // if(getClass() != obj.getClass()) // return false; // Literal other = (Literal) obj; // if(name == null) { // if(other.name != null) // return false; // } else if(!name.equals(other.name)) // return false; // return true; // } // // // // public GRBVar getVar() { // // return var; // // } // // // public void setVar(GRBVar var) { // // this.var = var; // // } // // @Override // public String toString() // { // StringBuilder builder = new StringBuilder(); // builder.append("["); // if(!positive) // builder.append("! "); // builder.append(name); // builder.append("]"); // return builder.toString(); // } // // // public int getId() // { // return id; // } // // // public void setId(int id) // { // this.id = id; // } // // } // // Path: src/main/java/com/googlecode/rockit/exception/ILPException.java // public class ILPException extends SolveException // { // /** // * When the ilp is infeasible, this exception occurs. // */ // private static final long serialVersionUID = -4390221337485101364L; // // // public ILPException() // { // } // // // public ILPException(String msg) // { // super(msg); // } // } // Path: src/main/java/com/googlecode/rockit/app/solver/aggregate/simple/AggregatedConstraint.java import java.util.ArrayList; import com.googlecode.rockit.app.solver.pojo.Literal; import com.googlecode.rockit.conn.ilp.ILPConnector; import com.googlecode.rockit.exception.ILPException; package com.googlecode.rockit.app.solver.aggregate.simple; public class AggregatedConstraint { private String id; private ArrayList<Literal> aggregatedVars = new ArrayList<Literal>(); private ArrayList<Literal> singleVars = new ArrayList<Literal>(); private double weight; private boolean conjunction; // private ArrayList<GRBConstr> oldConstraints = new ArrayList<GRBConstr>(); // private boolean deleteConstr =true; public AggregatedConstraint(String id, ArrayList<Literal> aggregatedVars, boolean conjunction, double weight) { this.id = id; // this.zVariable=zVariable; this.aggregatedVars = aggregatedVars; this.weight = weight; this.conjunction = conjunction; // this.oldConstraints=new ArrayList<GRBConstr>(); // this.deleteConstr=true; } public void addSingleVar(Literal singleVar) { this.singleVars.add(singleVar); // this.deleteConstr=true; } public double getWeight() { return this.weight; }
public void addConstraintAndDeleteOldOne(ILPConnector con) throws ILPException
jnoessner/rockIt
src/main/java/com/googlecode/rockit/test/MiniTestApplication.java
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/exception/SolveException.java // public class SolveException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390221337485101364L; // // // public SolveException() // { // } // // // public SolveException(String msg) // { // super(msg); // } // // }
import java.io.IOException; import java.sql.SQLException; import org.antlr.runtime.RecognitionException; import com.googlecode.rockit.app.Main; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.exception.ReadOrWriteToFileException; import com.googlecode.rockit.exception.SolveException;
package com.googlecode.rockit.test; public class MiniTestApplication { /** * @param args * @throws ReadOrWriteToFileException * @throws SQLException * @throws SolveException * @throws RecognitionException * @throws ParseException * @throws IOException */
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/exception/SolveException.java // public class SolveException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390221337485101364L; // // // public SolveException() // { // } // // // public SolveException(String msg) // { // super(msg); // } // // } // Path: src/main/java/com/googlecode/rockit/test/MiniTestApplication.java import java.io.IOException; import java.sql.SQLException; import org.antlr.runtime.RecognitionException; import com.googlecode.rockit.app.Main; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.exception.ReadOrWriteToFileException; import com.googlecode.rockit.exception.SolveException; package com.googlecode.rockit.test; public class MiniTestApplication { /** * @param args * @throws ReadOrWriteToFileException * @throws SQLException * @throws SolveException * @throws RecognitionException * @throws ParseException * @throws IOException */
public static void main(String[] args) throws IOException, ParseException, RecognitionException, SolveException, SQLException, ReadOrWriteToFileException
jnoessner/rockIt
src/main/java/com/googlecode/rockit/test/MiniTestApplication.java
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/exception/SolveException.java // public class SolveException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390221337485101364L; // // // public SolveException() // { // } // // // public SolveException(String msg) // { // super(msg); // } // // }
import java.io.IOException; import java.sql.SQLException; import org.antlr.runtime.RecognitionException; import com.googlecode.rockit.app.Main; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.exception.ReadOrWriteToFileException; import com.googlecode.rockit.exception.SolveException;
package com.googlecode.rockit.test; public class MiniTestApplication { /** * @param args * @throws ReadOrWriteToFileException * @throws SQLException * @throws SolveException * @throws RecognitionException * @throws ParseException * @throws IOException */
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/exception/SolveException.java // public class SolveException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390221337485101364L; // // // public SolveException() // { // } // // // public SolveException(String msg) // { // super(msg); // } // // } // Path: src/main/java/com/googlecode/rockit/test/MiniTestApplication.java import java.io.IOException; import java.sql.SQLException; import org.antlr.runtime.RecognitionException; import com.googlecode.rockit.app.Main; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.exception.ReadOrWriteToFileException; import com.googlecode.rockit.exception.SolveException; package com.googlecode.rockit.test; public class MiniTestApplication { /** * @param args * @throws ReadOrWriteToFileException * @throws SQLException * @throws SolveException * @throws RecognitionException * @throws ParseException * @throws IOException */
public static void main(String[] args) throws IOException, ParseException, RecognitionException, SolveException, SQLException, ReadOrWriteToFileException
jnoessner/rockIt
src/main/java/com/googlecode/rockit/javaAPI/formulas/FormulaObjective.java
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableDouble.java // public class VariableDouble extends VariableAbstract // { // public VariableDouble() // { // } // // // public VariableDouble(String name) // { // this.setName(name); // } // // // public String toString() // { // return this.getName(); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableType.java // public class VariableType extends VariableAbstract // { // private Type type; // // // public VariableType() // { // } // // // public VariableType(String name, Type type) // { // this.setName(name); // this.type = type; // } // // // public VariableType(String name) // { // this.setName(name); // } // // // public void setType(Type type) // { // this.type = type; // // } // // // public Type getType() // { // return type; // } // // // public String toString() // { // return getName(); // } // // }
import java.util.ArrayList; import java.util.HashSet; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.javaAPI.formulas.expressions.IfExpression; import com.googlecode.rockit.javaAPI.formulas.expressions.impl.PredicateExpression; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableDouble; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableType; import com.googlecode.rockit.javaAPI.predicates.PredicateAbstract;
package com.googlecode.rockit.javaAPI.formulas; /** * Formular with only 1 positive literal assigned with a double weight. * * @author jan * */ public class FormulaObjective extends FormulaAbstract {
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableDouble.java // public class VariableDouble extends VariableAbstract // { // public VariableDouble() // { // } // // // public VariableDouble(String name) // { // this.setName(name); // } // // // public String toString() // { // return this.getName(); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableType.java // public class VariableType extends VariableAbstract // { // private Type type; // // // public VariableType() // { // } // // // public VariableType(String name, Type type) // { // this.setName(name); // this.type = type; // } // // // public VariableType(String name) // { // this.setName(name); // } // // // public void setType(Type type) // { // this.type = type; // // } // // // public Type getType() // { // return type; // } // // // public String toString() // { // return getName(); // } // // } // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/FormulaObjective.java import java.util.ArrayList; import java.util.HashSet; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.javaAPI.formulas.expressions.IfExpression; import com.googlecode.rockit.javaAPI.formulas.expressions.impl.PredicateExpression; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableDouble; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableType; import com.googlecode.rockit.javaAPI.predicates.PredicateAbstract; package com.googlecode.rockit.javaAPI.formulas; /** * Formular with only 1 positive literal assigned with a double weight. * * @author jan * */ public class FormulaObjective extends FormulaAbstract {
private VariableDouble doubleVariable;
jnoessner/rockIt
src/main/java/com/googlecode/rockit/javaAPI/formulas/FormulaObjective.java
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableDouble.java // public class VariableDouble extends VariableAbstract // { // public VariableDouble() // { // } // // // public VariableDouble(String name) // { // this.setName(name); // } // // // public String toString() // { // return this.getName(); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableType.java // public class VariableType extends VariableAbstract // { // private Type type; // // // public VariableType() // { // } // // // public VariableType(String name, Type type) // { // this.setName(name); // this.type = type; // } // // // public VariableType(String name) // { // this.setName(name); // } // // // public void setType(Type type) // { // this.type = type; // // } // // // public Type getType() // { // return type; // } // // // public String toString() // { // return getName(); // } // // }
import java.util.ArrayList; import java.util.HashSet; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.javaAPI.formulas.expressions.IfExpression; import com.googlecode.rockit.javaAPI.formulas.expressions.impl.PredicateExpression; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableDouble; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableType; import com.googlecode.rockit.javaAPI.predicates.PredicateAbstract;
package com.googlecode.rockit.javaAPI.formulas; /** * Formular with only 1 positive literal assigned with a double weight. * * @author jan * */ public class FormulaObjective extends FormulaAbstract { private VariableDouble doubleVariable; private PredicateExpression objectiveExpression; private Double weight = null; public FormulaObjective() { }
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableDouble.java // public class VariableDouble extends VariableAbstract // { // public VariableDouble() // { // } // // // public VariableDouble(String name) // { // this.setName(name); // } // // // public String toString() // { // return this.getName(); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableType.java // public class VariableType extends VariableAbstract // { // private Type type; // // // public VariableType() // { // } // // // public VariableType(String name, Type type) // { // this.setName(name); // this.type = type; // } // // // public VariableType(String name) // { // this.setName(name); // } // // // public void setType(Type type) // { // this.type = type; // // } // // // public Type getType() // { // return type; // } // // // public String toString() // { // return getName(); // } // // } // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/FormulaObjective.java import java.util.ArrayList; import java.util.HashSet; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.javaAPI.formulas.expressions.IfExpression; import com.googlecode.rockit.javaAPI.formulas.expressions.impl.PredicateExpression; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableDouble; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableType; import com.googlecode.rockit.javaAPI.predicates.PredicateAbstract; package com.googlecode.rockit.javaAPI.formulas; /** * Formular with only 1 positive literal assigned with a double weight. * * @author jan * */ public class FormulaObjective extends FormulaAbstract { private VariableDouble doubleVariable; private PredicateExpression objectiveExpression; private Double weight = null; public FormulaObjective() { }
public FormulaObjective(String name, HashSet<VariableType> forVariables, ArrayList<IfExpression> ifExpressions, VariableDouble doubleVariable, PredicateExpression objectiveExpression) throws ParseException
jnoessner/rockIt
src/main/java/com/googlecode/rockit/javaAPI/formulas/FormulaObjective.java
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableDouble.java // public class VariableDouble extends VariableAbstract // { // public VariableDouble() // { // } // // // public VariableDouble(String name) // { // this.setName(name); // } // // // public String toString() // { // return this.getName(); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableType.java // public class VariableType extends VariableAbstract // { // private Type type; // // // public VariableType() // { // } // // // public VariableType(String name, Type type) // { // this.setName(name); // this.type = type; // } // // // public VariableType(String name) // { // this.setName(name); // } // // // public void setType(Type type) // { // this.type = type; // // } // // // public Type getType() // { // return type; // } // // // public String toString() // { // return getName(); // } // // }
import java.util.ArrayList; import java.util.HashSet; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.javaAPI.formulas.expressions.IfExpression; import com.googlecode.rockit.javaAPI.formulas.expressions.impl.PredicateExpression; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableDouble; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableType; import com.googlecode.rockit.javaAPI.predicates.PredicateAbstract;
package com.googlecode.rockit.javaAPI.formulas; /** * Formular with only 1 positive literal assigned with a double weight. * * @author jan * */ public class FormulaObjective extends FormulaAbstract { private VariableDouble doubleVariable; private PredicateExpression objectiveExpression; private Double weight = null; public FormulaObjective() { }
// Path: src/main/java/com/googlecode/rockit/exception/ParseException.java // public class ParseException extends Exception // { // // /** // * Exceptions which can occur in the Parse Phase of the application. // */ // private static final long serialVersionUID = -4390051337485101364L; // // // public ParseException() // { // } // // // public ParseException(String msg) // { // super(Messages.printParseExceptionError(msg)); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableDouble.java // public class VariableDouble extends VariableAbstract // { // public VariableDouble() // { // } // // // public VariableDouble(String name) // { // this.setName(name); // } // // // public String toString() // { // return this.getName(); // } // // } // // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/variables/impl/VariableType.java // public class VariableType extends VariableAbstract // { // private Type type; // // // public VariableType() // { // } // // // public VariableType(String name, Type type) // { // this.setName(name); // this.type = type; // } // // // public VariableType(String name) // { // this.setName(name); // } // // // public void setType(Type type) // { // this.type = type; // // } // // // public Type getType() // { // return type; // } // // // public String toString() // { // return getName(); // } // // } // Path: src/main/java/com/googlecode/rockit/javaAPI/formulas/FormulaObjective.java import java.util.ArrayList; import java.util.HashSet; import com.googlecode.rockit.exception.ParseException; import com.googlecode.rockit.javaAPI.formulas.expressions.IfExpression; import com.googlecode.rockit.javaAPI.formulas.expressions.impl.PredicateExpression; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableDouble; import com.googlecode.rockit.javaAPI.formulas.variables.impl.VariableType; import com.googlecode.rockit.javaAPI.predicates.PredicateAbstract; package com.googlecode.rockit.javaAPI.formulas; /** * Formular with only 1 positive literal assigned with a double weight. * * @author jan * */ public class FormulaObjective extends FormulaAbstract { private VariableDouble doubleVariable; private PredicateExpression objectiveExpression; private Double weight = null; public FormulaObjective() { }
public FormulaObjective(String name, HashSet<VariableType> forVariables, ArrayList<IfExpression> ifExpressions, VariableDouble doubleVariable, PredicateExpression objectiveExpression) throws ParseException
SecUSo/privacy-friendly-weather
app/src/test/java/org/secuso/privacyfriendlyweather/TimeTest.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/util/TimeUtil.java // public class TimeUtil { // private static SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault()); // // public static long getStartOfDay(int timezoneInSeconds) { // return getStartOfDayCustomCurrentTime(timezoneInSeconds, System.currentTimeMillis()); // } // // public static long getStartOfDayCustomCurrentTime(int timezoneInSeconds, long currentTime) { // Calendar cal = Calendar.getInstance(); // cal.setTimeZone(TimeZone.getTimeZone("GMT")); // cal.set(Calendar.DST_OFFSET, 0); // cal.setTimeInMillis(currentTime); // cal.set(Calendar.HOUR_OF_DAY, 0); // cal.set(Calendar.MINUTE, 0); // cal.set(Calendar.ZONE_OFFSET, timezoneInSeconds); // // long startOfDay = cal.getTimeInMillis(); // //Log.d("devtag", "calendar " + cal.getTimeInMillis() + cal.getTime()); // // if (currentTime < startOfDay) { // cal.add(Calendar.HOUR_OF_DAY, -24); // } // if (currentTime > startOfDay + 24 * 3600 * 1000) { // cal.add(Calendar.HOUR_OF_DAY, 24); // } // return cal.getTimeInMillis(); // } // // public static String formatTimeSimple(int timeZoneSeconds, long timeInSeconds) { // timeFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // Date dateTime = new Date((timeInSeconds + timeZoneSeconds) * 1000L); // return timeFormat.format(dateTime); // } // }
import org.junit.Test; import org.secuso.privacyfriendlyweather.util.TimeUtil; import java.sql.Time; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package org.secuso.privacyfriendlyweather; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class TimeTest { @Test public void testTimeStartOfDay() { long currentTime = 1599659833857L;
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/util/TimeUtil.java // public class TimeUtil { // private static SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault()); // // public static long getStartOfDay(int timezoneInSeconds) { // return getStartOfDayCustomCurrentTime(timezoneInSeconds, System.currentTimeMillis()); // } // // public static long getStartOfDayCustomCurrentTime(int timezoneInSeconds, long currentTime) { // Calendar cal = Calendar.getInstance(); // cal.setTimeZone(TimeZone.getTimeZone("GMT")); // cal.set(Calendar.DST_OFFSET, 0); // cal.setTimeInMillis(currentTime); // cal.set(Calendar.HOUR_OF_DAY, 0); // cal.set(Calendar.MINUTE, 0); // cal.set(Calendar.ZONE_OFFSET, timezoneInSeconds); // // long startOfDay = cal.getTimeInMillis(); // //Log.d("devtag", "calendar " + cal.getTimeInMillis() + cal.getTime()); // // if (currentTime < startOfDay) { // cal.add(Calendar.HOUR_OF_DAY, -24); // } // if (currentTime > startOfDay + 24 * 3600 * 1000) { // cal.add(Calendar.HOUR_OF_DAY, 24); // } // return cal.getTimeInMillis(); // } // // public static String formatTimeSimple(int timeZoneSeconds, long timeInSeconds) { // timeFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // Date dateTime = new Date((timeInSeconds + timeZoneSeconds) * 1000L); // return timeFormat.format(dateTime); // } // } // Path: app/src/test/java/org/secuso/privacyfriendlyweather/TimeTest.java import org.junit.Test; import org.secuso.privacyfriendlyweather.util.TimeUtil; import java.sql.Time; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package org.secuso.privacyfriendlyweather; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class TimeTest { @Test public void testTimeStartOfDay() { long currentTime = 1599659833857L;
long startOfDay = TimeUtil.getStartOfDayCustomCurrentTime(3 * 3600, currentTime);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForForecast.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForForecast.java // public interface IHttpRequestForForecast { // // /** // * @param cityId The (OWM) ID of the city to get the data for. // */ // void perform(int cityId); // // }
import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForForecast;
package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForForecast extends OwmHttpRequest implements IHttpRequestForForecast { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForForecast(Context context) { this.context = context; } /** * @see IHttpRequestForForecast#perform(int) */ @Override public void perform(int cityId) {
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForForecast.java // public interface IHttpRequestForForecast { // // /** // * @param cityId The (OWM) ID of the city to get the data for. // */ // void perform(int cityId); // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForForecast.java import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForForecast; package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForForecast extends OwmHttpRequest implements IHttpRequestForForecast { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForForecast(Context context) { this.context = context; } /** * @see IHttpRequestForForecast#perform(int) */ @Override public void perform(int cityId) {
IHttpRequest httpRequest = new VolleyHttpRequest(context);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForForecast.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForForecast.java // public interface IHttpRequestForForecast { // // /** // * @param cityId The (OWM) ID of the city to get the data for. // */ // void perform(int cityId); // // }
import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForForecast;
package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForForecast extends OwmHttpRequest implements IHttpRequestForForecast { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForForecast(Context context) { this.context = context; } /** * @see IHttpRequestForForecast#perform(int) */ @Override public void perform(int cityId) {
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForForecast.java // public interface IHttpRequestForForecast { // // /** // * @param cityId The (OWM) ID of the city to get the data for. // */ // void perform(int cityId); // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForForecast.java import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForForecast; package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForForecast extends OwmHttpRequest implements IHttpRequestForForecast { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForForecast(Context context) { this.context = context; } /** * @see IHttpRequestForForecast#perform(int) */ @Override public void perform(int cityId) {
IHttpRequest httpRequest = new VolleyHttpRequest(context);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForForecast.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForForecast.java // public interface IHttpRequestForForecast { // // /** // * @param cityId The (OWM) ID of the city to get the data for. // */ // void perform(int cityId); // // }
import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForForecast;
package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForForecast extends OwmHttpRequest implements IHttpRequestForForecast { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForForecast(Context context) { this.context = context; } /** * @see IHttpRequestForForecast#perform(int) */ @Override public void perform(int cityId) { IHttpRequest httpRequest = new VolleyHttpRequest(context); final String URL = getUrlForQueryingForecast(context, cityId);
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForForecast.java // public interface IHttpRequestForForecast { // // /** // * @param cityId The (OWM) ID of the city to get the data for. // */ // void perform(int cityId); // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForForecast.java import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForForecast; package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForForecast extends OwmHttpRequest implements IHttpRequestForForecast { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForForecast(Context context) { this.context = context; } /** * @see IHttpRequestForForecast#perform(int) */ @Override public void perform(int cityId) { IHttpRequest httpRequest = new VolleyHttpRequest(context); final String URL = getUrlForQueryingForecast(context, cityId);
httpRequest.make(URL, HttpRequestType.GET, new ProcessOwmForecastRequest(context));
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/activities/HelpActivity.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/ui/Help/ExpandableListAdapter.java // public class ExpandableListAdapter extends BaseExpandableListAdapter { // // private Context context; // private List<String> expandableListTitle; // private HashMap<String, List<String>> expandableListDetail; // // public ExpandableListAdapter(Context context, List<String> expandableListTitle, // HashMap<String, List<String>> expandableListDetail) { // this.context = context; // this.expandableListTitle = expandableListTitle; // this.expandableListDetail = expandableListDetail; // } // // @Override // public Object getChild(int listPosition, int expandedListPosition) { // return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)) // .get(expandedListPosition); // } // // @Override // public long getChildId(int listPosition, int expandedListPosition) { // return expandedListPosition; // } // // @Override // public View getChildView(int listPosition, final int expandedListPosition, // boolean isLastChild, View convertView, ViewGroup parent) { // final String expandedListText = (String) getChild(listPosition, expandedListPosition); // if (convertView == null) { // LayoutInflater layoutInflater = (LayoutInflater) this.context // .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // convertView = layoutInflater.inflate(R.layout.list_item, null); // } // TextView expandedListTextView = (TextView) convertView // .findViewById(R.id.expandedListItem); // expandedListTextView.setText(expandedListText); // return convertView; // } // // @Override // public int getChildrenCount(int listPosition) { // return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)) // .size(); // } // // @Override // public Object getGroup(int listPosition) { // return this.expandableListTitle.get(listPosition); // } // // @Override // public int getGroupCount() { // return this.expandableListTitle.size(); // } // // @Override // public long getGroupId(int listPosition) { // return listPosition; // } // // @Override // public View getGroupView(int listPosition, boolean isExpanded, // View convertView, ViewGroup parent) { // String listTitle = (String) getGroup(listPosition); // if (convertView == null) { // LayoutInflater layoutInflater = (LayoutInflater) this.context. // getSystemService(Context.LAYOUT_INFLATER_SERVICE); // convertView = layoutInflater.inflate(R.layout.list_group, null); // } // TextView listTitleTextView = (TextView) convertView // .findViewById(R.id.listTitle); // listTitleTextView.setTypeface(null, Typeface.BOLD); // listTitleTextView.setText(listTitle); // return convertView; // } // // @Override // public boolean hasStableIds() { // return false; // } // // @Override // public boolean isChildSelectable(int listPosition, int expandedListPosition) { // return true; // } // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/ui/Help/HelpDataDump.java // public class HelpDataDump { // // private Context context; // // public HelpDataDump(Context context) { // this.context = context; // } // // public LinkedHashMap<String, List<String>> getDataGeneral() { // LinkedHashMap<String, List<String>> expandableListDetail = new LinkedHashMap<String, List<String>>(); // List<String> general = new ArrayList<String>(); // general.add(context.getResources().getString(R.string.help_whatis_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_whatis), general); // // List<String> where = new ArrayList<String>(); // where.add(context.getResources().getString(R.string.help_where_from_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_where_from), where); // // List<String> radius = new ArrayList<String>(); // radius.add(context.getResources().getString(R.string.help_radius_search_text)); // expandableListDetail.put(context.getResources().getString(R.string.help_radius_search_title), radius); // // List<String> privacy = new ArrayList<String>(); // privacy.add(context.getResources().getString(R.string.help_privacy_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_privacy_heading), privacy); // // List<String> permissions = new ArrayList<String>(); // permissions.add(context.getResources().getString(R.string.help_permission_internet_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_internet_description)); // permissions.add(context.getResources().getString(R.string.help_permission_wakelock_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_wakelock_description)); // permissions.add(context.getResources().getString(R.string.help_permission_bindservice_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_bindservice_description)); // expandableListDetail.put(context.getResources().getString(R.string.help_permissions_heading), permissions); // // return expandableListDetail; // } // // }
import android.os.Bundle; import android.widget.ExpandableListView; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.ui.Help.ExpandableListAdapter; import org.secuso.privacyfriendlyweather.ui.Help.HelpDataDump; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List;
package org.secuso.privacyfriendlyweather.activities; /** * Created by yonjuni on 17.06.16. */ public class HelpActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help);
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/ui/Help/ExpandableListAdapter.java // public class ExpandableListAdapter extends BaseExpandableListAdapter { // // private Context context; // private List<String> expandableListTitle; // private HashMap<String, List<String>> expandableListDetail; // // public ExpandableListAdapter(Context context, List<String> expandableListTitle, // HashMap<String, List<String>> expandableListDetail) { // this.context = context; // this.expandableListTitle = expandableListTitle; // this.expandableListDetail = expandableListDetail; // } // // @Override // public Object getChild(int listPosition, int expandedListPosition) { // return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)) // .get(expandedListPosition); // } // // @Override // public long getChildId(int listPosition, int expandedListPosition) { // return expandedListPosition; // } // // @Override // public View getChildView(int listPosition, final int expandedListPosition, // boolean isLastChild, View convertView, ViewGroup parent) { // final String expandedListText = (String) getChild(listPosition, expandedListPosition); // if (convertView == null) { // LayoutInflater layoutInflater = (LayoutInflater) this.context // .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // convertView = layoutInflater.inflate(R.layout.list_item, null); // } // TextView expandedListTextView = (TextView) convertView // .findViewById(R.id.expandedListItem); // expandedListTextView.setText(expandedListText); // return convertView; // } // // @Override // public int getChildrenCount(int listPosition) { // return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)) // .size(); // } // // @Override // public Object getGroup(int listPosition) { // return this.expandableListTitle.get(listPosition); // } // // @Override // public int getGroupCount() { // return this.expandableListTitle.size(); // } // // @Override // public long getGroupId(int listPosition) { // return listPosition; // } // // @Override // public View getGroupView(int listPosition, boolean isExpanded, // View convertView, ViewGroup parent) { // String listTitle = (String) getGroup(listPosition); // if (convertView == null) { // LayoutInflater layoutInflater = (LayoutInflater) this.context. // getSystemService(Context.LAYOUT_INFLATER_SERVICE); // convertView = layoutInflater.inflate(R.layout.list_group, null); // } // TextView listTitleTextView = (TextView) convertView // .findViewById(R.id.listTitle); // listTitleTextView.setTypeface(null, Typeface.BOLD); // listTitleTextView.setText(listTitle); // return convertView; // } // // @Override // public boolean hasStableIds() { // return false; // } // // @Override // public boolean isChildSelectable(int listPosition, int expandedListPosition) { // return true; // } // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/ui/Help/HelpDataDump.java // public class HelpDataDump { // // private Context context; // // public HelpDataDump(Context context) { // this.context = context; // } // // public LinkedHashMap<String, List<String>> getDataGeneral() { // LinkedHashMap<String, List<String>> expandableListDetail = new LinkedHashMap<String, List<String>>(); // List<String> general = new ArrayList<String>(); // general.add(context.getResources().getString(R.string.help_whatis_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_whatis), general); // // List<String> where = new ArrayList<String>(); // where.add(context.getResources().getString(R.string.help_where_from_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_where_from), where); // // List<String> radius = new ArrayList<String>(); // radius.add(context.getResources().getString(R.string.help_radius_search_text)); // expandableListDetail.put(context.getResources().getString(R.string.help_radius_search_title), radius); // // List<String> privacy = new ArrayList<String>(); // privacy.add(context.getResources().getString(R.string.help_privacy_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_privacy_heading), privacy); // // List<String> permissions = new ArrayList<String>(); // permissions.add(context.getResources().getString(R.string.help_permission_internet_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_internet_description)); // permissions.add(context.getResources().getString(R.string.help_permission_wakelock_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_wakelock_description)); // permissions.add(context.getResources().getString(R.string.help_permission_bindservice_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_bindservice_description)); // expandableListDetail.put(context.getResources().getString(R.string.help_permissions_heading), permissions); // // return expandableListDetail; // } // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/activities/HelpActivity.java import android.os.Bundle; import android.widget.ExpandableListView; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.ui.Help.ExpandableListAdapter; import org.secuso.privacyfriendlyweather.ui.Help.HelpDataDump; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; package org.secuso.privacyfriendlyweather.activities; /** * Created by yonjuni on 17.06.16. */ public class HelpActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help);
ExpandableListAdapter expandableListAdapter;
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/activities/HelpActivity.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/ui/Help/ExpandableListAdapter.java // public class ExpandableListAdapter extends BaseExpandableListAdapter { // // private Context context; // private List<String> expandableListTitle; // private HashMap<String, List<String>> expandableListDetail; // // public ExpandableListAdapter(Context context, List<String> expandableListTitle, // HashMap<String, List<String>> expandableListDetail) { // this.context = context; // this.expandableListTitle = expandableListTitle; // this.expandableListDetail = expandableListDetail; // } // // @Override // public Object getChild(int listPosition, int expandedListPosition) { // return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)) // .get(expandedListPosition); // } // // @Override // public long getChildId(int listPosition, int expandedListPosition) { // return expandedListPosition; // } // // @Override // public View getChildView(int listPosition, final int expandedListPosition, // boolean isLastChild, View convertView, ViewGroup parent) { // final String expandedListText = (String) getChild(listPosition, expandedListPosition); // if (convertView == null) { // LayoutInflater layoutInflater = (LayoutInflater) this.context // .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // convertView = layoutInflater.inflate(R.layout.list_item, null); // } // TextView expandedListTextView = (TextView) convertView // .findViewById(R.id.expandedListItem); // expandedListTextView.setText(expandedListText); // return convertView; // } // // @Override // public int getChildrenCount(int listPosition) { // return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)) // .size(); // } // // @Override // public Object getGroup(int listPosition) { // return this.expandableListTitle.get(listPosition); // } // // @Override // public int getGroupCount() { // return this.expandableListTitle.size(); // } // // @Override // public long getGroupId(int listPosition) { // return listPosition; // } // // @Override // public View getGroupView(int listPosition, boolean isExpanded, // View convertView, ViewGroup parent) { // String listTitle = (String) getGroup(listPosition); // if (convertView == null) { // LayoutInflater layoutInflater = (LayoutInflater) this.context. // getSystemService(Context.LAYOUT_INFLATER_SERVICE); // convertView = layoutInflater.inflate(R.layout.list_group, null); // } // TextView listTitleTextView = (TextView) convertView // .findViewById(R.id.listTitle); // listTitleTextView.setTypeface(null, Typeface.BOLD); // listTitleTextView.setText(listTitle); // return convertView; // } // // @Override // public boolean hasStableIds() { // return false; // } // // @Override // public boolean isChildSelectable(int listPosition, int expandedListPosition) { // return true; // } // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/ui/Help/HelpDataDump.java // public class HelpDataDump { // // private Context context; // // public HelpDataDump(Context context) { // this.context = context; // } // // public LinkedHashMap<String, List<String>> getDataGeneral() { // LinkedHashMap<String, List<String>> expandableListDetail = new LinkedHashMap<String, List<String>>(); // List<String> general = new ArrayList<String>(); // general.add(context.getResources().getString(R.string.help_whatis_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_whatis), general); // // List<String> where = new ArrayList<String>(); // where.add(context.getResources().getString(R.string.help_where_from_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_where_from), where); // // List<String> radius = new ArrayList<String>(); // radius.add(context.getResources().getString(R.string.help_radius_search_text)); // expandableListDetail.put(context.getResources().getString(R.string.help_radius_search_title), radius); // // List<String> privacy = new ArrayList<String>(); // privacy.add(context.getResources().getString(R.string.help_privacy_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_privacy_heading), privacy); // // List<String> permissions = new ArrayList<String>(); // permissions.add(context.getResources().getString(R.string.help_permission_internet_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_internet_description)); // permissions.add(context.getResources().getString(R.string.help_permission_wakelock_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_wakelock_description)); // permissions.add(context.getResources().getString(R.string.help_permission_bindservice_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_bindservice_description)); // expandableListDetail.put(context.getResources().getString(R.string.help_permissions_heading), permissions); // // return expandableListDetail; // } // // }
import android.os.Bundle; import android.widget.ExpandableListView; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.ui.Help.ExpandableListAdapter; import org.secuso.privacyfriendlyweather.ui.Help.HelpDataDump; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List;
package org.secuso.privacyfriendlyweather.activities; /** * Created by yonjuni on 17.06.16. */ public class HelpActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help); ExpandableListAdapter expandableListAdapter;
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/ui/Help/ExpandableListAdapter.java // public class ExpandableListAdapter extends BaseExpandableListAdapter { // // private Context context; // private List<String> expandableListTitle; // private HashMap<String, List<String>> expandableListDetail; // // public ExpandableListAdapter(Context context, List<String> expandableListTitle, // HashMap<String, List<String>> expandableListDetail) { // this.context = context; // this.expandableListTitle = expandableListTitle; // this.expandableListDetail = expandableListDetail; // } // // @Override // public Object getChild(int listPosition, int expandedListPosition) { // return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)) // .get(expandedListPosition); // } // // @Override // public long getChildId(int listPosition, int expandedListPosition) { // return expandedListPosition; // } // // @Override // public View getChildView(int listPosition, final int expandedListPosition, // boolean isLastChild, View convertView, ViewGroup parent) { // final String expandedListText = (String) getChild(listPosition, expandedListPosition); // if (convertView == null) { // LayoutInflater layoutInflater = (LayoutInflater) this.context // .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // convertView = layoutInflater.inflate(R.layout.list_item, null); // } // TextView expandedListTextView = (TextView) convertView // .findViewById(R.id.expandedListItem); // expandedListTextView.setText(expandedListText); // return convertView; // } // // @Override // public int getChildrenCount(int listPosition) { // return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)) // .size(); // } // // @Override // public Object getGroup(int listPosition) { // return this.expandableListTitle.get(listPosition); // } // // @Override // public int getGroupCount() { // return this.expandableListTitle.size(); // } // // @Override // public long getGroupId(int listPosition) { // return listPosition; // } // // @Override // public View getGroupView(int listPosition, boolean isExpanded, // View convertView, ViewGroup parent) { // String listTitle = (String) getGroup(listPosition); // if (convertView == null) { // LayoutInflater layoutInflater = (LayoutInflater) this.context. // getSystemService(Context.LAYOUT_INFLATER_SERVICE); // convertView = layoutInflater.inflate(R.layout.list_group, null); // } // TextView listTitleTextView = (TextView) convertView // .findViewById(R.id.listTitle); // listTitleTextView.setTypeface(null, Typeface.BOLD); // listTitleTextView.setText(listTitle); // return convertView; // } // // @Override // public boolean hasStableIds() { // return false; // } // // @Override // public boolean isChildSelectable(int listPosition, int expandedListPosition) { // return true; // } // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/ui/Help/HelpDataDump.java // public class HelpDataDump { // // private Context context; // // public HelpDataDump(Context context) { // this.context = context; // } // // public LinkedHashMap<String, List<String>> getDataGeneral() { // LinkedHashMap<String, List<String>> expandableListDetail = new LinkedHashMap<String, List<String>>(); // List<String> general = new ArrayList<String>(); // general.add(context.getResources().getString(R.string.help_whatis_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_whatis), general); // // List<String> where = new ArrayList<String>(); // where.add(context.getResources().getString(R.string.help_where_from_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_where_from), where); // // List<String> radius = new ArrayList<String>(); // radius.add(context.getResources().getString(R.string.help_radius_search_text)); // expandableListDetail.put(context.getResources().getString(R.string.help_radius_search_title), radius); // // List<String> privacy = new ArrayList<String>(); // privacy.add(context.getResources().getString(R.string.help_privacy_answer)); // expandableListDetail.put(context.getResources().getString(R.string.help_privacy_heading), privacy); // // List<String> permissions = new ArrayList<String>(); // permissions.add(context.getResources().getString(R.string.help_permission_internet_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_internet_description)); // permissions.add(context.getResources().getString(R.string.help_permission_wakelock_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_wakelock_description)); // permissions.add(context.getResources().getString(R.string.help_permission_bindservice_heading)); // permissions.add(context.getResources().getString(R.string.help_permission_bindservice_description)); // expandableListDetail.put(context.getResources().getString(R.string.help_permissions_heading), permissions); // // return expandableListDetail; // } // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/activities/HelpActivity.java import android.os.Bundle; import android.widget.ExpandableListView; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.ui.Help.ExpandableListAdapter; import org.secuso.privacyfriendlyweather.ui.Help.HelpDataDump; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; package org.secuso.privacyfriendlyweather.activities; /** * Created by yonjuni on 17.06.16. */ public class HelpActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help); ExpandableListAdapter expandableListAdapter;
HelpDataDump helpDataDump = new HelpDataDump(this);
SecUSo/privacy-friendly-weather
app/src/androidTest/java/org/secuso/privacyfriendlyweather/database/DatabaseTest.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/data/City.java // @Entity(tableName = "CITIES", indices = {@Index(value = {"city_name", "cities_id"})}) // public class City { // // private static final String UNKNOWN_POSTAL_CODE_VALUE = "-"; // // @PrimaryKey @ColumnInfo(name = "cities_id") private int cityId; // @ColumnInfo(name = "city_name") @NonNull private String cityName = ""; // @ColumnInfo(name = "country_code") @NonNull private String countryCode = ""; // @ColumnInfo(name = "longitude") private float longitude; // @ColumnInfo(name = "latitude") private float latitude; // // public City() { } // // @Ignore public City(int cityId, @NonNull String cityName, @NonNull String countryCode, float lon, float lat) { // this.cityId = cityId; // this.cityName = cityName; // this.countryCode = countryCode; // this.longitude = lon; // this.latitude = lat; // } // // public int getCityId() { // return cityId; // } // // public void setCityId(int cityId) { // this.cityId = cityId; // } // // public @NonNull String getCityName() { // return cityName; // } // // public void setCityName(@NonNull String cityName) { // this.cityName = cityName; // } // // public @NonNull String getCountryCode() { // return countryCode; // } // // public void setCountryCode(@NonNull String countryCode) { // this.countryCode = countryCode; // } // // @Override // public @NonNull String toString() { // return String.format(Locale.ENGLISH, "%s, %s (%f - %f)", cityName, countryCode, longitude, latitude); // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public float getLatitude() { // return latitude; // } // // public float getLongitude() { // return longitude; // } // // public void setLongitude(float lon) { // this.longitude = lon; // } // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // public static final String DB_NAME = "PF_WEATHER_DB.db";
import android.content.Context; import androidx.room.Room; import androidx.room.testing.MigrationTestHelper; import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.secuso.privacyfriendlyweather.BuildConfig; import org.secuso.privacyfriendlyweather.database.data.City; import java.io.IOException; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.secuso.privacyfriendlyweather.database.AppDatabase.DB_NAME;
package org.secuso.privacyfriendlyweather.database; @RunWith(AndroidJUnit4.class) public class DatabaseTest { private static final String TAG = "AppTest"; private static final Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); private static final Context testContext = InstrumentationRegistry.getInstrumentation().getContext(); @Test public void useAppContext() { Assert.assertEquals(BuildConfig.APPLICATION_ID, appContext.getPackageName()); } @Before public void prepareDatabase() {
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/data/City.java // @Entity(tableName = "CITIES", indices = {@Index(value = {"city_name", "cities_id"})}) // public class City { // // private static final String UNKNOWN_POSTAL_CODE_VALUE = "-"; // // @PrimaryKey @ColumnInfo(name = "cities_id") private int cityId; // @ColumnInfo(name = "city_name") @NonNull private String cityName = ""; // @ColumnInfo(name = "country_code") @NonNull private String countryCode = ""; // @ColumnInfo(name = "longitude") private float longitude; // @ColumnInfo(name = "latitude") private float latitude; // // public City() { } // // @Ignore public City(int cityId, @NonNull String cityName, @NonNull String countryCode, float lon, float lat) { // this.cityId = cityId; // this.cityName = cityName; // this.countryCode = countryCode; // this.longitude = lon; // this.latitude = lat; // } // // public int getCityId() { // return cityId; // } // // public void setCityId(int cityId) { // this.cityId = cityId; // } // // public @NonNull String getCityName() { // return cityName; // } // // public void setCityName(@NonNull String cityName) { // this.cityName = cityName; // } // // public @NonNull String getCountryCode() { // return countryCode; // } // // public void setCountryCode(@NonNull String countryCode) { // this.countryCode = countryCode; // } // // @Override // public @NonNull String toString() { // return String.format(Locale.ENGLISH, "%s, %s (%f - %f)", cityName, countryCode, longitude, latitude); // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public float getLatitude() { // return latitude; // } // // public float getLongitude() { // return longitude; // } // // public void setLongitude(float lon) { // this.longitude = lon; // } // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // public static final String DB_NAME = "PF_WEATHER_DB.db"; // Path: app/src/androidTest/java/org/secuso/privacyfriendlyweather/database/DatabaseTest.java import android.content.Context; import androidx.room.Room; import androidx.room.testing.MigrationTestHelper; import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.secuso.privacyfriendlyweather.BuildConfig; import org.secuso.privacyfriendlyweather.database.data.City; import java.io.IOException; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.secuso.privacyfriendlyweather.database.AppDatabase.DB_NAME; package org.secuso.privacyfriendlyweather.database; @RunWith(AndroidJUnit4.class) public class DatabaseTest { private static final String TAG = "AppTest"; private static final Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); private static final Context testContext = InstrumentationRegistry.getInstrumentation().getContext(); @Test public void useAppContext() { Assert.assertEquals(BuildConfig.APPLICATION_ID, appContext.getPackageName()); } @Before public void prepareDatabase() {
appContext.getDatabasePath(DB_NAME).delete();
SecUSo/privacy-friendly-weather
app/src/androidTest/java/org/secuso/privacyfriendlyweather/database/DatabaseTest.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/data/City.java // @Entity(tableName = "CITIES", indices = {@Index(value = {"city_name", "cities_id"})}) // public class City { // // private static final String UNKNOWN_POSTAL_CODE_VALUE = "-"; // // @PrimaryKey @ColumnInfo(name = "cities_id") private int cityId; // @ColumnInfo(name = "city_name") @NonNull private String cityName = ""; // @ColumnInfo(name = "country_code") @NonNull private String countryCode = ""; // @ColumnInfo(name = "longitude") private float longitude; // @ColumnInfo(name = "latitude") private float latitude; // // public City() { } // // @Ignore public City(int cityId, @NonNull String cityName, @NonNull String countryCode, float lon, float lat) { // this.cityId = cityId; // this.cityName = cityName; // this.countryCode = countryCode; // this.longitude = lon; // this.latitude = lat; // } // // public int getCityId() { // return cityId; // } // // public void setCityId(int cityId) { // this.cityId = cityId; // } // // public @NonNull String getCityName() { // return cityName; // } // // public void setCityName(@NonNull String cityName) { // this.cityName = cityName; // } // // public @NonNull String getCountryCode() { // return countryCode; // } // // public void setCountryCode(@NonNull String countryCode) { // this.countryCode = countryCode; // } // // @Override // public @NonNull String toString() { // return String.format(Locale.ENGLISH, "%s, %s (%f - %f)", cityName, countryCode, longitude, latitude); // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public float getLatitude() { // return latitude; // } // // public float getLongitude() { // return longitude; // } // // public void setLongitude(float lon) { // this.longitude = lon; // } // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // public static final String DB_NAME = "PF_WEATHER_DB.db";
import android.content.Context; import androidx.room.Room; import androidx.room.testing.MigrationTestHelper; import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.secuso.privacyfriendlyweather.BuildConfig; import org.secuso.privacyfriendlyweather.database.data.City; import java.io.IOException; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.secuso.privacyfriendlyweather.database.AppDatabase.DB_NAME;
// init database dbHandler.getAllCitiesToWatch(); dbHandler.close(); // migration testHelper.runMigrationsAndValidate("PF_WEATHER_DB_4.db", AppDatabase.VERSION, true, AppDatabase.getMigrations(appContext)); AppDatabase appDatabase = Room.databaseBuilder(appContext, AppDatabase.class, "PF_WEATHER_DB_4.db").build(); // close the database and release any stream resources when the test finishes testHelper.closeWhenFinished(appDatabase); assertNotNull(appDatabase.cityToWatchDao().getAll()); assertNotNull(appDatabase.forecastDao().getAll()); assertNotNull(appDatabase.currentWeatherDao().getAll()); assertEquals(209579, appDatabase.cityDao().count()); // make sure all the cities are written correctly } @Test public void testRecommendationsTest() { AppDatabase appDatabase = getMigratedRoomDatabase(); // are all the cities in the database? assertEquals(209579, appDatabase.cityDao().count()); // get recommendations
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/data/City.java // @Entity(tableName = "CITIES", indices = {@Index(value = {"city_name", "cities_id"})}) // public class City { // // private static final String UNKNOWN_POSTAL_CODE_VALUE = "-"; // // @PrimaryKey @ColumnInfo(name = "cities_id") private int cityId; // @ColumnInfo(name = "city_name") @NonNull private String cityName = ""; // @ColumnInfo(name = "country_code") @NonNull private String countryCode = ""; // @ColumnInfo(name = "longitude") private float longitude; // @ColumnInfo(name = "latitude") private float latitude; // // public City() { } // // @Ignore public City(int cityId, @NonNull String cityName, @NonNull String countryCode, float lon, float lat) { // this.cityId = cityId; // this.cityName = cityName; // this.countryCode = countryCode; // this.longitude = lon; // this.latitude = lat; // } // // public int getCityId() { // return cityId; // } // // public void setCityId(int cityId) { // this.cityId = cityId; // } // // public @NonNull String getCityName() { // return cityName; // } // // public void setCityName(@NonNull String cityName) { // this.cityName = cityName; // } // // public @NonNull String getCountryCode() { // return countryCode; // } // // public void setCountryCode(@NonNull String countryCode) { // this.countryCode = countryCode; // } // // @Override // public @NonNull String toString() { // return String.format(Locale.ENGLISH, "%s, %s (%f - %f)", cityName, countryCode, longitude, latitude); // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public float getLatitude() { // return latitude; // } // // public float getLongitude() { // return longitude; // } // // public void setLongitude(float lon) { // this.longitude = lon; // } // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // public static final String DB_NAME = "PF_WEATHER_DB.db"; // Path: app/src/androidTest/java/org/secuso/privacyfriendlyweather/database/DatabaseTest.java import android.content.Context; import androidx.room.Room; import androidx.room.testing.MigrationTestHelper; import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.secuso.privacyfriendlyweather.BuildConfig; import org.secuso.privacyfriendlyweather.database.data.City; import java.io.IOException; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.secuso.privacyfriendlyweather.database.AppDatabase.DB_NAME; // init database dbHandler.getAllCitiesToWatch(); dbHandler.close(); // migration testHelper.runMigrationsAndValidate("PF_WEATHER_DB_4.db", AppDatabase.VERSION, true, AppDatabase.getMigrations(appContext)); AppDatabase appDatabase = Room.databaseBuilder(appContext, AppDatabase.class, "PF_WEATHER_DB_4.db").build(); // close the database and release any stream resources when the test finishes testHelper.closeWhenFinished(appDatabase); assertNotNull(appDatabase.cityToWatchDao().getAll()); assertNotNull(appDatabase.forecastDao().getAll()); assertNotNull(appDatabase.currentWeatherDao().getAll()); assertEquals(209579, appDatabase.cityDao().count()); // make sure all the cities are written correctly } @Test public void testRecommendationsTest() { AppDatabase appDatabase = getMigratedRoomDatabase(); // are all the cities in the database? assertEquals(209579, appDatabase.cityDao().count()); // get recommendations
List<City> possibleCities = appDatabase.cityDao().getCitiesWhereNameLike("Frankfurt", 10);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/database/dao/CityToWatchDao.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/data/CityToWatch.java // @SuppressWarnings({RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED, // RoomWarnings.MISSING_INDEX_ON_FOREIGN_KEY_CHILD, RoomWarnings.INDEX_FROM_EMBEDDED_ENTITY_IS_DROPPED}) // // /** // * This class is the database model for the cities to watch. 'Cities to watch' means the locations // * for which a user would like to see the weather for. This includes those locations that will be // * deleted after app close (non-persistent locations). // */ // @Entity(tableName = "CITIES_TO_WATCH", foreignKeys = { // @ForeignKey(entity = City.class, // parentColumns = {"cities_id"}, // childColumns = {"city_id"}, // onDelete = ForeignKey.CASCADE)}) // public class CityToWatch { // // @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "cities_to_watch_id") private int id = 0; // @ColumnInfo(name = "city_id") private int cityId; // @ColumnInfo(name = "rank") private int rank; // @Embedded private City city; // // public CityToWatch() { // this.city = new City(); // } // // @Ignore // public CityToWatch(int rank, String countryCode, int id, int cityId, String cityName, float longitude, float latitude) { // this.rank = rank; // this.id = id; // this.cityId = cityId; // this.city = new City(); // this.city.setCityName(cityName); // this.city.setCityId(cityId); // this.city.setCountryCode(countryCode); // this.city.setLongitude(longitude); // this.city.setLatitude(latitude); // } // // public City getCity() { // return city; // } // // public void setCity(City city) { // this.city = city; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public int getCityId() { // return cityId; // } // // public void setCityId(int cityId) { // this.cityId = cityId; // } // // public String getCityName() { // return city.getCityName(); // } // // public void setCityName(String cityName) { // this.city.setCityName(cityName); // } // // public String getCountryCode() { // return city.getCountryCode(); // } // // public void setCountryCode(String countryCode) { // this.city.setCountryCode(countryCode); // } // // public int getRank() { // return rank; // } // // public void setRank(int rank) { // this.rank = rank; // } // // public float getLongitude() { // return this.city.getLongitude(); // } // // public float getLatitude() { // return this.city.getLatitude(); // } // // public void setLongitude(float lon) { // this.city.setLongitude(lon); // } // // public void setLatitude(float lat) { // this.city.setLatitude(lat); // } // // }
import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import org.secuso.privacyfriendlyweather.database.data.CityToWatch; import java.util.List;
package org.secuso.privacyfriendlyweather.database.dao; /** * @author Christopher Beckmann */ @Dao public interface CityToWatchDao { @Query("SELECT * FROM CITIES_TO_WATCH")
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/data/CityToWatch.java // @SuppressWarnings({RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED, // RoomWarnings.MISSING_INDEX_ON_FOREIGN_KEY_CHILD, RoomWarnings.INDEX_FROM_EMBEDDED_ENTITY_IS_DROPPED}) // // /** // * This class is the database model for the cities to watch. 'Cities to watch' means the locations // * for which a user would like to see the weather for. This includes those locations that will be // * deleted after app close (non-persistent locations). // */ // @Entity(tableName = "CITIES_TO_WATCH", foreignKeys = { // @ForeignKey(entity = City.class, // parentColumns = {"cities_id"}, // childColumns = {"city_id"}, // onDelete = ForeignKey.CASCADE)}) // public class CityToWatch { // // @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "cities_to_watch_id") private int id = 0; // @ColumnInfo(name = "city_id") private int cityId; // @ColumnInfo(name = "rank") private int rank; // @Embedded private City city; // // public CityToWatch() { // this.city = new City(); // } // // @Ignore // public CityToWatch(int rank, String countryCode, int id, int cityId, String cityName, float longitude, float latitude) { // this.rank = rank; // this.id = id; // this.cityId = cityId; // this.city = new City(); // this.city.setCityName(cityName); // this.city.setCityId(cityId); // this.city.setCountryCode(countryCode); // this.city.setLongitude(longitude); // this.city.setLatitude(latitude); // } // // public City getCity() { // return city; // } // // public void setCity(City city) { // this.city = city; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public int getCityId() { // return cityId; // } // // public void setCityId(int cityId) { // this.cityId = cityId; // } // // public String getCityName() { // return city.getCityName(); // } // // public void setCityName(String cityName) { // this.city.setCityName(cityName); // } // // public String getCountryCode() { // return city.getCountryCode(); // } // // public void setCountryCode(String countryCode) { // this.city.setCountryCode(countryCode); // } // // public int getRank() { // return rank; // } // // public void setRank(int rank) { // this.rank = rank; // } // // public float getLongitude() { // return this.city.getLongitude(); // } // // public float getLatitude() { // return this.city.getLatitude(); // } // // public void setLongitude(float lon) { // this.city.setLongitude(lon); // } // // public void setLatitude(float lat) { // this.city.setLatitude(lat); // } // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/dao/CityToWatchDao.java import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import org.secuso.privacyfriendlyweather.database.data.CityToWatch; import java.util.List; package org.secuso.privacyfriendlyweather.database.dao; /** * @author Christopher Beckmann */ @Dao public interface CityToWatchDao { @Query("SELECT * FROM CITIES_TO_WATCH")
List<CityToWatch> getAll();
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/database/data/Forecast.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // @Database(entities = {City.class, CityToWatch.class, CurrentWeatherData.class, Forecast.class, WeekForecast.class}, version = AppDatabase.VERSION) // public abstract class AppDatabase extends RoomDatabase { // public static final String DB_NAME = "PF_WEATHER_DB.db"; // static final int VERSION = 7; // static final String TAG = AppDatabase.class.getSimpleName(); // // // DAOs // public abstract CityDao cityDao(); // public abstract CityToWatchDao cityToWatchDao(); // public abstract CurrentWeatherDao currentWeatherDao(); // // public abstract ForecastDao forecastDao(); // // public abstract WeekForecastDao weekForecastDao(); // // // INSTANCE // private static final Object databaseLock = new Object(); // private static volatile AppDatabase INSTANCE; // // /** // * Get list of all migrations. If they are ContextAwareMigrations, then inject the Context. // * @param context to be injected into the ContextAwareMigrations // * @return an array of Migrations, this can not be empty // */ // public static Migration[] getMigrations(Context context) { // Migration[] MIGRATIONS = new Migration[]{ // new Migration_1_2(), // new Migration_2_3(), // new Migration_3_4(), // new Migration_4_5(), // new Migration_5_6(), // new Migration_6_7() // // Add new migrations here // }; // // for(Migration m : MIGRATIONS) { // if(m instanceof ContextAwareMigration) { // ((ContextAwareMigration) m).injectContext(context); // } // } // return MIGRATIONS; // } // // public static AppDatabase getInstance(Context context) { // if(INSTANCE == null) { // synchronized (databaseLock) { // if(INSTANCE == null) { // INSTANCE = buildDatabase(context); // } // } // } // return INSTANCE; // } // // private static AppDatabase buildDatabase(final Context context) { // Migration[] MIGRATIONS = getMigrations(context); // // return Room.databaseBuilder(context, AppDatabase.class, DB_NAME) // .addMigrations(MIGRATIONS) // .addCallback(new Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // // // disable WAL because of the upcoming big transaction // db.setTransactionSuccessful(); // db.endTransaction(); // db.disableWriteAheadLogging(); // db.beginTransaction(); // // int cityCount = 0; // Cursor c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // // Log.d(TAG, "City count: " + cityCount); // if(cityCount == 0) { // fillCityDatabase(context, db); // } // // // TODO: DEBUG ONLY - REMOVE WHEN DONE // c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // Log.d(TAG, "City count: " + cityCount); // } // }) // .allowMainThreadQueries() // .fallbackToDestructiveMigration() // .build(); // } // // public static void fillCityDatabase(final Context context, SupportSQLiteDatabase database) { // long startInsertTime = System.currentTimeMillis(); // // InputStream inputStream = context.getResources().openRawResource(R.raw.city_list); // try { // FileReader fileReader = new FileReader(); // final List<City> cities = fileReader.readCitiesFromFile(inputStream); // // if (cities.size() > 0) { // for (City c : cities) { // ContentValues values = new ContentValues(); // values.put("cities_id", c.getCityId()); // values.put("city_name", c.getCityName()); // values.put("country_code", c.getCountryCode()); // values.put("longitude", c.getLongitude()); // values.put("latitude", c.getLatitude()); // database.insert("CITIES", SQLiteDatabase.CONFLICT_REPLACE, values); // } // } // // inputStream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // long endInsertTime = System.currentTimeMillis(); // Log.d("debug_info", "Time for insert:" + (endInsertTime - startInsertTime)); // } // }
import android.content.Context; import android.widget.Toast; import androidx.room.ColumnInfo; import androidx.room.Embedded; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.Ignore; import androidx.room.PrimaryKey; import androidx.room.RoomWarnings; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.database.AppDatabase;
public float getWindSpeed() { return windSpeed; } public void setWindSpeed(float speed) { windSpeed = speed; } /** * @return Returns the ID of the record (which uniquely identifies the record). */ public int getId() { return id; } public void setId(int id) { this.id = id; } /** * @return Returns the date and time for the forecast. */ public long getForecastTime() { return forecastTime; } /** * @return Returns the local time for the forecast in UTC epoch */ public long getLocalForecastTime(Context context) {
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // @Database(entities = {City.class, CityToWatch.class, CurrentWeatherData.class, Forecast.class, WeekForecast.class}, version = AppDatabase.VERSION) // public abstract class AppDatabase extends RoomDatabase { // public static final String DB_NAME = "PF_WEATHER_DB.db"; // static final int VERSION = 7; // static final String TAG = AppDatabase.class.getSimpleName(); // // // DAOs // public abstract CityDao cityDao(); // public abstract CityToWatchDao cityToWatchDao(); // public abstract CurrentWeatherDao currentWeatherDao(); // // public abstract ForecastDao forecastDao(); // // public abstract WeekForecastDao weekForecastDao(); // // // INSTANCE // private static final Object databaseLock = new Object(); // private static volatile AppDatabase INSTANCE; // // /** // * Get list of all migrations. If they are ContextAwareMigrations, then inject the Context. // * @param context to be injected into the ContextAwareMigrations // * @return an array of Migrations, this can not be empty // */ // public static Migration[] getMigrations(Context context) { // Migration[] MIGRATIONS = new Migration[]{ // new Migration_1_2(), // new Migration_2_3(), // new Migration_3_4(), // new Migration_4_5(), // new Migration_5_6(), // new Migration_6_7() // // Add new migrations here // }; // // for(Migration m : MIGRATIONS) { // if(m instanceof ContextAwareMigration) { // ((ContextAwareMigration) m).injectContext(context); // } // } // return MIGRATIONS; // } // // public static AppDatabase getInstance(Context context) { // if(INSTANCE == null) { // synchronized (databaseLock) { // if(INSTANCE == null) { // INSTANCE = buildDatabase(context); // } // } // } // return INSTANCE; // } // // private static AppDatabase buildDatabase(final Context context) { // Migration[] MIGRATIONS = getMigrations(context); // // return Room.databaseBuilder(context, AppDatabase.class, DB_NAME) // .addMigrations(MIGRATIONS) // .addCallback(new Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // // // disable WAL because of the upcoming big transaction // db.setTransactionSuccessful(); // db.endTransaction(); // db.disableWriteAheadLogging(); // db.beginTransaction(); // // int cityCount = 0; // Cursor c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // // Log.d(TAG, "City count: " + cityCount); // if(cityCount == 0) { // fillCityDatabase(context, db); // } // // // TODO: DEBUG ONLY - REMOVE WHEN DONE // c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // Log.d(TAG, "City count: " + cityCount); // } // }) // .allowMainThreadQueries() // .fallbackToDestructiveMigration() // .build(); // } // // public static void fillCityDatabase(final Context context, SupportSQLiteDatabase database) { // long startInsertTime = System.currentTimeMillis(); // // InputStream inputStream = context.getResources().openRawResource(R.raw.city_list); // try { // FileReader fileReader = new FileReader(); // final List<City> cities = fileReader.readCitiesFromFile(inputStream); // // if (cities.size() > 0) { // for (City c : cities) { // ContentValues values = new ContentValues(); // values.put("cities_id", c.getCityId()); // values.put("city_name", c.getCityName()); // values.put("country_code", c.getCountryCode()); // values.put("longitude", c.getLongitude()); // values.put("latitude", c.getLatitude()); // database.insert("CITIES", SQLiteDatabase.CONFLICT_REPLACE, values); // } // } // // inputStream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // long endInsertTime = System.currentTimeMillis(); // Log.d("debug_info", "Time for insert:" + (endInsertTime - startInsertTime)); // } // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/data/Forecast.java import android.content.Context; import android.widget.Toast; import androidx.room.ColumnInfo; import androidx.room.Embedded; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.Ignore; import androidx.room.PrimaryKey; import androidx.room.RoomWarnings; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.database.AppDatabase; public float getWindSpeed() { return windSpeed; } public void setWindSpeed(float speed) { windSpeed = speed; } /** * @return Returns the ID of the record (which uniquely identifies the record). */ public int getId() { return id; } public void setId(int id) { this.id = id; } /** * @return Returns the date and time for the forecast. */ public long getForecastTime() { return forecastTime; } /** * @return Returns the local time for the forecast in UTC epoch */ public long getLocalForecastTime(Context context) {
AppDatabase dbhelper = AppDatabase.getInstance(context);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IProcessHttpRequest.java // public interface IProcessHttpRequest { // // /** // * The method that will be executed in case of a successful HTTP request. // * // * @param response The response of the HTTP request. // */ // void processSuccessScenario(String response); // // /** // * This method will be executed in case any error arose while executing the HTTP request. // * // * @param error The error that occurred while executing the HTTP request. // */ // void processFailScenario(VolleyError error); // // }
import android.content.Context; import android.util.Log; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.secuso.privacyfriendlyweather.weather_api.IProcessHttpRequest; import java.io.BufferedInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory;
package org.secuso.privacyfriendlyweather.http; /** * This class implements the IHttpRequest interface. It provides HTTP requests by using Volley. * See: https://developer.android.com/training/volley/simple.html */ public class VolleyHttpRequest implements IHttpRequest { private Context context; /** * Constructor. * * @param context Volley needs a context "for creating the cache dir". * @see Volley#newRequestQueue(Context) */ public VolleyHttpRequest(Context context) { this.context = context; } /** * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) */ @Override
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IProcessHttpRequest.java // public interface IProcessHttpRequest { // // /** // * The method that will be executed in case of a successful HTTP request. // * // * @param response The response of the HTTP request. // */ // void processSuccessScenario(String response); // // /** // * This method will be executed in case any error arose while executing the HTTP request. // * // * @param error The error that occurred while executing the HTTP request. // */ // void processFailScenario(VolleyError error); // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java import android.content.Context; import android.util.Log; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.secuso.privacyfriendlyweather.weather_api.IProcessHttpRequest; import java.io.BufferedInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; package org.secuso.privacyfriendlyweather.http; /** * This class implements the IHttpRequest interface. It provides HTTP requests by using Volley. * See: https://developer.android.com/training/volley/simple.html */ public class VolleyHttpRequest implements IHttpRequest { private Context context; /** * Constructor. * * @param context Volley needs a context "for creating the cache dir". * @see Volley#newRequestQueue(Context) */ public VolleyHttpRequest(Context context) { this.context = context; } /** * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) */ @Override
public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) {
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/backup/BackupRestorer.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // @Database(entities = {City.class, CityToWatch.class, CurrentWeatherData.class, Forecast.class, WeekForecast.class}, version = AppDatabase.VERSION) // public abstract class AppDatabase extends RoomDatabase { // public static final String DB_NAME = "PF_WEATHER_DB.db"; // static final int VERSION = 7; // static final String TAG = AppDatabase.class.getSimpleName(); // // // DAOs // public abstract CityDao cityDao(); // public abstract CityToWatchDao cityToWatchDao(); // public abstract CurrentWeatherDao currentWeatherDao(); // // public abstract ForecastDao forecastDao(); // // public abstract WeekForecastDao weekForecastDao(); // // // INSTANCE // private static final Object databaseLock = new Object(); // private static volatile AppDatabase INSTANCE; // // /** // * Get list of all migrations. If they are ContextAwareMigrations, then inject the Context. // * @param context to be injected into the ContextAwareMigrations // * @return an array of Migrations, this can not be empty // */ // public static Migration[] getMigrations(Context context) { // Migration[] MIGRATIONS = new Migration[]{ // new Migration_1_2(), // new Migration_2_3(), // new Migration_3_4(), // new Migration_4_5(), // new Migration_5_6(), // new Migration_6_7() // // Add new migrations here // }; // // for(Migration m : MIGRATIONS) { // if(m instanceof ContextAwareMigration) { // ((ContextAwareMigration) m).injectContext(context); // } // } // return MIGRATIONS; // } // // public static AppDatabase getInstance(Context context) { // if(INSTANCE == null) { // synchronized (databaseLock) { // if(INSTANCE == null) { // INSTANCE = buildDatabase(context); // } // } // } // return INSTANCE; // } // // private static AppDatabase buildDatabase(final Context context) { // Migration[] MIGRATIONS = getMigrations(context); // // return Room.databaseBuilder(context, AppDatabase.class, DB_NAME) // .addMigrations(MIGRATIONS) // .addCallback(new Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // // // disable WAL because of the upcoming big transaction // db.setTransactionSuccessful(); // db.endTransaction(); // db.disableWriteAheadLogging(); // db.beginTransaction(); // // int cityCount = 0; // Cursor c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // // Log.d(TAG, "City count: " + cityCount); // if(cityCount == 0) { // fillCityDatabase(context, db); // } // // // TODO: DEBUG ONLY - REMOVE WHEN DONE // c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // Log.d(TAG, "City count: " + cityCount); // } // }) // .allowMainThreadQueries() // .fallbackToDestructiveMigration() // .build(); // } // // public static void fillCityDatabase(final Context context, SupportSQLiteDatabase database) { // long startInsertTime = System.currentTimeMillis(); // // InputStream inputStream = context.getResources().openRawResource(R.raw.city_list); // try { // FileReader fileReader = new FileReader(); // final List<City> cities = fileReader.readCitiesFromFile(inputStream); // // if (cities.size() > 0) { // for (City c : cities) { // ContentValues values = new ContentValues(); // values.put("cities_id", c.getCityId()); // values.put("city_name", c.getCityName()); // values.put("country_code", c.getCountryCode()); // values.put("longitude", c.getLongitude()); // values.put("latitude", c.getLatitude()); // database.insert("CITIES", SQLiteDatabase.CONFLICT_REPLACE, values); // } // } // // inputStream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // long endInsertTime = System.currentTimeMillis(); // Log.d("debug_info", "Time for insert:" + (endInsertTime - startInsertTime)); // } // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // public static final String DB_NAME = "PF_WEATHER_DB.db";
import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.preference.PreferenceManager; import android.util.JsonReader; import androidx.annotation.NonNull; import org.jetbrains.annotations.NotNull; import org.secuso.privacyfriendlybackup.api.backup.DatabaseUtil; import org.secuso.privacyfriendlybackup.api.pfa.IBackupRestorer; import org.secuso.privacyfriendlyweather.database.AppDatabase; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import static org.secuso.privacyfriendlyweather.database.AppDatabase.DB_NAME;
break; case "last_used_key": case "shared_calls_used": pref.edit().putInt(name, reader.nextInt()).apply(); break; case "shared_calls_count_start": pref.edit().putLong(name, reader.nextLong()).apply(); break; default: throw new RuntimeException("Unknown preference " + name); } } reader.endObject(); } private void readDatabase(JsonReader reader, Context context) throws IOException { reader.beginObject(); String n1 = reader.nextName(); if (!n1.equals("version")) { throw new RuntimeException("Unknown value " + n1); } int version = reader.nextInt(); String n2 = reader.nextName(); if (!n2.equals("content")) { throw new RuntimeException("Unknown value " + n2); }
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // @Database(entities = {City.class, CityToWatch.class, CurrentWeatherData.class, Forecast.class, WeekForecast.class}, version = AppDatabase.VERSION) // public abstract class AppDatabase extends RoomDatabase { // public static final String DB_NAME = "PF_WEATHER_DB.db"; // static final int VERSION = 7; // static final String TAG = AppDatabase.class.getSimpleName(); // // // DAOs // public abstract CityDao cityDao(); // public abstract CityToWatchDao cityToWatchDao(); // public abstract CurrentWeatherDao currentWeatherDao(); // // public abstract ForecastDao forecastDao(); // // public abstract WeekForecastDao weekForecastDao(); // // // INSTANCE // private static final Object databaseLock = new Object(); // private static volatile AppDatabase INSTANCE; // // /** // * Get list of all migrations. If they are ContextAwareMigrations, then inject the Context. // * @param context to be injected into the ContextAwareMigrations // * @return an array of Migrations, this can not be empty // */ // public static Migration[] getMigrations(Context context) { // Migration[] MIGRATIONS = new Migration[]{ // new Migration_1_2(), // new Migration_2_3(), // new Migration_3_4(), // new Migration_4_5(), // new Migration_5_6(), // new Migration_6_7() // // Add new migrations here // }; // // for(Migration m : MIGRATIONS) { // if(m instanceof ContextAwareMigration) { // ((ContextAwareMigration) m).injectContext(context); // } // } // return MIGRATIONS; // } // // public static AppDatabase getInstance(Context context) { // if(INSTANCE == null) { // synchronized (databaseLock) { // if(INSTANCE == null) { // INSTANCE = buildDatabase(context); // } // } // } // return INSTANCE; // } // // private static AppDatabase buildDatabase(final Context context) { // Migration[] MIGRATIONS = getMigrations(context); // // return Room.databaseBuilder(context, AppDatabase.class, DB_NAME) // .addMigrations(MIGRATIONS) // .addCallback(new Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // // // disable WAL because of the upcoming big transaction // db.setTransactionSuccessful(); // db.endTransaction(); // db.disableWriteAheadLogging(); // db.beginTransaction(); // // int cityCount = 0; // Cursor c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // // Log.d(TAG, "City count: " + cityCount); // if(cityCount == 0) { // fillCityDatabase(context, db); // } // // // TODO: DEBUG ONLY - REMOVE WHEN DONE // c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // Log.d(TAG, "City count: " + cityCount); // } // }) // .allowMainThreadQueries() // .fallbackToDestructiveMigration() // .build(); // } // // public static void fillCityDatabase(final Context context, SupportSQLiteDatabase database) { // long startInsertTime = System.currentTimeMillis(); // // InputStream inputStream = context.getResources().openRawResource(R.raw.city_list); // try { // FileReader fileReader = new FileReader(); // final List<City> cities = fileReader.readCitiesFromFile(inputStream); // // if (cities.size() > 0) { // for (City c : cities) { // ContentValues values = new ContentValues(); // values.put("cities_id", c.getCityId()); // values.put("city_name", c.getCityName()); // values.put("country_code", c.getCountryCode()); // values.put("longitude", c.getLongitude()); // values.put("latitude", c.getLatitude()); // database.insert("CITIES", SQLiteDatabase.CONFLICT_REPLACE, values); // } // } // // inputStream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // long endInsertTime = System.currentTimeMillis(); // Log.d("debug_info", "Time for insert:" + (endInsertTime - startInsertTime)); // } // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // public static final String DB_NAME = "PF_WEATHER_DB.db"; // Path: app/src/main/java/org/secuso/privacyfriendlyweather/backup/BackupRestorer.java import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.preference.PreferenceManager; import android.util.JsonReader; import androidx.annotation.NonNull; import org.jetbrains.annotations.NotNull; import org.secuso.privacyfriendlybackup.api.backup.DatabaseUtil; import org.secuso.privacyfriendlybackup.api.pfa.IBackupRestorer; import org.secuso.privacyfriendlyweather.database.AppDatabase; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import static org.secuso.privacyfriendlyweather.database.AppDatabase.DB_NAME; break; case "last_used_key": case "shared_calls_used": pref.edit().putInt(name, reader.nextInt()).apply(); break; case "shared_calls_count_start": pref.edit().putLong(name, reader.nextLong()).apply(); break; default: throw new RuntimeException("Unknown preference " + name); } } reader.endObject(); } private void readDatabase(JsonReader reader, Context context) throws IOException { reader.beginObject(); String n1 = reader.nextName(); if (!n1.equals("version")) { throw new RuntimeException("Unknown value " + n1); } int version = reader.nextInt(); String n2 = reader.nextName(); if (!n2.equals("content")) { throw new RuntimeException("Unknown value " + n2); }
AppDatabase database = AppDatabase.getInstance(context);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/backup/BackupCreator.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // public static final String DB_NAME = "PF_WEATHER_DB.db";
import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.preference.PreferenceManager; import android.util.JsonWriter; import android.util.Log; import org.jetbrains.annotations.NotNull; import org.secuso.privacyfriendlybackup.api.backup.DatabaseUtil; import org.secuso.privacyfriendlybackup.api.backup.PreferenceUtil; import org.secuso.privacyfriendlybackup.api.pfa.IBackupCreator; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.List; import kotlin.Pair; import static java.nio.charset.StandardCharsets.UTF_8; import static org.secuso.privacyfriendlyweather.database.AppDatabase.DB_NAME;
package org.secuso.privacyfriendlyweather.backup; public class BackupCreator implements IBackupCreator { @Override public void writeBackup(@NotNull Context context, @NotNull OutputStream outputStream) { // lock application, so no changes can be made as long as this backup is created // depending on the size of the application - this could take a bit Log.d("PFA BackupCreator", "createBackup() started"); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, Charset.forName("UTF-8")); JsonWriter writer = new JsonWriter(outputStreamWriter); writer.setIndent(""); try { writer.beginObject();
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // public static final String DB_NAME = "PF_WEATHER_DB.db"; // Path: app/src/main/java/org/secuso/privacyfriendlyweather/backup/BackupCreator.java import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.preference.PreferenceManager; import android.util.JsonWriter; import android.util.Log; import org.jetbrains.annotations.NotNull; import org.secuso.privacyfriendlybackup.api.backup.DatabaseUtil; import org.secuso.privacyfriendlybackup.api.backup.PreferenceUtil; import org.secuso.privacyfriendlybackup.api.pfa.IBackupCreator; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.List; import kotlin.Pair; import static java.nio.charset.StandardCharsets.UTF_8; import static org.secuso.privacyfriendlyweather.database.AppDatabase.DB_NAME; package org.secuso.privacyfriendlyweather.backup; public class BackupCreator implements IBackupCreator { @Override public void writeBackup(@NotNull Context context, @NotNull OutputStream outputStream) { // lock application, so no changes can be made as long as this backup is created // depending on the size of the application - this could take a bit Log.d("PFA BackupCreator", "createBackup() started"); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, Charset.forName("UTF-8")); JsonWriter writer = new JsonWriter(outputStreamWriter); writer.setIndent(""); try { writer.beginObject();
SQLiteDatabase dataBase = SQLiteDatabase.openDatabase(context.getDatabasePath(DB_NAME).getPath(), null, SQLiteDatabase.OPEN_READONLY);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/database/data/WeekForecast.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // @Database(entities = {City.class, CityToWatch.class, CurrentWeatherData.class, Forecast.class, WeekForecast.class}, version = AppDatabase.VERSION) // public abstract class AppDatabase extends RoomDatabase { // public static final String DB_NAME = "PF_WEATHER_DB.db"; // static final int VERSION = 7; // static final String TAG = AppDatabase.class.getSimpleName(); // // // DAOs // public abstract CityDao cityDao(); // public abstract CityToWatchDao cityToWatchDao(); // public abstract CurrentWeatherDao currentWeatherDao(); // // public abstract ForecastDao forecastDao(); // // public abstract WeekForecastDao weekForecastDao(); // // // INSTANCE // private static final Object databaseLock = new Object(); // private static volatile AppDatabase INSTANCE; // // /** // * Get list of all migrations. If they are ContextAwareMigrations, then inject the Context. // * @param context to be injected into the ContextAwareMigrations // * @return an array of Migrations, this can not be empty // */ // public static Migration[] getMigrations(Context context) { // Migration[] MIGRATIONS = new Migration[]{ // new Migration_1_2(), // new Migration_2_3(), // new Migration_3_4(), // new Migration_4_5(), // new Migration_5_6(), // new Migration_6_7() // // Add new migrations here // }; // // for(Migration m : MIGRATIONS) { // if(m instanceof ContextAwareMigration) { // ((ContextAwareMigration) m).injectContext(context); // } // } // return MIGRATIONS; // } // // public static AppDatabase getInstance(Context context) { // if(INSTANCE == null) { // synchronized (databaseLock) { // if(INSTANCE == null) { // INSTANCE = buildDatabase(context); // } // } // } // return INSTANCE; // } // // private static AppDatabase buildDatabase(final Context context) { // Migration[] MIGRATIONS = getMigrations(context); // // return Room.databaseBuilder(context, AppDatabase.class, DB_NAME) // .addMigrations(MIGRATIONS) // .addCallback(new Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // // // disable WAL because of the upcoming big transaction // db.setTransactionSuccessful(); // db.endTransaction(); // db.disableWriteAheadLogging(); // db.beginTransaction(); // // int cityCount = 0; // Cursor c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // // Log.d(TAG, "City count: " + cityCount); // if(cityCount == 0) { // fillCityDatabase(context, db); // } // // // TODO: DEBUG ONLY - REMOVE WHEN DONE // c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // Log.d(TAG, "City count: " + cityCount); // } // }) // .allowMainThreadQueries() // .fallbackToDestructiveMigration() // .build(); // } // // public static void fillCityDatabase(final Context context, SupportSQLiteDatabase database) { // long startInsertTime = System.currentTimeMillis(); // // InputStream inputStream = context.getResources().openRawResource(R.raw.city_list); // try { // FileReader fileReader = new FileReader(); // final List<City> cities = fileReader.readCitiesFromFile(inputStream); // // if (cities.size() > 0) { // for (City c : cities) { // ContentValues values = new ContentValues(); // values.put("cities_id", c.getCityId()); // values.put("city_name", c.getCityName()); // values.put("country_code", c.getCountryCode()); // values.put("longitude", c.getLongitude()); // values.put("latitude", c.getLatitude()); // database.insert("CITIES", SQLiteDatabase.CONFLICT_REPLACE, values); // } // } // // inputStream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // long endInsertTime = System.currentTimeMillis(); // Log.d("debug_info", "Time for insert:" + (endInsertTime - startInsertTime)); // } // }
import android.content.Context; import androidx.room.ColumnInfo; import androidx.room.Embedded; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.Ignore; import androidx.room.PrimaryKey; import androidx.room.RoomWarnings; import org.secuso.privacyfriendlyweather.database.AppDatabase;
this.precipitation = precipitation; this.wind_speed = wind_speed; this.wind_direction = wind_direction; this.uv_index = uv_index; this.rain_probability = rain_probability; } /** * @return Returns the ID of the record (which uniquely identifies the record). */ public int getId() { return id; } public void setId(int id) { this.id = id; } /** * @return Returns the date and time for the forecast. */ public long getForecastTime() { return forecastTime; } /** * @return Returns the local time for the forecast in UTC epoch */ public long getLocalForecastTime(Context context) {
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // @Database(entities = {City.class, CityToWatch.class, CurrentWeatherData.class, Forecast.class, WeekForecast.class}, version = AppDatabase.VERSION) // public abstract class AppDatabase extends RoomDatabase { // public static final String DB_NAME = "PF_WEATHER_DB.db"; // static final int VERSION = 7; // static final String TAG = AppDatabase.class.getSimpleName(); // // // DAOs // public abstract CityDao cityDao(); // public abstract CityToWatchDao cityToWatchDao(); // public abstract CurrentWeatherDao currentWeatherDao(); // // public abstract ForecastDao forecastDao(); // // public abstract WeekForecastDao weekForecastDao(); // // // INSTANCE // private static final Object databaseLock = new Object(); // private static volatile AppDatabase INSTANCE; // // /** // * Get list of all migrations. If they are ContextAwareMigrations, then inject the Context. // * @param context to be injected into the ContextAwareMigrations // * @return an array of Migrations, this can not be empty // */ // public static Migration[] getMigrations(Context context) { // Migration[] MIGRATIONS = new Migration[]{ // new Migration_1_2(), // new Migration_2_3(), // new Migration_3_4(), // new Migration_4_5(), // new Migration_5_6(), // new Migration_6_7() // // Add new migrations here // }; // // for(Migration m : MIGRATIONS) { // if(m instanceof ContextAwareMigration) { // ((ContextAwareMigration) m).injectContext(context); // } // } // return MIGRATIONS; // } // // public static AppDatabase getInstance(Context context) { // if(INSTANCE == null) { // synchronized (databaseLock) { // if(INSTANCE == null) { // INSTANCE = buildDatabase(context); // } // } // } // return INSTANCE; // } // // private static AppDatabase buildDatabase(final Context context) { // Migration[] MIGRATIONS = getMigrations(context); // // return Room.databaseBuilder(context, AppDatabase.class, DB_NAME) // .addMigrations(MIGRATIONS) // .addCallback(new Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // // // disable WAL because of the upcoming big transaction // db.setTransactionSuccessful(); // db.endTransaction(); // db.disableWriteAheadLogging(); // db.beginTransaction(); // // int cityCount = 0; // Cursor c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // // Log.d(TAG, "City count: " + cityCount); // if(cityCount == 0) { // fillCityDatabase(context, db); // } // // // TODO: DEBUG ONLY - REMOVE WHEN DONE // c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // Log.d(TAG, "City count: " + cityCount); // } // }) // .allowMainThreadQueries() // .fallbackToDestructiveMigration() // .build(); // } // // public static void fillCityDatabase(final Context context, SupportSQLiteDatabase database) { // long startInsertTime = System.currentTimeMillis(); // // InputStream inputStream = context.getResources().openRawResource(R.raw.city_list); // try { // FileReader fileReader = new FileReader(); // final List<City> cities = fileReader.readCitiesFromFile(inputStream); // // if (cities.size() > 0) { // for (City c : cities) { // ContentValues values = new ContentValues(); // values.put("cities_id", c.getCityId()); // values.put("city_name", c.getCityName()); // values.put("country_code", c.getCountryCode()); // values.put("longitude", c.getLongitude()); // values.put("latitude", c.getLatitude()); // database.insert("CITIES", SQLiteDatabase.CONFLICT_REPLACE, values); // } // } // // inputStream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // long endInsertTime = System.currentTimeMillis(); // Log.d("debug_info", "Time for insert:" + (endInsertTime - startInsertTime)); // } // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/data/WeekForecast.java import android.content.Context; import androidx.room.ColumnInfo; import androidx.room.Embedded; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.Ignore; import androidx.room.PrimaryKey; import androidx.room.RoomWarnings; import org.secuso.privacyfriendlyweather.database.AppDatabase; this.precipitation = precipitation; this.wind_speed = wind_speed; this.wind_direction = wind_direction; this.uv_index = uv_index; this.rain_probability = rain_probability; } /** * @return Returns the ID of the record (which uniquely identifies the record). */ public int getId() { return id; } public void setId(int id) { this.id = id; } /** * @return Returns the date and time for the forecast. */ public long getForecastTime() { return forecastTime; } /** * @return Returns the local time for the forecast in UTC epoch */ public long getLocalForecastTime(Context context) {
AppDatabase dbhelper = AppDatabase.getInstance(context);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/database/migration/Migration_4_5.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // @Database(entities = {City.class, CityToWatch.class, CurrentWeatherData.class, Forecast.class, WeekForecast.class}, version = AppDatabase.VERSION) // public abstract class AppDatabase extends RoomDatabase { // public static final String DB_NAME = "PF_WEATHER_DB.db"; // static final int VERSION = 7; // static final String TAG = AppDatabase.class.getSimpleName(); // // // DAOs // public abstract CityDao cityDao(); // public abstract CityToWatchDao cityToWatchDao(); // public abstract CurrentWeatherDao currentWeatherDao(); // // public abstract ForecastDao forecastDao(); // // public abstract WeekForecastDao weekForecastDao(); // // // INSTANCE // private static final Object databaseLock = new Object(); // private static volatile AppDatabase INSTANCE; // // /** // * Get list of all migrations. If they are ContextAwareMigrations, then inject the Context. // * @param context to be injected into the ContextAwareMigrations // * @return an array of Migrations, this can not be empty // */ // public static Migration[] getMigrations(Context context) { // Migration[] MIGRATIONS = new Migration[]{ // new Migration_1_2(), // new Migration_2_3(), // new Migration_3_4(), // new Migration_4_5(), // new Migration_5_6(), // new Migration_6_7() // // Add new migrations here // }; // // for(Migration m : MIGRATIONS) { // if(m instanceof ContextAwareMigration) { // ((ContextAwareMigration) m).injectContext(context); // } // } // return MIGRATIONS; // } // // public static AppDatabase getInstance(Context context) { // if(INSTANCE == null) { // synchronized (databaseLock) { // if(INSTANCE == null) { // INSTANCE = buildDatabase(context); // } // } // } // return INSTANCE; // } // // private static AppDatabase buildDatabase(final Context context) { // Migration[] MIGRATIONS = getMigrations(context); // // return Room.databaseBuilder(context, AppDatabase.class, DB_NAME) // .addMigrations(MIGRATIONS) // .addCallback(new Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // // // disable WAL because of the upcoming big transaction // db.setTransactionSuccessful(); // db.endTransaction(); // db.disableWriteAheadLogging(); // db.beginTransaction(); // // int cityCount = 0; // Cursor c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // // Log.d(TAG, "City count: " + cityCount); // if(cityCount == 0) { // fillCityDatabase(context, db); // } // // // TODO: DEBUG ONLY - REMOVE WHEN DONE // c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // Log.d(TAG, "City count: " + cityCount); // } // }) // .allowMainThreadQueries() // .fallbackToDestructiveMigration() // .build(); // } // // public static void fillCityDatabase(final Context context, SupportSQLiteDatabase database) { // long startInsertTime = System.currentTimeMillis(); // // InputStream inputStream = context.getResources().openRawResource(R.raw.city_list); // try { // FileReader fileReader = new FileReader(); // final List<City> cities = fileReader.readCitiesFromFile(inputStream); // // if (cities.size() > 0) { // for (City c : cities) { // ContentValues values = new ContentValues(); // values.put("cities_id", c.getCityId()); // values.put("city_name", c.getCityName()); // values.put("country_code", c.getCountryCode()); // values.put("longitude", c.getLongitude()); // values.put("latitude", c.getLatitude()); // database.insert("CITIES", SQLiteDatabase.CONFLICT_REPLACE, values); // } // } // // inputStream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // long endInsertTime = System.currentTimeMillis(); // Log.d("debug_info", "Time for insert:" + (endInsertTime - startInsertTime)); // } // }
import android.content.Context; import androidx.annotation.NonNull; import androidx.sqlite.db.SupportSQLiteDatabase; import org.secuso.privacyfriendlyweather.database.AppDatabase;
package org.secuso.privacyfriendlyweather.database.migration; /** * Migration from version 4 to 5. This is the migration from regular SQLite to Room. * That is why a lot of changes had to be done here. Some tables had wrong entry types and the city list was updated. * Because this was the case for every table, each one is rebuilt completely and repopulated with the old data. * This migration needs a {@link Context} because it needs to populate the city table from a file. * * @see org.secuso.privacyfriendlyweather.database.migration.ContextAwareMigration * * @author Christopher Beckmann * */ public class Migration_4_5 extends ContextAwareMigration { public Migration_4_5() { super(4, 5); } @Override public void migrate(@NonNull Context context, @NonNull SupportSQLiteDatabase database) { // Cities database.execSQL("DROP TABLE CITIES;"); database.execSQL("CREATE TABLE IF NOT EXISTS CITIES (" + "cities_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + "city_name TEXT NOT NULL," + "country_code TEXT NOT NULL," + "longitude REAL NOT NULL," + "latitude REAL NOT NULL);");
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/AppDatabase.java // @Database(entities = {City.class, CityToWatch.class, CurrentWeatherData.class, Forecast.class, WeekForecast.class}, version = AppDatabase.VERSION) // public abstract class AppDatabase extends RoomDatabase { // public static final String DB_NAME = "PF_WEATHER_DB.db"; // static final int VERSION = 7; // static final String TAG = AppDatabase.class.getSimpleName(); // // // DAOs // public abstract CityDao cityDao(); // public abstract CityToWatchDao cityToWatchDao(); // public abstract CurrentWeatherDao currentWeatherDao(); // // public abstract ForecastDao forecastDao(); // // public abstract WeekForecastDao weekForecastDao(); // // // INSTANCE // private static final Object databaseLock = new Object(); // private static volatile AppDatabase INSTANCE; // // /** // * Get list of all migrations. If they are ContextAwareMigrations, then inject the Context. // * @param context to be injected into the ContextAwareMigrations // * @return an array of Migrations, this can not be empty // */ // public static Migration[] getMigrations(Context context) { // Migration[] MIGRATIONS = new Migration[]{ // new Migration_1_2(), // new Migration_2_3(), // new Migration_3_4(), // new Migration_4_5(), // new Migration_5_6(), // new Migration_6_7() // // Add new migrations here // }; // // for(Migration m : MIGRATIONS) { // if(m instanceof ContextAwareMigration) { // ((ContextAwareMigration) m).injectContext(context); // } // } // return MIGRATIONS; // } // // public static AppDatabase getInstance(Context context) { // if(INSTANCE == null) { // synchronized (databaseLock) { // if(INSTANCE == null) { // INSTANCE = buildDatabase(context); // } // } // } // return INSTANCE; // } // // private static AppDatabase buildDatabase(final Context context) { // Migration[] MIGRATIONS = getMigrations(context); // // return Room.databaseBuilder(context, AppDatabase.class, DB_NAME) // .addMigrations(MIGRATIONS) // .addCallback(new Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // // // disable WAL because of the upcoming big transaction // db.setTransactionSuccessful(); // db.endTransaction(); // db.disableWriteAheadLogging(); // db.beginTransaction(); // // int cityCount = 0; // Cursor c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // // Log.d(TAG, "City count: " + cityCount); // if(cityCount == 0) { // fillCityDatabase(context, db); // } // // // TODO: DEBUG ONLY - REMOVE WHEN DONE // c = db.query("SELECT count(*) FROM CITIES"); // if(c != null) { // if(c.moveToFirst()) { // cityCount = c.getInt(c.getColumnIndex("count(*)")); // } // c.close(); // } // Log.d(TAG, "City count: " + cityCount); // } // }) // .allowMainThreadQueries() // .fallbackToDestructiveMigration() // .build(); // } // // public static void fillCityDatabase(final Context context, SupportSQLiteDatabase database) { // long startInsertTime = System.currentTimeMillis(); // // InputStream inputStream = context.getResources().openRawResource(R.raw.city_list); // try { // FileReader fileReader = new FileReader(); // final List<City> cities = fileReader.readCitiesFromFile(inputStream); // // if (cities.size() > 0) { // for (City c : cities) { // ContentValues values = new ContentValues(); // values.put("cities_id", c.getCityId()); // values.put("city_name", c.getCityName()); // values.put("country_code", c.getCountryCode()); // values.put("longitude", c.getLongitude()); // values.put("latitude", c.getLatitude()); // database.insert("CITIES", SQLiteDatabase.CONFLICT_REPLACE, values); // } // } // // inputStream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // long endInsertTime = System.currentTimeMillis(); // Log.d("debug_info", "Time for insert:" + (endInsertTime - startInsertTime)); // } // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/migration/Migration_4_5.java import android.content.Context; import androidx.annotation.NonNull; import androidx.sqlite.db.SupportSQLiteDatabase; import org.secuso.privacyfriendlyweather.database.AppDatabase; package org.secuso.privacyfriendlyweather.database.migration; /** * Migration from version 4 to 5. This is the migration from regular SQLite to Room. * That is why a lot of changes had to be done here. Some tables had wrong entry types and the city list was updated. * Because this was the case for every table, each one is rebuilt completely and repopulated with the old data. * This migration needs a {@link Context} because it needs to populate the city table from a file. * * @see org.secuso.privacyfriendlyweather.database.migration.ContextAwareMigration * * @author Christopher Beckmann * */ public class Migration_4_5 extends ContextAwareMigration { public Migration_4_5() { super(4, 5); } @Override public void migrate(@NonNull Context context, @NonNull SupportSQLiteDatabase database) { // Cities database.execSQL("DROP TABLE CITIES;"); database.execSQL("CREATE TABLE IF NOT EXISTS CITIES (" + "cities_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + "city_name TEXT NOT NULL," + "country_code TEXT NOT NULL," + "longitude REAL NOT NULL," + "latitude REAL NOT NULL);");
AppDatabase.fillCityDatabase(context, database);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForRadiusSearch.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForRadiusSearch.java // public interface IHttpRequestForRadiusSearch { // // /** // * @param cityId The ID of the cityId to get the best weather locations around. // * @param edgeLength Determines the edge length of the square. The given cityId will be exactly // * the center of the square. // * @param resultCount Determines how many records shall be finally displayed in the UI. // */ // void perform(int cityId, int edgeLength, int resultCount); // // }
import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForRadiusSearch;
package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * Implementation for the OpenWeatherMap API. */ public class OwmHttpRequestForRadiusSearch extends OwmHttpRequest implements IHttpRequestForRadiusSearch { /** * Member variables */ private Context context; /** * Constructor. * * @param context The context to use. */ public OwmHttpRequestForRadiusSearch(Context context) { this.context = context; } @Override public void perform(int cityId, int edgeLength, int resultCount) { // First, retrieve the city from OWM to have the latitude and longitude for the city
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForRadiusSearch.java // public interface IHttpRequestForRadiusSearch { // // /** // * @param cityId The ID of the cityId to get the best weather locations around. // * @param edgeLength Determines the edge length of the square. The given cityId will be exactly // * the center of the square. // * @param resultCount Determines how many records shall be finally displayed in the UI. // */ // void perform(int cityId, int edgeLength, int resultCount); // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForRadiusSearch.java import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForRadiusSearch; package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * Implementation for the OpenWeatherMap API. */ public class OwmHttpRequestForRadiusSearch extends OwmHttpRequest implements IHttpRequestForRadiusSearch { /** * Member variables */ private Context context; /** * Constructor. * * @param context The context to use. */ public OwmHttpRequestForRadiusSearch(Context context) { this.context = context; } @Override public void perform(int cityId, int edgeLength, int resultCount) { // First, retrieve the city from OWM to have the latitude and longitude for the city
IHttpRequest httpRequest = new VolleyHttpRequest(context);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForRadiusSearch.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForRadiusSearch.java // public interface IHttpRequestForRadiusSearch { // // /** // * @param cityId The ID of the cityId to get the best weather locations around. // * @param edgeLength Determines the edge length of the square. The given cityId will be exactly // * the center of the square. // * @param resultCount Determines how many records shall be finally displayed in the UI. // */ // void perform(int cityId, int edgeLength, int resultCount); // // }
import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForRadiusSearch;
package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * Implementation for the OpenWeatherMap API. */ public class OwmHttpRequestForRadiusSearch extends OwmHttpRequest implements IHttpRequestForRadiusSearch { /** * Member variables */ private Context context; /** * Constructor. * * @param context The context to use. */ public OwmHttpRequestForRadiusSearch(Context context) { this.context = context; } @Override public void perform(int cityId, int edgeLength, int resultCount) { // First, retrieve the city from OWM to have the latitude and longitude for the city
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForRadiusSearch.java // public interface IHttpRequestForRadiusSearch { // // /** // * @param cityId The ID of the cityId to get the best weather locations around. // * @param edgeLength Determines the edge length of the square. The given cityId will be exactly // * the center of the square. // * @param resultCount Determines how many records shall be finally displayed in the UI. // */ // void perform(int cityId, int edgeLength, int resultCount); // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForRadiusSearch.java import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForRadiusSearch; package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * Implementation for the OpenWeatherMap API. */ public class OwmHttpRequestForRadiusSearch extends OwmHttpRequest implements IHttpRequestForRadiusSearch { /** * Member variables */ private Context context; /** * Constructor. * * @param context The context to use. */ public OwmHttpRequestForRadiusSearch(Context context) { this.context = context; } @Override public void perform(int cityId, int edgeLength, int resultCount) { // First, retrieve the city from OWM to have the latitude and longitude for the city
IHttpRequest httpRequest = new VolleyHttpRequest(context);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/preferences/AppPreferencesManager.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/ui/Help/StringFormatUtils.java // public final class StringFormatUtils { // // private static DecimalFormat decimalFormat = new DecimalFormat("0.0"); // private static DecimalFormat intFormat = new DecimalFormat("0"); // // public static String formatDecimal(float decimal) { // return decimalFormat.format(decimal); // } // // public static String formatInt(float decimal) { // return intFormat.format(decimal); // } // // public static String formatInt(float decimal, String appendix) { // return String.format("%s\u200a%s", formatInt(decimal), appendix); //\u200a adds tiny space // } // // public static String formatDecimal(float decimal, String appendix) { // return String.format("%s\u200a%s", formatDecimal(decimal), appendix); // } // // public static String formatTemperature(Context context, float temperature) { // AppPreferencesManager prefManager = new AppPreferencesManager(PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext())); // return formatDecimal(prefManager.convertTemperatureFromCelsius(temperature), prefManager.getWeatherUnit()); // } // // public static String formatTimeWithoutZone(long time) { // SimpleDateFormat df = new SimpleDateFormat("HH:mm", Locale.getDefault()); // df.setTimeZone(TimeZone.getTimeZone("GMT")); // return df.format(time); // } // // public static String formatWindToBeaufort(float wind_speed) { // if (wind_speed < 0.3) { // return formatInt(0, "Bft"); // Calm // } else if (wind_speed < 1.5) { // return formatInt(1, "Bft"); // Light air // } else if (wind_speed < 3.3) { // return formatInt(2, "Bft"); // Light breeze // } else if (wind_speed < 5.5) { // return formatInt(3, "Bft"); // Gentle breeze // } else if (wind_speed < 7.9) { // return formatInt(4, "Bft"); // Moderate breeze // } else if (wind_speed < 10.7) { // return formatInt(5, "Bft"); // Fresh breeze // } else if (wind_speed < 13.8) { // return formatInt(6, "Bft"); // Strong breeze // } else if (wind_speed < 17.1) { // return formatInt(7, "Bft"); // High wind // } else if (wind_speed < 20.7) { // return formatInt(8, "Bft"); // Gale // } else if (wind_speed < 24.4) { // return formatInt(9, "Bft"); // Strong gale // } else if (wind_speed < 28.4) { // return formatInt(10, "Bft"); // Storm // } else if (wind_speed < 32.6) { // return formatInt(11, "Bft"); // Violent storm // } else { // return formatInt(12, "Bft"); // Hurricane // } // } // // // public static String formatWindDir(Context context, float wind_direction) { // if (wind_direction < 22.5) { // return Character.toString((char) 0x2193); // North // } else if (wind_direction < 67.5) { // return Character.toString((char) 0x2199); // North East // } else if (wind_direction < 112.5) { // return Character.toString((char) 0x2190); // East // } else if (wind_direction < 157.5) { // return Character.toString((char) 0x2196); // South East // } else if (wind_direction < 202.5) { // return Character.toString((char) 0x2191); // South // } else if (wind_direction < 247.5) { // return Character.toString((char) 0x2197); // South West // } else if (wind_direction < 292.5) { // return Character.toString((char) 0x2192); // West // } else if (wind_direction < 337.5) { // return Character.toString((char) 0x2198); // North West // } else { // return Character.toString((char) 0x2193); // North // } // } // // public static Integer getDay(int day) { // // switch (day) { // case Calendar.MONDAY: // day = R.string.abbreviation_monday; // break; // case Calendar.TUESDAY: // day = R.string.abbreviation_tuesday; // break; // case Calendar.WEDNESDAY: // day = R.string.abbreviation_wednesday; // break; // case Calendar.THURSDAY: // day = R.string.abbreviation_thursday; // break; // case Calendar.FRIDAY: // day = R.string.abbreviation_friday; // break; // case Calendar.SATURDAY: // day = R.string.abbreviation_saturday; // break; // case Calendar.SUNDAY: // day = R.string.abbreviation_sunday; // break; // default: // day = R.string.abbreviation_monday; // } // return day; // } // }
import android.content.Context; import android.content.SharedPreferences; import androidx.appcompat.app.AppCompatDelegate; import org.secuso.privacyfriendlyweather.BuildConfig; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.ui.Help.StringFormatUtils;
break; case 3: AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); break; } } /** * @return Returns speed unit abbreviations */ public String getSpeedUnit() { int prefValue = Integer.parseInt(preferences.getString("speedUnit", "6")); if (prefValue == 1) { return "km/h"; } else if (prefValue == 2) { return "m/s"; } else if (prefValue == 3) { return "mph"; } else if (prefValue == 4) { return "ft/s"; } else if (prefValue == 5) { return "kn"; } else { return "Bft"; } } public String convertToCurrentSpeedUnit(float speedInMetersPerSecond) { int prefValue = Integer.parseInt(preferences.getString("speedUnit", "6")); if (prefValue == 1) {
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/ui/Help/StringFormatUtils.java // public final class StringFormatUtils { // // private static DecimalFormat decimalFormat = new DecimalFormat("0.0"); // private static DecimalFormat intFormat = new DecimalFormat("0"); // // public static String formatDecimal(float decimal) { // return decimalFormat.format(decimal); // } // // public static String formatInt(float decimal) { // return intFormat.format(decimal); // } // // public static String formatInt(float decimal, String appendix) { // return String.format("%s\u200a%s", formatInt(decimal), appendix); //\u200a adds tiny space // } // // public static String formatDecimal(float decimal, String appendix) { // return String.format("%s\u200a%s", formatDecimal(decimal), appendix); // } // // public static String formatTemperature(Context context, float temperature) { // AppPreferencesManager prefManager = new AppPreferencesManager(PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext())); // return formatDecimal(prefManager.convertTemperatureFromCelsius(temperature), prefManager.getWeatherUnit()); // } // // public static String formatTimeWithoutZone(long time) { // SimpleDateFormat df = new SimpleDateFormat("HH:mm", Locale.getDefault()); // df.setTimeZone(TimeZone.getTimeZone("GMT")); // return df.format(time); // } // // public static String formatWindToBeaufort(float wind_speed) { // if (wind_speed < 0.3) { // return formatInt(0, "Bft"); // Calm // } else if (wind_speed < 1.5) { // return formatInt(1, "Bft"); // Light air // } else if (wind_speed < 3.3) { // return formatInt(2, "Bft"); // Light breeze // } else if (wind_speed < 5.5) { // return formatInt(3, "Bft"); // Gentle breeze // } else if (wind_speed < 7.9) { // return formatInt(4, "Bft"); // Moderate breeze // } else if (wind_speed < 10.7) { // return formatInt(5, "Bft"); // Fresh breeze // } else if (wind_speed < 13.8) { // return formatInt(6, "Bft"); // Strong breeze // } else if (wind_speed < 17.1) { // return formatInt(7, "Bft"); // High wind // } else if (wind_speed < 20.7) { // return formatInt(8, "Bft"); // Gale // } else if (wind_speed < 24.4) { // return formatInt(9, "Bft"); // Strong gale // } else if (wind_speed < 28.4) { // return formatInt(10, "Bft"); // Storm // } else if (wind_speed < 32.6) { // return formatInt(11, "Bft"); // Violent storm // } else { // return formatInt(12, "Bft"); // Hurricane // } // } // // // public static String formatWindDir(Context context, float wind_direction) { // if (wind_direction < 22.5) { // return Character.toString((char) 0x2193); // North // } else if (wind_direction < 67.5) { // return Character.toString((char) 0x2199); // North East // } else if (wind_direction < 112.5) { // return Character.toString((char) 0x2190); // East // } else if (wind_direction < 157.5) { // return Character.toString((char) 0x2196); // South East // } else if (wind_direction < 202.5) { // return Character.toString((char) 0x2191); // South // } else if (wind_direction < 247.5) { // return Character.toString((char) 0x2197); // South West // } else if (wind_direction < 292.5) { // return Character.toString((char) 0x2192); // West // } else if (wind_direction < 337.5) { // return Character.toString((char) 0x2198); // North West // } else { // return Character.toString((char) 0x2193); // North // } // } // // public static Integer getDay(int day) { // // switch (day) { // case Calendar.MONDAY: // day = R.string.abbreviation_monday; // break; // case Calendar.TUESDAY: // day = R.string.abbreviation_tuesday; // break; // case Calendar.WEDNESDAY: // day = R.string.abbreviation_wednesday; // break; // case Calendar.THURSDAY: // day = R.string.abbreviation_thursday; // break; // case Calendar.FRIDAY: // day = R.string.abbreviation_friday; // break; // case Calendar.SATURDAY: // day = R.string.abbreviation_saturday; // break; // case Calendar.SUNDAY: // day = R.string.abbreviation_sunday; // break; // default: // day = R.string.abbreviation_monday; // } // return day; // } // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/preferences/AppPreferencesManager.java import android.content.Context; import android.content.SharedPreferences; import androidx.appcompat.app.AppCompatDelegate; import org.secuso.privacyfriendlyweather.BuildConfig; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.ui.Help.StringFormatUtils; break; case 3: AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); break; } } /** * @return Returns speed unit abbreviations */ public String getSpeedUnit() { int prefValue = Integer.parseInt(preferences.getString("speedUnit", "6")); if (prefValue == 1) { return "km/h"; } else if (prefValue == 2) { return "m/s"; } else if (prefValue == 3) { return "mph"; } else if (prefValue == 4) { return "ft/s"; } else if (prefValue == 5) { return "kn"; } else { return "Bft"; } } public String convertToCurrentSpeedUnit(float speedInMetersPerSecond) { int prefValue = Integer.parseInt(preferences.getString("speedUnit", "6")); if (prefValue == 1) {
return StringFormatUtils.formatDecimal(speedInMetersPerSecond * 3.6f, "km/h");
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/ui/AreYouSureFragment.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/activities/CreateKeyActivity.java // public class CreateKeyActivity extends AppCompatActivity { // // public static boolean active = false; // // RelativeLayout layout; // EditText personalKeyField; // Button keyButton; // Button abortButton; // Boolean fragmentShown = false; // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // setContentView(R.layout.activity_create_key); // layout = findViewById(R.id.add_key_layout); // personalKeyField = findViewById(R.id.owm_key_field); // keyButton = findViewById(R.id.set_owm_key_button); // abortButton = findViewById(R.id.abort_button); // TextView introText = findViewById(R.id.explanation_text_owm_key); // boolean limitReached = getIntent().getBooleanExtra("429", false); // if (!limitReached) { // introText.setText(R.string.explanation_owm_key_on_start); // } // // keyButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // String currentValue = personalKeyField.getText().toString().replaceAll("[\\s\\u0085\\p{Z}]", ""); // Log.d("debugtag", "currentfalue3: " + currentValue); // if (currentValue != null && currentValue.length() == 32) { // // SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // SharedPreferences.Editor editor = settings.edit(); // editor.putString("API_key_value", currentValue); // editor.commit(); // leave(); // } else { // Toast.makeText(getApplicationContext(), R.string.insert_correct_owm_key, Toast.LENGTH_LONG).show(); // } // } // }); // // abortButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // onBackPressed(); // } // }); // // // Toolbar toolbar = findViewById(R.id.toolbar); // if (getSupportActionBar() == null) { // setSupportActionBar(toolbar); // } // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // getSupportActionBar().setDisplayShowHomeEnabled(true); // // } // // @Override // public boolean onSupportNavigateUp() { // onBackPressed(); // return true; // } // // private void areYouSure() { // fragmentShown = true; // FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); // ft.replace(R.id.are_you_sure_fragment, new AreYouSureFragment()); // ft.commit(); // } // // @Override // public void onBackPressed() { // if (fragmentShown) { // FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); // ft.remove(getSupportFragmentManager().findFragmentById(R.id.are_you_sure_fragment)); // ft.commit(); // fragmentShown = false; // } else { // areYouSure(); // } // } // // public void leave() { // AppPreferencesManager prefManager = new AppPreferencesManager(PreferenceManager.getDefaultSharedPreferences(this)); // prefManager.setAskedForOwmKey(true); // ForecastCityActivity.stopTurning = true; // if (isTaskRoot()) { // Intent mainIntent = new Intent(getApplicationContext(), ForecastCityActivity.class); // startActivity(mainIntent); // } else { // super.onBackPressed(); // // } // } // // @Override // protected void onStart() { // super.onStart(); // active = true; // } // // @Override // protected void onStop() { // super.onStop(); // active = false; // } // // @Override // protected void onNewIntent(Intent intent) { // super.onNewIntent(intent); // setIntent(intent); // } // }
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.activities.CreateKeyActivity;
package org.secuso.privacyfriendlyweather.ui; public class AreYouSureFragment extends Fragment { Button shared; Button personal; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_are_you_sure, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); shared = view.findViewById(R.id.button_abort_personal_key); personal = view.findViewById(R.id.button_return_to_key); shared.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/activities/CreateKeyActivity.java // public class CreateKeyActivity extends AppCompatActivity { // // public static boolean active = false; // // RelativeLayout layout; // EditText personalKeyField; // Button keyButton; // Button abortButton; // Boolean fragmentShown = false; // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // setContentView(R.layout.activity_create_key); // layout = findViewById(R.id.add_key_layout); // personalKeyField = findViewById(R.id.owm_key_field); // keyButton = findViewById(R.id.set_owm_key_button); // abortButton = findViewById(R.id.abort_button); // TextView introText = findViewById(R.id.explanation_text_owm_key); // boolean limitReached = getIntent().getBooleanExtra("429", false); // if (!limitReached) { // introText.setText(R.string.explanation_owm_key_on_start); // } // // keyButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // String currentValue = personalKeyField.getText().toString().replaceAll("[\\s\\u0085\\p{Z}]", ""); // Log.d("debugtag", "currentfalue3: " + currentValue); // if (currentValue != null && currentValue.length() == 32) { // // SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // SharedPreferences.Editor editor = settings.edit(); // editor.putString("API_key_value", currentValue); // editor.commit(); // leave(); // } else { // Toast.makeText(getApplicationContext(), R.string.insert_correct_owm_key, Toast.LENGTH_LONG).show(); // } // } // }); // // abortButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // onBackPressed(); // } // }); // // // Toolbar toolbar = findViewById(R.id.toolbar); // if (getSupportActionBar() == null) { // setSupportActionBar(toolbar); // } // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // getSupportActionBar().setDisplayShowHomeEnabled(true); // // } // // @Override // public boolean onSupportNavigateUp() { // onBackPressed(); // return true; // } // // private void areYouSure() { // fragmentShown = true; // FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); // ft.replace(R.id.are_you_sure_fragment, new AreYouSureFragment()); // ft.commit(); // } // // @Override // public void onBackPressed() { // if (fragmentShown) { // FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); // ft.remove(getSupportFragmentManager().findFragmentById(R.id.are_you_sure_fragment)); // ft.commit(); // fragmentShown = false; // } else { // areYouSure(); // } // } // // public void leave() { // AppPreferencesManager prefManager = new AppPreferencesManager(PreferenceManager.getDefaultSharedPreferences(this)); // prefManager.setAskedForOwmKey(true); // ForecastCityActivity.stopTurning = true; // if (isTaskRoot()) { // Intent mainIntent = new Intent(getApplicationContext(), ForecastCityActivity.class); // startActivity(mainIntent); // } else { // super.onBackPressed(); // // } // } // // @Override // protected void onStart() { // super.onStart(); // active = true; // } // // @Override // protected void onStop() { // super.onStop(); // active = false; // } // // @Override // protected void onNewIntent(Intent intent) { // super.onNewIntent(intent); // setIntent(intent); // } // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/ui/AreYouSureFragment.java import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import org.secuso.privacyfriendlyweather.R; import org.secuso.privacyfriendlyweather.activities.CreateKeyActivity; package org.secuso.privacyfriendlyweather.ui; public class AreYouSureFragment extends Fragment { Button shared; Button personal; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_are_you_sure, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); shared = view.findViewById(R.id.button_abort_personal_key); personal = view.findViewById(R.id.button_return_to_key); shared.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
((CreateKeyActivity) getActivity()).leave();
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForOneCallAPI.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForOneCallAPI.java // public interface IHttpRequestForOneCallAPI { // // /** // * @param lat The latitude of the city to get the data for. // * @param lon The longitude of the city to get the data for. // */ // void perform(float lat, float lon); // // }
import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForOneCallAPI;
package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForOneCallAPI extends OwmHttpRequest implements IHttpRequestForOneCallAPI { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForOneCallAPI(Context context) { this.context = context; } @Override public void perform(float lat, float lon) {
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForOneCallAPI.java // public interface IHttpRequestForOneCallAPI { // // /** // * @param lat The latitude of the city to get the data for. // * @param lon The longitude of the city to get the data for. // */ // void perform(float lat, float lon); // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForOneCallAPI.java import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForOneCallAPI; package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForOneCallAPI extends OwmHttpRequest implements IHttpRequestForOneCallAPI { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForOneCallAPI(Context context) { this.context = context; } @Override public void perform(float lat, float lon) {
IHttpRequest httpRequest = new VolleyHttpRequest(context);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForOneCallAPI.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForOneCallAPI.java // public interface IHttpRequestForOneCallAPI { // // /** // * @param lat The latitude of the city to get the data for. // * @param lon The longitude of the city to get the data for. // */ // void perform(float lat, float lon); // // }
import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForOneCallAPI;
package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForOneCallAPI extends OwmHttpRequest implements IHttpRequestForOneCallAPI { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForOneCallAPI(Context context) { this.context = context; } @Override public void perform(float lat, float lon) {
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForOneCallAPI.java // public interface IHttpRequestForOneCallAPI { // // /** // * @param lat The latitude of the city to get the data for. // * @param lon The longitude of the city to get the data for. // */ // void perform(float lat, float lon); // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForOneCallAPI.java import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForOneCallAPI; package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForOneCallAPI extends OwmHttpRequest implements IHttpRequestForOneCallAPI { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForOneCallAPI(Context context) { this.context = context; } @Override public void perform(float lat, float lon) {
IHttpRequest httpRequest = new VolleyHttpRequest(context);
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForOneCallAPI.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForOneCallAPI.java // public interface IHttpRequestForOneCallAPI { // // /** // * @param lat The latitude of the city to get the data for. // * @param lon The longitude of the city to get the data for. // */ // void perform(float lat, float lon); // // }
import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForOneCallAPI;
package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForOneCallAPI extends OwmHttpRequest implements IHttpRequestForOneCallAPI { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForOneCallAPI(Context context) { this.context = context; } @Override public void perform(float lat, float lon) { IHttpRequest httpRequest = new VolleyHttpRequest(context); final String URL = getUrlForQueryingOneCallAPI(context, lat, lon); // Log.d("OneCallURL",URL);
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/HttpRequestType.java // public enum HttpRequestType { // POST, // GET, // PUT, // DELETE // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/IHttpRequest.java // public interface IHttpRequest { // // /** // * Makes an HTTP request and processes the response. // * // * @param URL The target of the HTTP request. // * @param method Which method to use for the HTTP request (e.g. GET or POST) // * @param requestProcessor This object with its implemented methods processSuccessScenario and // * processFailScenario defines how to handle the response in the success // * and error case respectively. // */ // void make(final String URL, HttpRequestType method, IProcessHttpRequest requestProcessor); // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/http/VolleyHttpRequest.java // public class VolleyHttpRequest implements IHttpRequest { // // private Context context; // // /** // * Constructor. // * // * @param context Volley needs a context "for creating the cache dir". // * @see Volley#newRequestQueue(Context) // */ // public VolleyHttpRequest(Context context) { // this.context = context; // } // // /** // * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest) // */ // @Override // public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) { // RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory())); // // // Set the request method // int requestMethod; // switch (method) { // case POST: // requestMethod = Request.Method.POST; // break; // case GET: // requestMethod = Request.Method.GET; // break; // case PUT: // requestMethod = Request.Method.PUT; // break; // case DELETE: // requestMethod = Request.Method.DELETE; // break; // default: // requestMethod = Request.Method.GET; // } // // // Execute the request and handle the response // StringRequest stringRequest = new StringRequest(requestMethod, URL, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // requestProcessor.processSuccessScenario(response); // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // requestProcessor.processFailScenario(error); // } // } // ); // // queue.add(stringRequest); // } // // private SSLSocketFactory getSocketFactory() { // // CertificateFactory cf = null; // try { // // Load CAs from an InputStream // cf = CertificateFactory.getInstance("X.509"); // InputStream caInput = new BufferedInputStream(context.getAssets().open("SectigoRSADomainValidationSecureServerCA.crt")); // // Certificate ca; // try { // ca = cf.generateCertificate(caInput); // Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN()); // } finally { // caInput.close(); // } // // // Create a KeyStore containing our trusted CAs // String keyStoreType = KeyStore.getDefaultType(); // KeyStore keyStore = KeyStore.getInstance(keyStoreType); // keyStore.load(null, null); // keyStore.setCertificateEntry("ca", ca); // // // Create a TrustManager that trusts the CAs in our KeyStore // String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); // TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); // tmf.init(keyStore); // // // Create an SSLContext that uses our TrustManager // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, tmf.getTrustManagers(), null); // // SSLSocketFactory sf = context.getSocketFactory(); // // return sf; // // } catch (CertificateException e) { // Log.e("CERT", "CertificateException"); // e.printStackTrace(); // } catch (NoSuchAlgorithmException e) { // Log.e("CERT", "NoSuchAlgorithmException"); // e.printStackTrace(); // } catch (KeyStoreException e) { // Log.e("CERT", "KeyStoreException"); // e.printStackTrace(); // } catch (FileNotFoundException e) { // Log.e("CERT", "FileNotFoundException"); // e.printStackTrace(); // } catch (IOException e) { // Log.e("CERT", "IOException"); // e.printStackTrace(); // } catch (KeyManagementException e) { // Log.e("CERT", "KeyManagementException"); // e.printStackTrace(); // } // // return null; // } // // } // // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/IHttpRequestForOneCallAPI.java // public interface IHttpRequestForOneCallAPI { // // /** // * @param lat The latitude of the city to get the data for. // * @param lon The longitude of the city to get the data for. // */ // void perform(float lat, float lon); // // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/weather_api/open_weather_map/OwmHttpRequestForOneCallAPI.java import android.content.Context; import org.secuso.privacyfriendlyweather.http.HttpRequestType; import org.secuso.privacyfriendlyweather.http.IHttpRequest; import org.secuso.privacyfriendlyweather.http.VolleyHttpRequest; import org.secuso.privacyfriendlyweather.weather_api.IHttpRequestForOneCallAPI; package org.secuso.privacyfriendlyweather.weather_api.open_weather_map; /** * This class provides the functionality for making and processing HTTP requests to the * OpenWeatherMap to retrieve the latest weather data for all stored cities. */ public class OwmHttpRequestForOneCallAPI extends OwmHttpRequest implements IHttpRequestForOneCallAPI { /** * Member variables. */ private Context context; /** * @param context The context to use. */ public OwmHttpRequestForOneCallAPI(Context context) { this.context = context; } @Override public void perform(float lat, float lon) { IHttpRequest httpRequest = new VolleyHttpRequest(context); final String URL = getUrlForQueryingOneCallAPI(context, lat, lon); // Log.d("OneCallURL",URL);
httpRequest.make(URL, HttpRequestType.GET, new ProcessOwmForecastOneCallAPIRequest(context));
SecUSo/privacy-friendly-weather
app/src/main/java/org/secuso/privacyfriendlyweather/database/dao/CityDao.java
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/data/City.java // @Entity(tableName = "CITIES", indices = {@Index(value = {"city_name", "cities_id"})}) // public class City { // // private static final String UNKNOWN_POSTAL_CODE_VALUE = "-"; // // @PrimaryKey @ColumnInfo(name = "cities_id") private int cityId; // @ColumnInfo(name = "city_name") @NonNull private String cityName = ""; // @ColumnInfo(name = "country_code") @NonNull private String countryCode = ""; // @ColumnInfo(name = "longitude") private float longitude; // @ColumnInfo(name = "latitude") private float latitude; // // public City() { } // // @Ignore public City(int cityId, @NonNull String cityName, @NonNull String countryCode, float lon, float lat) { // this.cityId = cityId; // this.cityName = cityName; // this.countryCode = countryCode; // this.longitude = lon; // this.latitude = lat; // } // // public int getCityId() { // return cityId; // } // // public void setCityId(int cityId) { // this.cityId = cityId; // } // // public @NonNull String getCityName() { // return cityName; // } // // public void setCityName(@NonNull String cityName) { // this.cityName = cityName; // } // // public @NonNull String getCountryCode() { // return countryCode; // } // // public void setCountryCode(@NonNull String countryCode) { // this.countryCode = countryCode; // } // // @Override // public @NonNull String toString() { // return String.format(Locale.ENGLISH, "%s, %s (%f - %f)", cityName, countryCode, longitude, latitude); // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public float getLatitude() { // return latitude; // } // // public float getLongitude() { // return longitude; // } // // public void setLongitude(float lon) { // this.longitude = lon; // } // }
import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import org.secuso.privacyfriendlyweather.database.data.City; import java.util.List;
package org.secuso.privacyfriendlyweather.database.dao; /** * @author Christopher Beckmann */ @Dao public interface CityDao { @Insert
// Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/data/City.java // @Entity(tableName = "CITIES", indices = {@Index(value = {"city_name", "cities_id"})}) // public class City { // // private static final String UNKNOWN_POSTAL_CODE_VALUE = "-"; // // @PrimaryKey @ColumnInfo(name = "cities_id") private int cityId; // @ColumnInfo(name = "city_name") @NonNull private String cityName = ""; // @ColumnInfo(name = "country_code") @NonNull private String countryCode = ""; // @ColumnInfo(name = "longitude") private float longitude; // @ColumnInfo(name = "latitude") private float latitude; // // public City() { } // // @Ignore public City(int cityId, @NonNull String cityName, @NonNull String countryCode, float lon, float lat) { // this.cityId = cityId; // this.cityName = cityName; // this.countryCode = countryCode; // this.longitude = lon; // this.latitude = lat; // } // // public int getCityId() { // return cityId; // } // // public void setCityId(int cityId) { // this.cityId = cityId; // } // // public @NonNull String getCityName() { // return cityName; // } // // public void setCityName(@NonNull String cityName) { // this.cityName = cityName; // } // // public @NonNull String getCountryCode() { // return countryCode; // } // // public void setCountryCode(@NonNull String countryCode) { // this.countryCode = countryCode; // } // // @Override // public @NonNull String toString() { // return String.format(Locale.ENGLISH, "%s, %s (%f - %f)", cityName, countryCode, longitude, latitude); // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public float getLatitude() { // return latitude; // } // // public float getLongitude() { // return longitude; // } // // public void setLongitude(float lon) { // this.longitude = lon; // } // } // Path: app/src/main/java/org/secuso/privacyfriendlyweather/database/dao/CityDao.java import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import org.secuso.privacyfriendlyweather.database.data.City; import java.util.List; package org.secuso.privacyfriendlyweather.database.dao; /** * @author Christopher Beckmann */ @Dao public interface CityDao { @Insert
void insertAll(List<City> cities);
Psiphon-Labs/ploggy
AndroidApp/src/fi/iki/elonen/NanoHTTPD.java
// Path: AndroidApp/src/ca/psiphon/ploggy/Log.java // public class Log { // // private static final String LOG_TAG = "Log"; // // public static class Entry { // public final Date mTimestamp; // public final String mTag; // public final String mMessage; // // public Entry(String tag, String message) { // mTimestamp = new Date(); // mTag = tag; // mMessage = message; // } // } // // public interface Observer { // void onUpdatedRecentEntries(); // } // // private static final int MAX_RECENT_ENTRIES = 500; // // private static ArrayList<Entry> mRecentEntries; // private static ArrayList<Observer> mObservers; // private static Handler mHandler; // // // TODO: explicit singleton? // // public synchronized static void initialize() { // mRecentEntries = new ArrayList<Entry>(); // mObservers = new ArrayList<Observer>(); // mHandler = new Handler(); // } // // public synchronized static void addEntry(String tag, String message) { // if (message == null) { // message = "(null)"; // } // // Entry entry = new Entry(tag, message); // // // Update the in-memory entry list on the UI thread (also // // notifies any ListView adapters subscribed to that list) // postAddEntry(entry); // // // Temporary // android.util.Log.e("Ploggy", tag + " " + message); // } // // public synchronized static int getRecentEntryCount() { // return mRecentEntries.size(); // } // // public synchronized static Entry getRecentEntry(int index) { // return mRecentEntries.get(index); // } // // public synchronized static void registerObserver(Observer observer) { // if (!mObservers.contains(observer)) { // mObservers.add(observer); // } // } // // public synchronized static void unregisterObserver(Observer observer) { // mObservers.remove(observer); // } // // public synchronized static void composeEmail(Context context) { // // TODO: temporary feature for debugging prototype -- will compromise unlinkability // try { // StringBuilder body = new StringBuilder(); // for (Entry entry : mRecentEntries) { // body.append(entry.mTimestamp); // body.append(" "); // body.append(entry.mTag); // body.append(": "); // body.append(entry.mMessage); // body.append("\n"); // } // // Intent intent = new Intent(Intent.ACTION_SEND); // intent.setType("message/rfc822"); // intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"}); // intent.putExtra(Intent.EXTRA_SUBJECT, "Ploggy Logs"); // intent.putExtra(Intent.EXTRA_TEXT, body.toString()); // context.startActivity(intent); // } catch (ActivityNotFoundException e) { // Log.addEntry(LOG_TAG, e.getMessage()); // Log.addEntry(LOG_TAG, "compose log email failed"); // } // } // // private static void postAddEntry(Entry entry) { // final Entry finalEntry = entry; // mHandler.post( // new Runnable() { // @Override // public void run() { // mRecentEntries.add(finalEntry); // while (mRecentEntries.size() > MAX_RECENT_ENTRIES) { // mRecentEntries.remove(0); // } // for (Observer observer : mObservers) { // observer.onUpdatedRecentEntries(); // } // } // }); // } // }
import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.SequenceInputStream; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; import ca.psiphon.ploggy.Log;
myThread = new Thread(new Runnable() { @Override public void run() { do { try { final Socket finalAccept = myServerSocket.accept(); registerConnection(finalAccept); finalAccept.setSoTimeout(getReadTimeout()); final InputStream inputStream = finalAccept.getInputStream(); if (inputStream == null) { safeClose(finalAccept); unRegisterConnection(finalAccept); } else { asyncRunner.exec(new Runnable() { @Override public void run() { OutputStream outputStream = null; try { outputStream = finalAccept.getOutputStream(); TempFileManager tempFileManager = tempFileManagerFactory.create(); HTTPSession session = new HTTPSession(finalAccept, tempFileManager, inputStream, outputStream); while (!finalAccept.isClosed()) { session.execute(); } } catch (Exception e) { // When the socket is closed by the client, we throw our own SocketException // to break the "keep alive" loop above. if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { // ==== ploggy ====
// Path: AndroidApp/src/ca/psiphon/ploggy/Log.java // public class Log { // // private static final String LOG_TAG = "Log"; // // public static class Entry { // public final Date mTimestamp; // public final String mTag; // public final String mMessage; // // public Entry(String tag, String message) { // mTimestamp = new Date(); // mTag = tag; // mMessage = message; // } // } // // public interface Observer { // void onUpdatedRecentEntries(); // } // // private static final int MAX_RECENT_ENTRIES = 500; // // private static ArrayList<Entry> mRecentEntries; // private static ArrayList<Observer> mObservers; // private static Handler mHandler; // // // TODO: explicit singleton? // // public synchronized static void initialize() { // mRecentEntries = new ArrayList<Entry>(); // mObservers = new ArrayList<Observer>(); // mHandler = new Handler(); // } // // public synchronized static void addEntry(String tag, String message) { // if (message == null) { // message = "(null)"; // } // // Entry entry = new Entry(tag, message); // // // Update the in-memory entry list on the UI thread (also // // notifies any ListView adapters subscribed to that list) // postAddEntry(entry); // // // Temporary // android.util.Log.e("Ploggy", tag + " " + message); // } // // public synchronized static int getRecentEntryCount() { // return mRecentEntries.size(); // } // // public synchronized static Entry getRecentEntry(int index) { // return mRecentEntries.get(index); // } // // public synchronized static void registerObserver(Observer observer) { // if (!mObservers.contains(observer)) { // mObservers.add(observer); // } // } // // public synchronized static void unregisterObserver(Observer observer) { // mObservers.remove(observer); // } // // public synchronized static void composeEmail(Context context) { // // TODO: temporary feature for debugging prototype -- will compromise unlinkability // try { // StringBuilder body = new StringBuilder(); // for (Entry entry : mRecentEntries) { // body.append(entry.mTimestamp); // body.append(" "); // body.append(entry.mTag); // body.append(": "); // body.append(entry.mMessage); // body.append("\n"); // } // // Intent intent = new Intent(Intent.ACTION_SEND); // intent.setType("message/rfc822"); // intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"}); // intent.putExtra(Intent.EXTRA_SUBJECT, "Ploggy Logs"); // intent.putExtra(Intent.EXTRA_TEXT, body.toString()); // context.startActivity(intent); // } catch (ActivityNotFoundException e) { // Log.addEntry(LOG_TAG, e.getMessage()); // Log.addEntry(LOG_TAG, "compose log email failed"); // } // } // // private static void postAddEntry(Entry entry) { // final Entry finalEntry = entry; // mHandler.post( // new Runnable() { // @Override // public void run() { // mRecentEntries.add(finalEntry); // while (mRecentEntries.size() > MAX_RECENT_ENTRIES) { // mRecentEntries.remove(0); // } // for (Observer observer : mObservers) { // observer.onUpdatedRecentEntries(); // } // } // }); // } // } // Path: AndroidApp/src/fi/iki/elonen/NanoHTTPD.java import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.SequenceInputStream; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; import ca.psiphon.ploggy.Log; myThread = new Thread(new Runnable() { @Override public void run() { do { try { final Socket finalAccept = myServerSocket.accept(); registerConnection(finalAccept); finalAccept.setSoTimeout(getReadTimeout()); final InputStream inputStream = finalAccept.getInputStream(); if (inputStream == null) { safeClose(finalAccept); unRegisterConnection(finalAccept); } else { asyncRunner.exec(new Runnable() { @Override public void run() { OutputStream outputStream = null; try { outputStream = finalAccept.getOutputStream(); TempFileManager tempFileManager = tempFileManagerFactory.create(); HTTPSession session = new HTTPSession(finalAccept, tempFileManager, inputStream, outputStream); while (!finalAccept.isClosed()) { session.execute(); } } catch (Exception e) { // When the socket is closed by the client, we throw our own SocketException // to break the "keep alive" loop above. if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { // ==== ploggy ====
Log.addEntry(LOG_TAG, e.getMessage());
Psiphon-Labs/ploggy
AndroidApp/src/ca/psiphon/ploggy/Downloads.java
// Path: AndroidApp/src/ca/psiphon/ploggy/Utils.java // public static class ApplicationError extends Exception { // private static final long serialVersionUID = -3656367025650685613L; // // public ApplicationError(String tag, String message) { // if (tag != null) { // Log.addEntry(tag, message); // } // } // // public ApplicationError(String tag, Exception e) { // // TODO: require message param as well? // super(e); // String message = e.getLocalizedMessage(); // if (message == null) { // message = "(null)"; // } // Log.addEntry(tag, String.format("%s: %s", e.getClass().toString(), message)); // // TODO: log stack trace? // } // }
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import android.content.Context; import ca.psiphon.ploggy.Utils.ApplicationError;
/* * Copyright (c) 2013, Psiphon Inc. * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package ca.psiphon.ploggy; /** * Helpers for managing download files */ public class Downloads { private static final String LOG_TAG = "Downloads"; private static final String DOWNLOAD_FILENAME_FORMAT_STRING = "%s-%s.download"; private static final String DOWNLOADS_DIRECTORY = "ploggyDownloads"; public static long getDownloadedSize(Data.Download download) { return getDownloadFile(download).length(); }
// Path: AndroidApp/src/ca/psiphon/ploggy/Utils.java // public static class ApplicationError extends Exception { // private static final long serialVersionUID = -3656367025650685613L; // // public ApplicationError(String tag, String message) { // if (tag != null) { // Log.addEntry(tag, message); // } // } // // public ApplicationError(String tag, Exception e) { // // TODO: require message param as well? // super(e); // String message = e.getLocalizedMessage(); // if (message == null) { // message = "(null)"; // } // Log.addEntry(tag, String.format("%s: %s", e.getClass().toString(), message)); // // TODO: log stack trace? // } // } // Path: AndroidApp/src/ca/psiphon/ploggy/Downloads.java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import android.content.Context; import ca.psiphon.ploggy.Utils.ApplicationError; /* * Copyright (c) 2013, Psiphon Inc. * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package ca.psiphon.ploggy; /** * Helpers for managing download files */ public class Downloads { private static final String LOG_TAG = "Downloads"; private static final String DOWNLOAD_FILENAME_FORMAT_STRING = "%s-%s.download"; private static final String DOWNLOADS_DIRECTORY = "ploggyDownloads"; public static long getDownloadedSize(Data.Download download) { return getDownloadFile(download).length(); }
public static OutputStream openDownloadResourceForAppending(Data.Download download) throws ApplicationError {
Psiphon-Labs/ploggy
AndroidApp/src/ca/psiphon/ploggy/ActivitySettings.java
// Path: AndroidApp/src/ca/psiphon/ploggy/widgets/TimePickerPreference.java // public class TimePickerPreference extends DialogPreference implements // TimePicker.OnTimeChangedListener { // // /** // * The validation expression for this preference // */ // private static final String VALIDATION_EXPRESSION = "[0-2]*[0-9]:[0-5]*[0-9]"; // // /** // * The default value for this preference // */ // private final String defaultValue; // private String result; // private TimePicker tp; // // /** // * @param context // * @param attrs // */ // public TimePickerPreference(Context context, AttributeSet attrs) { // super(context, attrs); // defaultValue = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "defaultValue"); // initialize(); // } // // /** // * @param context // * @param attrs // * @param defStyle // */ // public TimePickerPreference(Context context, AttributeSet attrs, // int defStyle) { // super(context, attrs, defStyle); // defaultValue = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "defaultValue"); // initialize(); // } // // /** // * Initialize this preference // */ // private void initialize() { // setPersistent(true); // } // // /* // * (non-Javadoc) // * // * @see android.preference.DialogPreference#onCreateDialogView() // */ // @Override // protected View onCreateDialogView() { // // tp = new TimePicker(getContext()); // tp.setOnTimeChangedListener(this); // // String value = getPersistedString(this.defaultValue); // int h = getHour(value); // int m = getMinute(value); // if (h >= 0 && m >= 0) { // tp.setCurrentHour(h); // tp.setCurrentMinute(m); // } // tp.setIs24HourView(DateFormat.is24HourFormat(getContext())); // // return tp; // } // // /* // * (non-Javadoc) // * // * @see // * android.widget.TimePicker.OnTimeChangedListener#onTimeChanged(android // * .widget.TimePicker, int, int) // */ // // @Override // public void onTimeChanged(TimePicker view, int hour, int minute) { // result = hour + ":" + minute; // } // // /* // * (non-Javadoc) // * // * @see // * android.preference.DialogPreference#onDismiss(android.content.DialogInterface // * ) // */ // @Override // public void onDismiss(DialogInterface dialog) { // super.onDismiss(dialog); // } // // /* // * (non-Javadoc) // * // * @see android.preference.DialogPreference#onDialogClosed(boolean) // */ // @Override // protected void onDialogClosed(boolean positiveResult) { // super.onDialogClosed(positiveResult); // if (positiveResult) { // tp.clearFocus(); // to get value of number if edited in text field, and clicking OK without clicking outside the field first (bug in NumberPicker) // result = tp.getCurrentHour() + ":" + tp.getCurrentMinute(); // persistString(result); // callChangeListener(result); // } // } // // /** // * Get the hour value (in 24 hour time) // * // * @return The hour value, will be 0 to 23 (inclusive) // */ // public static int getHour(String value) { // if (value == null || !value.matches(VALIDATION_EXPRESSION)) { // return -1; // } // // return Integer.valueOf(value.split(":|/")[0]); // } // // /** // * Get the minute value // * // * @return the minute value, will be 0 to 59 (inclusive) // */ // public static int getMinute(String value) { // if (value == null || !value.matches(VALIDATION_EXPRESSION)) { // return -1; // } // // return Integer.valueOf(value.split(":|/")[1]); // } // }
import java.util.Map; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import ca.psiphon.ploggy.widgets.TimePickerPreference;
initTimePickerPreferences(); } @Override public void onResume() { super.onResume(); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { setTimePickerPreferenceSummary(sharedPreferences, key); } private void initTimePickerPreferences() { SharedPreferences sharedPreferences = this.getPreferenceManager().getSharedPreferences(); for (Map.Entry<String, ?> entry : sharedPreferences.getAll().entrySet()) { setTimePickerPreferenceSummary(sharedPreferences, entry.getKey()); } } private void setTimePickerPreferenceSummary(SharedPreferences sharedPreferences, String key) { Preference preference = findPreference(key);
// Path: AndroidApp/src/ca/psiphon/ploggy/widgets/TimePickerPreference.java // public class TimePickerPreference extends DialogPreference implements // TimePicker.OnTimeChangedListener { // // /** // * The validation expression for this preference // */ // private static final String VALIDATION_EXPRESSION = "[0-2]*[0-9]:[0-5]*[0-9]"; // // /** // * The default value for this preference // */ // private final String defaultValue; // private String result; // private TimePicker tp; // // /** // * @param context // * @param attrs // */ // public TimePickerPreference(Context context, AttributeSet attrs) { // super(context, attrs); // defaultValue = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "defaultValue"); // initialize(); // } // // /** // * @param context // * @param attrs // * @param defStyle // */ // public TimePickerPreference(Context context, AttributeSet attrs, // int defStyle) { // super(context, attrs, defStyle); // defaultValue = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "defaultValue"); // initialize(); // } // // /** // * Initialize this preference // */ // private void initialize() { // setPersistent(true); // } // // /* // * (non-Javadoc) // * // * @see android.preference.DialogPreference#onCreateDialogView() // */ // @Override // protected View onCreateDialogView() { // // tp = new TimePicker(getContext()); // tp.setOnTimeChangedListener(this); // // String value = getPersistedString(this.defaultValue); // int h = getHour(value); // int m = getMinute(value); // if (h >= 0 && m >= 0) { // tp.setCurrentHour(h); // tp.setCurrentMinute(m); // } // tp.setIs24HourView(DateFormat.is24HourFormat(getContext())); // // return tp; // } // // /* // * (non-Javadoc) // * // * @see // * android.widget.TimePicker.OnTimeChangedListener#onTimeChanged(android // * .widget.TimePicker, int, int) // */ // // @Override // public void onTimeChanged(TimePicker view, int hour, int minute) { // result = hour + ":" + minute; // } // // /* // * (non-Javadoc) // * // * @see // * android.preference.DialogPreference#onDismiss(android.content.DialogInterface // * ) // */ // @Override // public void onDismiss(DialogInterface dialog) { // super.onDismiss(dialog); // } // // /* // * (non-Javadoc) // * // * @see android.preference.DialogPreference#onDialogClosed(boolean) // */ // @Override // protected void onDialogClosed(boolean positiveResult) { // super.onDialogClosed(positiveResult); // if (positiveResult) { // tp.clearFocus(); // to get value of number if edited in text field, and clicking OK without clicking outside the field first (bug in NumberPicker) // result = tp.getCurrentHour() + ":" + tp.getCurrentMinute(); // persistString(result); // callChangeListener(result); // } // } // // /** // * Get the hour value (in 24 hour time) // * // * @return The hour value, will be 0 to 23 (inclusive) // */ // public static int getHour(String value) { // if (value == null || !value.matches(VALIDATION_EXPRESSION)) { // return -1; // } // // return Integer.valueOf(value.split(":|/")[0]); // } // // /** // * Get the minute value // * // * @return the minute value, will be 0 to 59 (inclusive) // */ // public static int getMinute(String value) { // if (value == null || !value.matches(VALIDATION_EXPRESSION)) { // return -1; // } // // return Integer.valueOf(value.split(":|/")[1]); // } // } // Path: AndroidApp/src/ca/psiphon/ploggy/ActivitySettings.java import java.util.Map; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import ca.psiphon.ploggy.widgets.TimePickerPreference; initTimePickerPreferences(); } @Override public void onResume() { super.onResume(); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { setTimePickerPreferenceSummary(sharedPreferences, key); } private void initTimePickerPreferences() { SharedPreferences sharedPreferences = this.getPreferenceManager().getSharedPreferences(); for (Map.Entry<String, ?> entry : sharedPreferences.getAll().entrySet()) { setTimePickerPreferenceSummary(sharedPreferences, entry.getKey()); } } private void setTimePickerPreferenceSummary(SharedPreferences sharedPreferences, String key) { Preference preference = findPreference(key);
if (preference instanceof TimePickerPreference) {
Psiphon-Labs/ploggy
AndroidApp/src/ca/psiphon/ploggy/LocationMonitor.java
// Path: AndroidApp/src/ca/psiphon/ploggy/Utils.java // public static class ApplicationError extends Exception { // private static final long serialVersionUID = -3656367025650685613L; // // public ApplicationError(String tag, String message) { // if (tag != null) { // Log.addEntry(tag, message); // } // } // // public ApplicationError(String tag, Exception e) { // // TODO: require message param as well? // super(e); // String message = e.getLocalizedMessage(); // if (message == null) { // message = "(null)"; // } // Log.addEntry(tag, String.format("%s: %s", e.getClass().toString(), message)); // // TODO: log stack trace? // } // }
import android.content.Context; import android.location.Address; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import ca.psiphon.ploggy.Utils.ApplicationError;
/* * Copyright (c) 2013, Psiphon Inc. * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package ca.psiphon.ploggy; /** * Schedule and monitor location events from Android OS. * * Implements best practices from: * - http://developer.android.com/guide/topics/location/strategies.html * - http://code.google.com/p/android-protips-location/ * * Does not use the newer, higher level Play Services location API as it's * not available on open source Android builds and its source is not available * to review (e.g., verify that location isn't sent to 3rd party). */ public class LocationMonitor implements android.location.LocationListener { private static final String LOG_TAG = "Location Monitor"; Engine mEngine; Handler mHandler; Runnable mStartLocationFixTask; Runnable mFinishLocationFixTask; Runnable mStopLocationUpdatesTask; Location mLastReportedLocation; Location mCurrentLocation; LocationMonitor(Engine engine) { // TODO: use Utils.FixedDelayExecutor mEngine = engine; mHandler = new Handler(); initRunnables(); }
// Path: AndroidApp/src/ca/psiphon/ploggy/Utils.java // public static class ApplicationError extends Exception { // private static final long serialVersionUID = -3656367025650685613L; // // public ApplicationError(String tag, String message) { // if (tag != null) { // Log.addEntry(tag, message); // } // } // // public ApplicationError(String tag, Exception e) { // // TODO: require message param as well? // super(e); // String message = e.getLocalizedMessage(); // if (message == null) { // message = "(null)"; // } // Log.addEntry(tag, String.format("%s: %s", e.getClass().toString(), message)); // // TODO: log stack trace? // } // } // Path: AndroidApp/src/ca/psiphon/ploggy/LocationMonitor.java import android.content.Context; import android.location.Address; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import ca.psiphon.ploggy.Utils.ApplicationError; /* * Copyright (c) 2013, Psiphon Inc. * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package ca.psiphon.ploggy; /** * Schedule and monitor location events from Android OS. * * Implements best practices from: * - http://developer.android.com/guide/topics/location/strategies.html * - http://code.google.com/p/android-protips-location/ * * Does not use the newer, higher level Play Services location API as it's * not available on open source Android builds and its source is not available * to review (e.g., verify that location isn't sent to 3rd party). */ public class LocationMonitor implements android.location.LocationListener { private static final String LOG_TAG = "Location Monitor"; Engine mEngine; Handler mHandler; Runnable mStartLocationFixTask; Runnable mFinishLocationFixTask; Runnable mStopLocationUpdatesTask; Location mLastReportedLocation; Location mCurrentLocation; LocationMonitor(Engine engine) { // TODO: use Utils.FixedDelayExecutor mEngine = engine; mHandler = new Handler(); initRunnables(); }
public void start() throws Utils.ApplicationError {
Psiphon-Labs/ploggy
AndroidApp/src/ca/psiphon/ploggy/Engine.java
// Path: AndroidApp/src/ca/psiphon/ploggy/widgets/TimePickerPreference.java // public class TimePickerPreference extends DialogPreference implements // TimePicker.OnTimeChangedListener { // // /** // * The validation expression for this preference // */ // private static final String VALIDATION_EXPRESSION = "[0-2]*[0-9]:[0-5]*[0-9]"; // // /** // * The default value for this preference // */ // private final String defaultValue; // private String result; // private TimePicker tp; // // /** // * @param context // * @param attrs // */ // public TimePickerPreference(Context context, AttributeSet attrs) { // super(context, attrs); // defaultValue = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "defaultValue"); // initialize(); // } // // /** // * @param context // * @param attrs // * @param defStyle // */ // public TimePickerPreference(Context context, AttributeSet attrs, // int defStyle) { // super(context, attrs, defStyle); // defaultValue = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "defaultValue"); // initialize(); // } // // /** // * Initialize this preference // */ // private void initialize() { // setPersistent(true); // } // // /* // * (non-Javadoc) // * // * @see android.preference.DialogPreference#onCreateDialogView() // */ // @Override // protected View onCreateDialogView() { // // tp = new TimePicker(getContext()); // tp.setOnTimeChangedListener(this); // // String value = getPersistedString(this.defaultValue); // int h = getHour(value); // int m = getMinute(value); // if (h >= 0 && m >= 0) { // tp.setCurrentHour(h); // tp.setCurrentMinute(m); // } // tp.setIs24HourView(DateFormat.is24HourFormat(getContext())); // // return tp; // } // // /* // * (non-Javadoc) // * // * @see // * android.widget.TimePicker.OnTimeChangedListener#onTimeChanged(android // * .widget.TimePicker, int, int) // */ // // @Override // public void onTimeChanged(TimePicker view, int hour, int minute) { // result = hour + ":" + minute; // } // // /* // * (non-Javadoc) // * // * @see // * android.preference.DialogPreference#onDismiss(android.content.DialogInterface // * ) // */ // @Override // public void onDismiss(DialogInterface dialog) { // super.onDismiss(dialog); // } // // /* // * (non-Javadoc) // * // * @see android.preference.DialogPreference#onDialogClosed(boolean) // */ // @Override // protected void onDialogClosed(boolean positiveResult) { // super.onDialogClosed(positiveResult); // if (positiveResult) { // tp.clearFocus(); // to get value of number if edited in text field, and clicking OK without clicking outside the field first (bug in NumberPicker) // result = tp.getCurrentHour() + ":" + tp.getCurrentMinute(); // persistString(result); // callChangeListener(result); // } // } // // /** // * Get the hour value (in 24 hour time) // * // * @return The hour value, will be 0 to 23 (inclusive) // */ // public static int getHour(String value) { // if (value == null || !value.matches(VALIDATION_EXPRESSION)) { // return -1; // } // // return Integer.valueOf(value.split(":|/")[0]); // } // // /** // * Get the minute value // * // * @return the minute value, will be 0 to 59 (inclusive) // */ // public static int getMinute(String value) { // if (value == null || !value.matches(VALIDATION_EXPRESSION)) { // return -1; // } // // return Integer.valueOf(value.split(":|/")[1]); // } // }
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Handler; import android.preference.PreferenceManager; import android.util.Pair; import ca.psiphon.ploggy.widgets.TimePickerPreference; import com.squareup.otto.Subscribe;
public synchronized boolean getBooleanPreference(int keyResID) throws Utils.ApplicationError { String key = mContext.getString(keyResID); // Defaults which are "false" are not present in the preferences file // if (!mSharedPreferences.contains(key)) {...} // TODO: this is ambiguous: there's now no test for failure to initialize defaults return mSharedPreferences.getBoolean(key, false); } public synchronized int getIntPreference(int keyResID) throws Utils.ApplicationError { String key = mContext.getString(keyResID); if (!mSharedPreferences.contains(key)) { throw new Utils.ApplicationError(LOG_TAG, "missing preference default: " + key); } return mSharedPreferences.getInt(key, 0); } public synchronized boolean currentlySharingLocation() throws Utils.ApplicationError { if (!getBooleanPreference(R.string.preferenceAutomaticLocationSharing)) { return false; } Calendar now = Calendar.getInstance(); if (getBooleanPreference(R.string.preferenceLimitLocationSharingTime)) { int currentHour = now.get(Calendar.HOUR_OF_DAY); int currentMinute = now.get(Calendar.MINUTE); String sharingTimeNotBefore = mSharedPreferences.getString( mContext.getString(R.string.preferenceLimitLocationSharingTimeNotBefore), "");
// Path: AndroidApp/src/ca/psiphon/ploggy/widgets/TimePickerPreference.java // public class TimePickerPreference extends DialogPreference implements // TimePicker.OnTimeChangedListener { // // /** // * The validation expression for this preference // */ // private static final String VALIDATION_EXPRESSION = "[0-2]*[0-9]:[0-5]*[0-9]"; // // /** // * The default value for this preference // */ // private final String defaultValue; // private String result; // private TimePicker tp; // // /** // * @param context // * @param attrs // */ // public TimePickerPreference(Context context, AttributeSet attrs) { // super(context, attrs); // defaultValue = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "defaultValue"); // initialize(); // } // // /** // * @param context // * @param attrs // * @param defStyle // */ // public TimePickerPreference(Context context, AttributeSet attrs, // int defStyle) { // super(context, attrs, defStyle); // defaultValue = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "defaultValue"); // initialize(); // } // // /** // * Initialize this preference // */ // private void initialize() { // setPersistent(true); // } // // /* // * (non-Javadoc) // * // * @see android.preference.DialogPreference#onCreateDialogView() // */ // @Override // protected View onCreateDialogView() { // // tp = new TimePicker(getContext()); // tp.setOnTimeChangedListener(this); // // String value = getPersistedString(this.defaultValue); // int h = getHour(value); // int m = getMinute(value); // if (h >= 0 && m >= 0) { // tp.setCurrentHour(h); // tp.setCurrentMinute(m); // } // tp.setIs24HourView(DateFormat.is24HourFormat(getContext())); // // return tp; // } // // /* // * (non-Javadoc) // * // * @see // * android.widget.TimePicker.OnTimeChangedListener#onTimeChanged(android // * .widget.TimePicker, int, int) // */ // // @Override // public void onTimeChanged(TimePicker view, int hour, int minute) { // result = hour + ":" + minute; // } // // /* // * (non-Javadoc) // * // * @see // * android.preference.DialogPreference#onDismiss(android.content.DialogInterface // * ) // */ // @Override // public void onDismiss(DialogInterface dialog) { // super.onDismiss(dialog); // } // // /* // * (non-Javadoc) // * // * @see android.preference.DialogPreference#onDialogClosed(boolean) // */ // @Override // protected void onDialogClosed(boolean positiveResult) { // super.onDialogClosed(positiveResult); // if (positiveResult) { // tp.clearFocus(); // to get value of number if edited in text field, and clicking OK without clicking outside the field first (bug in NumberPicker) // result = tp.getCurrentHour() + ":" + tp.getCurrentMinute(); // persistString(result); // callChangeListener(result); // } // } // // /** // * Get the hour value (in 24 hour time) // * // * @return The hour value, will be 0 to 23 (inclusive) // */ // public static int getHour(String value) { // if (value == null || !value.matches(VALIDATION_EXPRESSION)) { // return -1; // } // // return Integer.valueOf(value.split(":|/")[0]); // } // // /** // * Get the minute value // * // * @return the minute value, will be 0 to 59 (inclusive) // */ // public static int getMinute(String value) { // if (value == null || !value.matches(VALIDATION_EXPRESSION)) { // return -1; // } // // return Integer.valueOf(value.split(":|/")[1]); // } // } // Path: AndroidApp/src/ca/psiphon/ploggy/Engine.java import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Handler; import android.preference.PreferenceManager; import android.util.Pair; import ca.psiphon.ploggy.widgets.TimePickerPreference; import com.squareup.otto.Subscribe; public synchronized boolean getBooleanPreference(int keyResID) throws Utils.ApplicationError { String key = mContext.getString(keyResID); // Defaults which are "false" are not present in the preferences file // if (!mSharedPreferences.contains(key)) {...} // TODO: this is ambiguous: there's now no test for failure to initialize defaults return mSharedPreferences.getBoolean(key, false); } public synchronized int getIntPreference(int keyResID) throws Utils.ApplicationError { String key = mContext.getString(keyResID); if (!mSharedPreferences.contains(key)) { throw new Utils.ApplicationError(LOG_TAG, "missing preference default: " + key); } return mSharedPreferences.getInt(key, 0); } public synchronized boolean currentlySharingLocation() throws Utils.ApplicationError { if (!getBooleanPreference(R.string.preferenceAutomaticLocationSharing)) { return false; } Calendar now = Calendar.getInstance(); if (getBooleanPreference(R.string.preferenceLimitLocationSharingTime)) { int currentHour = now.get(Calendar.HOUR_OF_DAY); int currentMinute = now.get(Calendar.MINUTE); String sharingTimeNotBefore = mSharedPreferences.getString( mContext.getString(R.string.preferenceLimitLocationSharingTimeNotBefore), "");
int notBeforeHour = TimePickerPreference.getHour(sharingTimeNotBefore);
Psiphon-Labs/ploggy
AndroidApp/src/ca/psiphon/ploggy/Utils.java
// Path: AndroidApp/src/de/schildbach/wallet/util/LinuxSecureRandom.java // public class LinuxSecureRandom extends SecureRandomSpi // { // private static final long serialVersionUID = -6575880163829115605L; // private static final FileInputStream urandom; // // private static class LinuxSecureRandomProvider extends Provider // { // private static final long serialVersionUID = -3366530978335459636L; // // public LinuxSecureRandomProvider() // { // super("LinuxSecureRandom", 1.0, "A Linux specific random number provider that uses /dev/urandom"); // put("SecureRandom.LinuxSecureRandom", LinuxSecureRandom.class.getName()); // } // } // // static // { // try // { // File file = new File("/dev/urandom"); // if (file.exists()) // { // // This stream is deliberately leaked. // urandom = new FileInputStream(file); // // Now override the default SecureRandom implementation with this one. // Security.insertProviderAt(new LinuxSecureRandomProvider(), 1); // } // else // { // urandom = null; // } // } // catch (FileNotFoundException e) // { // // Should never happen. // throw new RuntimeException(e); // } // } // // private final DataInputStream dis; // // public LinuxSecureRandom() // { // // DataInputStream is not thread safe, so each random object has its own. // dis = new DataInputStream(urandom); // } // // @Override // protected void engineSetSeed(byte[] bytes) // { // // Ignore. // } // // @Override // protected void engineNextBytes(byte[] bytes) // { // try // { // dis.readFully(bytes); // This will block until all the bytes can be read. // } // catch (IOException e) // { // throw new RuntimeException(e); // Fatal error. Do not attempt to recover from this. // } // } // // @Override // protected byte[] engineGenerateSeed(int i) // { // byte[] bits = new byte[i]; // engineNextBytes(bits); // return bits; // } // }
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.security.SecureRandom; import java.text.DateFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.location.Location; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.FileObserver; import android.os.Handler; import android.util.Base64; import android.view.View; import android.view.inputmethod.InputMethodManager; import de.schildbach.wallet.util.LinuxSecureRandom;
// writes to that file, then renames to <target>. There's no CLOSE_WRITE event for <target>. super( directory.getAbsolutePath(), FileObserver.MOVED_TO | FileObserver.CLOSE_WRITE); mTargetFilenames = new ArrayList<String>(Arrays.asList(filenames)); mLatch = new CountDownLatch(mTargetFilenames.size()); } @Override public void onEvent(int event, String path) { if (path != null) { for (int i = 0; i < mTargetFilenames.size(); i++) { if (path.equals(mTargetFilenames.get(i))) { mTargetFilenames.remove(i); mLatch.countDown(); if (mTargetFilenames.size() == 0) { stopWatching(); } break; } } } } public boolean await(long timeoutMilliseconds) throws InterruptedException { return mLatch.await(timeoutMilliseconds, TimeUnit.MILLISECONDS); } } public static void initSecureRandom() {
// Path: AndroidApp/src/de/schildbach/wallet/util/LinuxSecureRandom.java // public class LinuxSecureRandom extends SecureRandomSpi // { // private static final long serialVersionUID = -6575880163829115605L; // private static final FileInputStream urandom; // // private static class LinuxSecureRandomProvider extends Provider // { // private static final long serialVersionUID = -3366530978335459636L; // // public LinuxSecureRandomProvider() // { // super("LinuxSecureRandom", 1.0, "A Linux specific random number provider that uses /dev/urandom"); // put("SecureRandom.LinuxSecureRandom", LinuxSecureRandom.class.getName()); // } // } // // static // { // try // { // File file = new File("/dev/urandom"); // if (file.exists()) // { // // This stream is deliberately leaked. // urandom = new FileInputStream(file); // // Now override the default SecureRandom implementation with this one. // Security.insertProviderAt(new LinuxSecureRandomProvider(), 1); // } // else // { // urandom = null; // } // } // catch (FileNotFoundException e) // { // // Should never happen. // throw new RuntimeException(e); // } // } // // private final DataInputStream dis; // // public LinuxSecureRandom() // { // // DataInputStream is not thread safe, so each random object has its own. // dis = new DataInputStream(urandom); // } // // @Override // protected void engineSetSeed(byte[] bytes) // { // // Ignore. // } // // @Override // protected void engineNextBytes(byte[] bytes) // { // try // { // dis.readFully(bytes); // This will block until all the bytes can be read. // } // catch (IOException e) // { // throw new RuntimeException(e); // Fatal error. Do not attempt to recover from this. // } // } // // @Override // protected byte[] engineGenerateSeed(int i) // { // byte[] bits = new byte[i]; // engineNextBytes(bits); // return bits; // } // } // Path: AndroidApp/src/ca/psiphon/ploggy/Utils.java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.security.SecureRandom; import java.text.DateFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.location.Location; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.FileObserver; import android.os.Handler; import android.util.Base64; import android.view.View; import android.view.inputmethod.InputMethodManager; import de.schildbach.wallet.util.LinuxSecureRandom; // writes to that file, then renames to <target>. There's no CLOSE_WRITE event for <target>. super( directory.getAbsolutePath(), FileObserver.MOVED_TO | FileObserver.CLOSE_WRITE); mTargetFilenames = new ArrayList<String>(Arrays.asList(filenames)); mLatch = new CountDownLatch(mTargetFilenames.size()); } @Override public void onEvent(int event, String path) { if (path != null) { for (int i = 0; i < mTargetFilenames.size(); i++) { if (path.equals(mTargetFilenames.get(i))) { mTargetFilenames.remove(i); mLatch.countDown(); if (mTargetFilenames.size() == 0) { stopWatching(); } break; } } } } public boolean await(long timeoutMilliseconds) throws InterruptedException { return mLatch.await(timeoutMilliseconds, TimeUnit.MILLISECONDS); } } public static void initSecureRandom() {
new LinuxSecureRandom();
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/index/JresRefresh.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresShardsReply.java // public class JresShardsReply extends JresJsonReply { // // @JsonProperty("_shards") // private Shards shards; // // public Shards getShards() { // return shards; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.common.JresShardsReply; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpPost;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresRefresh extends JresJsonRequest<JresShardsReply> { private final String index; public JresRefresh(String index) { super(JresShardsReply.class); this.index = index; } @Override public String getHttpMethod() { return HttpPost.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresShardsReply.java // public class JresShardsReply extends JresJsonReply { // // @JsonProperty("_shards") // private Shards shards; // // public Shards getShards() { // return shards; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresRefresh.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.common.JresShardsReply; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpPost; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresRefresh extends JresJsonRequest<JresShardsReply> { private final String index; public JresRefresh(String index) { super(JresShardsReply.class); this.index = index; } @Override public String getHttpMethod() { return HttpPost.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(index) + "_refresh";
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/alias/JresRetrieveAliasesTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresRetrieveAliasesTest extends BaseJresTest { @Test(expected = JresErrorReplyException.class) public void sad() { String index = "JresRetrieveAliasesRequestTest".toLowerCase(); String alias = index + "_alias"; // no matches returns 404 response jres.quest(new JresRetrieveAliases(index, alias)); } @Test public void happy() { String index = "JresRetrieveAliasesRequestTest_happy".toLowerCase(); String alias = index + "_alias";
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/alias/JresRetrieveAliasesTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresRetrieveAliasesTest extends BaseJresTest { @Test(expected = JresErrorReplyException.class) public void sad() { String index = "JresRetrieveAliasesRequestTest".toLowerCase(); String alias = index + "_alias"; // no matches returns 404 response jres.quest(new JresRetrieveAliases(index, alias)); } @Test public void happy() { String index = "JresRetrieveAliasesRequestTest_happy".toLowerCase(); String alias = index + "_alias";
jres.quest(new JresCreateIndex(index));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/alias/JresRetrieveAliasesTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresRetrieveAliasesTest extends BaseJresTest { @Test(expected = JresErrorReplyException.class) public void sad() { String index = "JresRetrieveAliasesRequestTest".toLowerCase(); String alias = index + "_alias"; // no matches returns 404 response jres.quest(new JresRetrieveAliases(index, alias)); } @Test public void happy() { String index = "JresRetrieveAliasesRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); jres.quest(new JresAddAlias(index, alias));
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/alias/JresRetrieveAliasesTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresRetrieveAliasesTest extends BaseJresTest { @Test(expected = JresErrorReplyException.class) public void sad() { String index = "JresRetrieveAliasesRequestTest".toLowerCase(); String alias = index + "_alias"; // no matches returns 404 response jres.quest(new JresRetrieveAliases(index, alias)); } @Test public void happy() { String index = "JresRetrieveAliasesRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); jres.quest(new JresAddAlias(index, alias));
JresRetrieveAliasesReply response = jres.quest(new JresRetrieveAliases(index, "*"));
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/search/query/JresMatchAllQuery.java
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Collections; import java.util.Map;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search.query; public class JresMatchAllQuery implements JresQuery { private final Map<Object, Object> value = Collections.emptyMap(); @Override public String queryType() { return "match_all"; } @JsonValue public Map<Object, Object> getValue() { return value; } @Override public String toString() {
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/search/query/JresMatchAllQuery.java import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Collections; import java.util.Map; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search.query; public class JresMatchAllQuery implements JresQuery { private final Map<Object, Object> value = Collections.emptyMap(); @Override public String queryType() { return "match_all"; } @JsonValue public Map<Object, Object> getValue() { return value; } @Override public String toString() {
return ObjectMappers.toJson(this);
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/response/common/JresShardsReply.java
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Shards.java // public class Shards { // // private Integer total; // // private Integer successful; // // private Integer failed; // // public Integer getTotal() { // return total; // } // // public Integer getSuccessful() { // return successful; // } // // public Integer getFailed() { // return failed; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // }
import com.blacklocus.jres.model.Shards; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.common; public class JresShardsReply extends JresJsonReply { @JsonProperty("_shards")
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Shards.java // public class Shards { // // private Integer total; // // private Integer successful; // // private Integer failed; // // public Integer getTotal() { // return total; // } // // public Integer getSuccessful() { // return successful; // } // // public Integer getFailed() { // return failed; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresShardsReply.java import com.blacklocus.jres.model.Shards; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.common; public class JresShardsReply extends JresJsonReply { @JsonProperty("_shards")
private Shards shards;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/index/JresIndexExists.java
// Path: jres-core/src/main/java/com/blacklocus/jres/handler/JresPredicates.java // public class JresPredicates { // // public static final Predicate<HttpResponse> STATUS_200 = new Predicate<HttpResponse>() { // @Override // public boolean apply(HttpResponse input) { // return input.getStatusLine().getStatusCode() == 200; // } // }; // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/JresBooleanRequest.java // public abstract class JresBooleanRequest extends JresJsonRequest<JresBooleanReply> { // // protected JresBooleanRequest() { // super(JresBooleanReply.class); // } // // public abstract Predicate<HttpResponse> getPredicate(); // }
import com.blacklocus.jres.handler.JresPredicates; import com.blacklocus.jres.request.JresBooleanRequest; import com.google.common.base.Predicate; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpHead;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-exists.html#indices-exists">Index Exists API</a> */ public class JresIndexExists extends JresBooleanRequest { private final String index; public JresIndexExists(String index) { this.index = index; } @Override public String getHttpMethod() { return HttpHead.METHOD_NAME; } @Override public String getPath() { return index; } @Override public Object getPayload() { return null; } @Override public Predicate<HttpResponse> getPredicate() {
// Path: jres-core/src/main/java/com/blacklocus/jres/handler/JresPredicates.java // public class JresPredicates { // // public static final Predicate<HttpResponse> STATUS_200 = new Predicate<HttpResponse>() { // @Override // public boolean apply(HttpResponse input) { // return input.getStatusLine().getStatusCode() == 200; // } // }; // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/JresBooleanRequest.java // public abstract class JresBooleanRequest extends JresJsonRequest<JresBooleanReply> { // // protected JresBooleanRequest() { // super(JresBooleanReply.class); // } // // public abstract Predicate<HttpResponse> getPredicate(); // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresIndexExists.java import com.blacklocus.jres.handler.JresPredicates; import com.blacklocus.jres.request.JresBooleanRequest; import com.google.common.base.Predicate; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpHead; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-exists.html#indices-exists">Index Exists API</a> */ public class JresIndexExists extends JresBooleanRequest { private final String index; public JresIndexExists(String index) { this.index = index; } @Override public String getHttpMethod() { return HttpHead.METHOD_NAME; } @Override public String getPath() { return index; } @Override public Object getPayload() { return null; } @Override public Predicate<HttpResponse> getPredicate() {
return JresPredicates.STATUS_200;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/mapping/JresGetMapping.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.JresJsonReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpGet;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-get-mapping.html#indices-get-mapping">Get Mapping API</a> * <p> * Can throw {@link JresErrorReplyException} */ public class JresGetMapping extends JresJsonRequest<JresJsonReply> { private final String index; private final String type; public JresGetMapping(String index, String type) { super(JresJsonReply.class); this.index = index; this.type = type; } @Override public String getHttpMethod() { return HttpGet.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/mapping/JresGetMapping.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.JresJsonReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpGet; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-get-mapping.html#indices-get-mapping">Get Mapping API</a> * <p> * Can throw {@link JresErrorReplyException} */ public class JresGetMapping extends JresJsonRequest<JresJsonReply> { private final String index; private final String type; public JresGetMapping(String index, String type) { super(JresJsonReply.class); this.index = index; this.type = type; } @Override public String getHttpMethod() { return HttpGet.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(index) + JresPaths.slashedPath(type) + "_mapping";
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/response/search/JresSearchReply.java
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Shards.java // public class Shards { // // private Integer total; // // private Integer successful; // // private Integer failed; // // public Integer getTotal() { // return total; // } // // public Integer getSuccessful() { // return successful; // } // // public Integer getFailed() { // return failed; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Facets.java // public class Facets extends HashMap<String, JsonNode> { // // public <T extends Facet> T get(String facetName, Class<T> klass) { // return ObjectMappers.fromJson(get(facetName), klass); // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hit.java // public class Hit { // // @JsonProperty("_index") // private String index; // // @JsonProperty("_type") // private String type; // // @JsonProperty("_id") // private String id; // // @JsonProperty("_score") // private Double score; // // @JsonProperty("_source") // private JsonNode source; // // // public String getIndex() { // return index; // } // // public String getType() { // return type; // } // // public String getId() { // return id; // } // // public Double getScore() { // return score; // } // // public JsonNode getSource() { // return source; // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(Class<T> klass) { // return source == null ? null : ObjectMappers.fromJson(source, klass); // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(TypeReference<T> typeReference) { // return source == null ? null : ObjectMappers.fromJson(source, typeReference); // } // // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("index", index) // .add("type", type) // .add("id", id) // .add("score", score) // .add("source", ObjectMappers.toJsonPretty(source)) // .toString(); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hits.java // public class Hits { // // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // private List<Hit> hits; // // public Long getTotal() { // return total; // } // // public Double getMaxScore() { // return maxScore; // } // // public List<Hit> getHits() { // return hits; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // }
import com.blacklocus.jres.model.Shards; import com.blacklocus.jres.model.search.Facets; import com.blacklocus.jres.model.search.Hit; import com.blacklocus.jres.model.search.Hits; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Function; import com.google.common.collect.Lists; import java.util.List;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.search; public class JresSearchReply extends JresJsonReply { private Integer took; @JsonProperty("timed_out") private Boolean timedOut; @JsonProperty("_shards")
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Shards.java // public class Shards { // // private Integer total; // // private Integer successful; // // private Integer failed; // // public Integer getTotal() { // return total; // } // // public Integer getSuccessful() { // return successful; // } // // public Integer getFailed() { // return failed; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Facets.java // public class Facets extends HashMap<String, JsonNode> { // // public <T extends Facet> T get(String facetName, Class<T> klass) { // return ObjectMappers.fromJson(get(facetName), klass); // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hit.java // public class Hit { // // @JsonProperty("_index") // private String index; // // @JsonProperty("_type") // private String type; // // @JsonProperty("_id") // private String id; // // @JsonProperty("_score") // private Double score; // // @JsonProperty("_source") // private JsonNode source; // // // public String getIndex() { // return index; // } // // public String getType() { // return type; // } // // public String getId() { // return id; // } // // public Double getScore() { // return score; // } // // public JsonNode getSource() { // return source; // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(Class<T> klass) { // return source == null ? null : ObjectMappers.fromJson(source, klass); // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(TypeReference<T> typeReference) { // return source == null ? null : ObjectMappers.fromJson(source, typeReference); // } // // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("index", index) // .add("type", type) // .add("id", id) // .add("score", score) // .add("source", ObjectMappers.toJsonPretty(source)) // .toString(); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hits.java // public class Hits { // // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // private List<Hit> hits; // // public Long getTotal() { // return total; // } // // public Double getMaxScore() { // return maxScore; // } // // public List<Hit> getHits() { // return hits; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // Path: jres-core/src/main/java/com/blacklocus/jres/response/search/JresSearchReply.java import com.blacklocus.jres.model.Shards; import com.blacklocus.jres.model.search.Facets; import com.blacklocus.jres.model.search.Hit; import com.blacklocus.jres.model.search.Hits; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Function; import com.google.common.collect.Lists; import java.util.List; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.search; public class JresSearchReply extends JresJsonReply { private Integer took; @JsonProperty("timed_out") private Boolean timedOut; @JsonProperty("_shards")
private Shards shards;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/response/search/JresSearchReply.java
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Shards.java // public class Shards { // // private Integer total; // // private Integer successful; // // private Integer failed; // // public Integer getTotal() { // return total; // } // // public Integer getSuccessful() { // return successful; // } // // public Integer getFailed() { // return failed; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Facets.java // public class Facets extends HashMap<String, JsonNode> { // // public <T extends Facet> T get(String facetName, Class<T> klass) { // return ObjectMappers.fromJson(get(facetName), klass); // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hit.java // public class Hit { // // @JsonProperty("_index") // private String index; // // @JsonProperty("_type") // private String type; // // @JsonProperty("_id") // private String id; // // @JsonProperty("_score") // private Double score; // // @JsonProperty("_source") // private JsonNode source; // // // public String getIndex() { // return index; // } // // public String getType() { // return type; // } // // public String getId() { // return id; // } // // public Double getScore() { // return score; // } // // public JsonNode getSource() { // return source; // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(Class<T> klass) { // return source == null ? null : ObjectMappers.fromJson(source, klass); // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(TypeReference<T> typeReference) { // return source == null ? null : ObjectMappers.fromJson(source, typeReference); // } // // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("index", index) // .add("type", type) // .add("id", id) // .add("score", score) // .add("source", ObjectMappers.toJsonPretty(source)) // .toString(); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hits.java // public class Hits { // // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // private List<Hit> hits; // // public Long getTotal() { // return total; // } // // public Double getMaxScore() { // return maxScore; // } // // public List<Hit> getHits() { // return hits; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // }
import com.blacklocus.jres.model.Shards; import com.blacklocus.jres.model.search.Facets; import com.blacklocus.jres.model.search.Hit; import com.blacklocus.jres.model.search.Hits; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Function; import com.google.common.collect.Lists; import java.util.List;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.search; public class JresSearchReply extends JresJsonReply { private Integer took; @JsonProperty("timed_out") private Boolean timedOut; @JsonProperty("_shards") private Shards shards;
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Shards.java // public class Shards { // // private Integer total; // // private Integer successful; // // private Integer failed; // // public Integer getTotal() { // return total; // } // // public Integer getSuccessful() { // return successful; // } // // public Integer getFailed() { // return failed; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Facets.java // public class Facets extends HashMap<String, JsonNode> { // // public <T extends Facet> T get(String facetName, Class<T> klass) { // return ObjectMappers.fromJson(get(facetName), klass); // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hit.java // public class Hit { // // @JsonProperty("_index") // private String index; // // @JsonProperty("_type") // private String type; // // @JsonProperty("_id") // private String id; // // @JsonProperty("_score") // private Double score; // // @JsonProperty("_source") // private JsonNode source; // // // public String getIndex() { // return index; // } // // public String getType() { // return type; // } // // public String getId() { // return id; // } // // public Double getScore() { // return score; // } // // public JsonNode getSource() { // return source; // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(Class<T> klass) { // return source == null ? null : ObjectMappers.fromJson(source, klass); // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(TypeReference<T> typeReference) { // return source == null ? null : ObjectMappers.fromJson(source, typeReference); // } // // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("index", index) // .add("type", type) // .add("id", id) // .add("score", score) // .add("source", ObjectMappers.toJsonPretty(source)) // .toString(); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hits.java // public class Hits { // // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // private List<Hit> hits; // // public Long getTotal() { // return total; // } // // public Double getMaxScore() { // return maxScore; // } // // public List<Hit> getHits() { // return hits; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // Path: jres-core/src/main/java/com/blacklocus/jres/response/search/JresSearchReply.java import com.blacklocus.jres.model.Shards; import com.blacklocus.jres.model.search.Facets; import com.blacklocus.jres.model.search.Hit; import com.blacklocus.jres.model.search.Hits; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Function; import com.google.common.collect.Lists; import java.util.List; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.search; public class JresSearchReply extends JresJsonReply { private Integer took; @JsonProperty("timed_out") private Boolean timedOut; @JsonProperty("_shards") private Shards shards;
private Hits hits;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/response/search/JresSearchReply.java
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Shards.java // public class Shards { // // private Integer total; // // private Integer successful; // // private Integer failed; // // public Integer getTotal() { // return total; // } // // public Integer getSuccessful() { // return successful; // } // // public Integer getFailed() { // return failed; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Facets.java // public class Facets extends HashMap<String, JsonNode> { // // public <T extends Facet> T get(String facetName, Class<T> klass) { // return ObjectMappers.fromJson(get(facetName), klass); // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hit.java // public class Hit { // // @JsonProperty("_index") // private String index; // // @JsonProperty("_type") // private String type; // // @JsonProperty("_id") // private String id; // // @JsonProperty("_score") // private Double score; // // @JsonProperty("_source") // private JsonNode source; // // // public String getIndex() { // return index; // } // // public String getType() { // return type; // } // // public String getId() { // return id; // } // // public Double getScore() { // return score; // } // // public JsonNode getSource() { // return source; // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(Class<T> klass) { // return source == null ? null : ObjectMappers.fromJson(source, klass); // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(TypeReference<T> typeReference) { // return source == null ? null : ObjectMappers.fromJson(source, typeReference); // } // // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("index", index) // .add("type", type) // .add("id", id) // .add("score", score) // .add("source", ObjectMappers.toJsonPretty(source)) // .toString(); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hits.java // public class Hits { // // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // private List<Hit> hits; // // public Long getTotal() { // return total; // } // // public Double getMaxScore() { // return maxScore; // } // // public List<Hit> getHits() { // return hits; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // }
import com.blacklocus.jres.model.Shards; import com.blacklocus.jres.model.search.Facets; import com.blacklocus.jres.model.search.Hit; import com.blacklocus.jres.model.search.Hits; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Function; import com.google.common.collect.Lists; import java.util.List;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.search; public class JresSearchReply extends JresJsonReply { private Integer took; @JsonProperty("timed_out") private Boolean timedOut; @JsonProperty("_shards") private Shards shards; private Hits hits;
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Shards.java // public class Shards { // // private Integer total; // // private Integer successful; // // private Integer failed; // // public Integer getTotal() { // return total; // } // // public Integer getSuccessful() { // return successful; // } // // public Integer getFailed() { // return failed; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Facets.java // public class Facets extends HashMap<String, JsonNode> { // // public <T extends Facet> T get(String facetName, Class<T> klass) { // return ObjectMappers.fromJson(get(facetName), klass); // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hit.java // public class Hit { // // @JsonProperty("_index") // private String index; // // @JsonProperty("_type") // private String type; // // @JsonProperty("_id") // private String id; // // @JsonProperty("_score") // private Double score; // // @JsonProperty("_source") // private JsonNode source; // // // public String getIndex() { // return index; // } // // public String getType() { // return type; // } // // public String getId() { // return id; // } // // public Double getScore() { // return score; // } // // public JsonNode getSource() { // return source; // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(Class<T> klass) { // return source == null ? null : ObjectMappers.fromJson(source, klass); // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(TypeReference<T> typeReference) { // return source == null ? null : ObjectMappers.fromJson(source, typeReference); // } // // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("index", index) // .add("type", type) // .add("id", id) // .add("score", score) // .add("source", ObjectMappers.toJsonPretty(source)) // .toString(); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hits.java // public class Hits { // // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // private List<Hit> hits; // // public Long getTotal() { // return total; // } // // public Double getMaxScore() { // return maxScore; // } // // public List<Hit> getHits() { // return hits; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // Path: jres-core/src/main/java/com/blacklocus/jres/response/search/JresSearchReply.java import com.blacklocus.jres.model.Shards; import com.blacklocus.jres.model.search.Facets; import com.blacklocus.jres.model.search.Hit; import com.blacklocus.jres.model.search.Hits; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Function; import com.google.common.collect.Lists; import java.util.List; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.search; public class JresSearchReply extends JresJsonReply { private Integer took; @JsonProperty("timed_out") private Boolean timedOut; @JsonProperty("_shards") private Shards shards; private Hits hits;
private Facets facets;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/response/search/JresSearchReply.java
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Shards.java // public class Shards { // // private Integer total; // // private Integer successful; // // private Integer failed; // // public Integer getTotal() { // return total; // } // // public Integer getSuccessful() { // return successful; // } // // public Integer getFailed() { // return failed; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Facets.java // public class Facets extends HashMap<String, JsonNode> { // // public <T extends Facet> T get(String facetName, Class<T> klass) { // return ObjectMappers.fromJson(get(facetName), klass); // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hit.java // public class Hit { // // @JsonProperty("_index") // private String index; // // @JsonProperty("_type") // private String type; // // @JsonProperty("_id") // private String id; // // @JsonProperty("_score") // private Double score; // // @JsonProperty("_source") // private JsonNode source; // // // public String getIndex() { // return index; // } // // public String getType() { // return type; // } // // public String getId() { // return id; // } // // public Double getScore() { // return score; // } // // public JsonNode getSource() { // return source; // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(Class<T> klass) { // return source == null ? null : ObjectMappers.fromJson(source, klass); // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(TypeReference<T> typeReference) { // return source == null ? null : ObjectMappers.fromJson(source, typeReference); // } // // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("index", index) // .add("type", type) // .add("id", id) // .add("score", score) // .add("source", ObjectMappers.toJsonPretty(source)) // .toString(); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hits.java // public class Hits { // // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // private List<Hit> hits; // // public Long getTotal() { // return total; // } // // public Double getMaxScore() { // return maxScore; // } // // public List<Hit> getHits() { // return hits; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // }
import com.blacklocus.jres.model.Shards; import com.blacklocus.jres.model.search.Facets; import com.blacklocus.jres.model.search.Hit; import com.blacklocus.jres.model.search.Hits; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Function; import com.google.common.collect.Lists; import java.util.List;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.search; public class JresSearchReply extends JresJsonReply { private Integer took; @JsonProperty("timed_out") private Boolean timedOut; @JsonProperty("_shards") private Shards shards; private Hits hits; private Facets facets; public Integer getTook() { return took; } public Boolean isTimedOut() { return timedOut; } public Shards getShards() { return shards; } public Hits getHits() { return hits; } public Facets getFacets() { return facets; } /** * Shortcut to {@link Hit#getSourceAsType(Class)} */ public <T> List<T> getHitsAsType(final Class<T> klass) {
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Shards.java // public class Shards { // // private Integer total; // // private Integer successful; // // private Integer failed; // // public Integer getTotal() { // return total; // } // // public Integer getSuccessful() { // return successful; // } // // public Integer getFailed() { // return failed; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Facets.java // public class Facets extends HashMap<String, JsonNode> { // // public <T extends Facet> T get(String facetName, Class<T> klass) { // return ObjectMappers.fromJson(get(facetName), klass); // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hit.java // public class Hit { // // @JsonProperty("_index") // private String index; // // @JsonProperty("_type") // private String type; // // @JsonProperty("_id") // private String id; // // @JsonProperty("_score") // private Double score; // // @JsonProperty("_source") // private JsonNode source; // // // public String getIndex() { // return index; // } // // public String getType() { // return type; // } // // public String getId() { // return id; // } // // public Double getScore() { // return score; // } // // public JsonNode getSource() { // return source; // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(Class<T> klass) { // return source == null ? null : ObjectMappers.fromJson(source, klass); // } // // /** // * May return <code>null</code> if source was not available. // */ // public <T> T getSourceAsType(TypeReference<T> typeReference) { // return source == null ? null : ObjectMappers.fromJson(source, typeReference); // } // // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("index", index) // .add("type", type) // .add("id", id) // .add("score", score) // .add("source", ObjectMappers.toJsonPretty(source)) // .toString(); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hits.java // public class Hits { // // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // private List<Hit> hits; // // public Long getTotal() { // return total; // } // // public Double getMaxScore() { // return maxScore; // } // // public List<Hit> getHits() { // return hits; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // Path: jres-core/src/main/java/com/blacklocus/jres/response/search/JresSearchReply.java import com.blacklocus.jres.model.Shards; import com.blacklocus.jres.model.search.Facets; import com.blacklocus.jres.model.search.Hit; import com.blacklocus.jres.model.search.Hits; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Function; import com.google.common.collect.Lists; import java.util.List; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.search; public class JresSearchReply extends JresJsonReply { private Integer took; @JsonProperty("timed_out") private Boolean timedOut; @JsonProperty("_shards") private Shards shards; private Hits hits; private Facets facets; public Integer getTook() { return took; } public Boolean isTimedOut() { return timedOut; } public Shards getShards() { return shards; } public Hits getHits() { return hits; } public Facets getFacets() { return facets; } /** * Shortcut to {@link Hit#getSourceAsType(Class)} */ public <T> List<T> getHitsAsType(final Class<T> klass) {
return Lists.transform(getHits().getHits(), new Function<Hit, T>() {
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/response/document/JresGetDocumentReply.java
// Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.response.JresJsonReply; import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode;
private Boolean found; @JsonProperty("_source") private JsonNode source; public String getIndex() { return index; } public String getType() { return type; } public String getId() { return id; } public Integer getVersion() { return version; } public Boolean getFound() { return found; } public JsonNode getSource() { return source; } public <T> T getSourceAsType(Class<T> klass) {
// Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/response/document/JresGetDocumentReply.java import com.blacklocus.jres.response.JresJsonReply; import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; private Boolean found; @JsonProperty("_source") private JsonNode source; public String getIndex() { return index; } public String getType() { return type; } public String getId() { return id; } public Integer getVersion() { return version; } public Boolean getFound() { return found; } public JsonNode getSource() { return source; } public <T> T getSourceAsType(Class<T> klass) {
return ObjectMappers.fromJson(source, klass);
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/search/query/JresMatchQuery.java
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.strings.ObjectMappers; import java.util.HashMap;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search.query; public class JresMatchQuery extends HashMap<String, Object> implements JresQuery { public JresMatchQuery() { } public JresMatchQuery(String field, Object subquery) { put(field, subquery); } @Override public String queryType() { return "match"; } @Override public String toString() {
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/search/query/JresMatchQuery.java import com.blacklocus.jres.strings.ObjectMappers; import java.util.HashMap; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search.query; public class JresMatchQuery extends HashMap<String, Object> implements JresQuery { public JresMatchQuery() { } public JresMatchQuery(String field, Object subquery) { put(field, subquery); } @Override public String queryType() { return "match"; } @Override public String toString() {
return ObjectMappers.toJson(this);
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/alias/JresDeleteAlias.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpDelete;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-aliases.html#deleting">Delete Single Index Alias API</a> * <p> * This command will return successful even if the alias didn't exist. The index must still exist. * <p> * Can throw {@link JresErrorReplyException}. */ public class JresDeleteAlias extends JresJsonRequest<JresAcknowledgedReply> { private final String index; private final String alias; /** * @param index the actual index * @param alias another name by which the actual index may be addressed */ public JresDeleteAlias(String index, String alias) { super(JresAcknowledgedReply.class); this.index = index; this.alias = alias; } @Override public String getHttpMethod() { return HttpDelete.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/alias/JresDeleteAlias.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpDelete; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-aliases.html#deleting">Delete Single Index Alias API</a> * <p> * This command will return successful even if the alias didn't exist. The index must still exist. * <p> * Can throw {@link JresErrorReplyException}. */ public class JresDeleteAlias extends JresJsonRequest<JresAcknowledgedReply> { private final String index; private final String alias; /** * @param index the actual index * @param alias another name by which the actual index may be addressed */ public JresDeleteAlias(String index, String alias) { super(JresAcknowledgedReply.class); this.index = index; this.alias = alias; } @Override public String getHttpMethod() { return HttpDelete.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(index) + "_alias/" + alias;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/search/sort/JresFieldSort.java
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.strings.ObjectMappers;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search.sort; public class JresFieldSort implements JresSort { private final String field; private String order; public JresFieldSort(String field) { this.field = field; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public JresFieldSort withOrder(String order) { this.order = order; return this; } @Override public String sortType() { return field; } @Override public String toString() {
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/search/sort/JresFieldSort.java import com.blacklocus.jres.strings.ObjectMappers; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search.sort; public class JresFieldSort implements JresSort { private final String field; private String order; public JresFieldSort(String field) { this.field = field; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public JresFieldSort withOrder(String order) { this.order = order; return this; } @Override public String sortType() { return field; } @Override public String toString() {
return ObjectMappers.toJson(this);
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/model/search/Hit.java
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.MoreObjects;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.model.search; public class Hit { @JsonProperty("_index") private String index; @JsonProperty("_type") private String type; @JsonProperty("_id") private String id; @JsonProperty("_score") private Double score; @JsonProperty("_source") private JsonNode source; public String getIndex() { return index; } public String getType() { return type; } public String getId() { return id; } public Double getScore() { return score; } public JsonNode getSource() { return source; } /** * May return <code>null</code> if source was not available. */ public <T> T getSourceAsType(Class<T> klass) {
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Hit.java import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.MoreObjects; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.model.search; public class Hit { @JsonProperty("_index") private String index; @JsonProperty("_type") private String type; @JsonProperty("_id") private String id; @JsonProperty("_score") private Double score; @JsonProperty("_source") private JsonNode source; public String getIndex() { return index; } public String getType() { return type; } public String getId() { return id; } public Double getScore() { return score; } public JsonNode getSource() { return source; } /** * May return <code>null</code> if source was not available. */ public <T> T getSourceAsType(Class<T> klass) {
return source == null ? null : ObjectMappers.fromJson(source, klass);
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/alias/JresDeleteAliasTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresDeleteAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresDeleteAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias";
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/alias/JresDeleteAliasTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresDeleteAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresDeleteAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias";
jres.quest(new JresCreateIndex(index));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/alias/JresDeleteAliasTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresDeleteAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresDeleteAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); // Delete alias excepts if the alias doesn't exist. jres.tolerate(new JresDeleteAlias(index, alias), 404); jres.quest(new JresAddAlias(index, alias));
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/alias/JresDeleteAliasTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresDeleteAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresDeleteAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); // Delete alias excepts if the alias doesn't exist. jres.tolerate(new JresDeleteAlias(index, alias), 404); jres.quest(new JresAddAlias(index, alias));
JresRetrieveAliasesReply retrieveAliasesResponse = jres.quest(new JresRetrieveAliases(index, alias));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/alias/JresDeleteAliasTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresDeleteAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresDeleteAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); // Delete alias excepts if the alias doesn't exist. jres.tolerate(new JresDeleteAlias(index, alias), 404); jres.quest(new JresAddAlias(index, alias)); JresRetrieveAliasesReply retrieveAliasesResponse = jres.quest(new JresRetrieveAliases(index, alias)); Assert.assertEquals(Collections.singletonList(alias), retrieveAliasesResponse.getAliases(index));
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/alias/JresDeleteAliasTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresDeleteAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresDeleteAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); // Delete alias excepts if the alias doesn't exist. jres.tolerate(new JresDeleteAlias(index, alias), 404); jres.quest(new JresAddAlias(index, alias)); JresRetrieveAliasesReply retrieveAliasesResponse = jres.quest(new JresRetrieveAliases(index, alias)); Assert.assertEquals(Collections.singletonList(alias), retrieveAliasesResponse.getAliases(index));
JresAcknowledgedReply response = jres.quest(new JresDeleteAlias(index, alias));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/alias/JresDeleteAliasTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresDeleteAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresDeleteAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); // Delete alias excepts if the alias doesn't exist. jres.tolerate(new JresDeleteAlias(index, alias), 404); jres.quest(new JresAddAlias(index, alias)); JresRetrieveAliasesReply retrieveAliasesResponse = jres.quest(new JresRetrieveAliases(index, alias)); Assert.assertEquals(Collections.singletonList(alias), retrieveAliasesResponse.getAliases(index)); JresAcknowledgedReply response = jres.quest(new JresDeleteAlias(index, alias)); Assert.assertTrue(response.getAcknowledged()); retrieveAliasesResponse = jres.quest(new JresRetrieveAliases(index, "*")); Assert.assertEquals(0, retrieveAliasesResponse.getAliases(index).size()); }
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/alias/JresDeleteAliasTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresDeleteAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresDeleteAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); // Delete alias excepts if the alias doesn't exist. jres.tolerate(new JresDeleteAlias(index, alias), 404); jres.quest(new JresAddAlias(index, alias)); JresRetrieveAliasesReply retrieveAliasesResponse = jres.quest(new JresRetrieveAliases(index, alias)); Assert.assertEquals(Collections.singletonList(alias), retrieveAliasesResponse.getAliases(index)); JresAcknowledgedReply response = jres.quest(new JresDeleteAlias(index, alias)); Assert.assertTrue(response.getAcknowledged()); retrieveAliasesResponse = jres.quest(new JresRetrieveAliases(index, "*")); Assert.assertEquals(0, retrieveAliasesResponse.getAliases(index).size()); }
@Test(expected = JresErrorReplyException.class)
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/handler/JresPredicatedResponseHandler.java
// Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.google.common.base.Predicate; import org.apache.http.HttpResponse; import java.io.IOException;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.handler; public class JresPredicatedResponseHandler extends AbstractJresResponseHandler<JresBooleanReply> { private final Predicate<HttpResponse> predicate; public JresPredicatedResponseHandler(Predicate<HttpResponse> predicate) { super(JresBooleanReply.class); this.predicate = predicate; } @Override
// Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/handler/JresPredicatedResponseHandler.java import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.google.common.base.Predicate; import org.apache.http.HttpResponse; import java.io.IOException; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.handler; public class JresPredicatedResponseHandler extends AbstractJresResponseHandler<JresBooleanReply> { private final Predicate<HttpResponse> predicate; public JresPredicatedResponseHandler(Predicate<HttpResponse> predicate) { super(JresBooleanReply.class); this.predicate = predicate; } @Override
public JresBooleanReply handleResponse(HttpResponse http) throws IOException, JresErrorReplyException {
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/mapping/JresPutMapping.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpPut;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-put-mapping.html#indices-put-mapping">Put Mapping API</a> * <p> * Can throw {@link JresErrorReplyException}. */ public class JresPutMapping extends JresJsonRequest<JresAcknowledgedReply> { private final String index; private final String type; private final String mappingJson; public JresPutMapping(String index, String type) { this(index, type, String.format("{\"%s\":{}}", type)); } public JresPutMapping(String index, String type, String mappingJson) { super(JresAcknowledgedReply.class); this.index = index; this.type = type; this.mappingJson = mappingJson; } @Override public String getHttpMethod() { return HttpPut.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/mapping/JresPutMapping.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpPut; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-put-mapping.html#indices-put-mapping">Put Mapping API</a> * <p> * Can throw {@link JresErrorReplyException}. */ public class JresPutMapping extends JresJsonRequest<JresAcknowledgedReply> { private final String index; private final String type; private final String mappingJson; public JresPutMapping(String index, String type) { this(index, type, String.format("{\"%s\":{}}", type)); } public JresPutMapping(String index, String type, String mappingJson) { super(JresAcknowledgedReply.class); this.index = index; this.type = type; this.mappingJson = mappingJson; } @Override public String getHttpMethod() { return HttpPut.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(index) + JresPaths.slashedPath(type) + "_mapping";
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/index/JresRefreshTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresShardsReply.java // public class JresShardsReply extends JresJsonReply { // // @JsonProperty("_shards") // private Shards shards; // // public Shards getShards() { // return shards; // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.common.JresShardsReply; import org.junit.Assert; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresRefreshTest extends BaseJresTest { @Test public void test() { String index = "JresRefreshTest_test".toLowerCase(); jres.quest(new JresCreateIndex(index));
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresShardsReply.java // public class JresShardsReply extends JresJsonReply { // // @JsonProperty("_shards") // private Shards shards; // // public Shards getShards() { // return shards; // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/index/JresRefreshTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.common.JresShardsReply; import org.junit.Assert; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresRefreshTest extends BaseJresTest { @Test public void test() { String index = "JresRefreshTest_test".toLowerCase(); jres.quest(new JresCreateIndex(index));
JresShardsReply refreshReply = jres.quest(new JresRefresh(index));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresTypeExistsTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import org.junit.Assert; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresTypeExistsTest extends BaseJresTest { @Test public void happy() { String index = "JresTypeExistsRequestTest_happy".toLowerCase(); String type = "test";
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresTypeExistsTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import org.junit.Assert; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresTypeExistsTest extends BaseJresTest { @Test public void happy() { String index = "JresTypeExistsRequestTest_happy".toLowerCase(); String type = "test";
jres.quest(new JresCreateIndex(index));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresTypeExistsTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import org.junit.Assert; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresTypeExistsTest extends BaseJresTest { @Test public void happy() { String index = "JresTypeExistsRequestTest_happy".toLowerCase(); String type = "test"; jres.quest(new JresCreateIndex(index)); jres.quest(new JresPutMapping(index, type));
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresTypeExistsTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import org.junit.Assert; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresTypeExistsTest extends BaseJresTest { @Test public void happy() { String index = "JresTypeExistsRequestTest_happy".toLowerCase(); String type = "test"; jres.quest(new JresCreateIndex(index)); jres.quest(new JresPutMapping(index, type));
JresBooleanReply response = jres.bool(new JresTypeExists(index, type));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresGetMappingTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresGetMappingTest extends BaseJresTest { @Test(expected = JresErrorReplyException.class) public void sad() { String index = "JresGetMappingRequestTest_sad".toLowerCase(); String type = "test"; jres.quest(new JresGetMapping(index, type)); } @Test public void happy() { String index = "JresGetMappingRequestTest_happy".toLowerCase(); String type = "test";
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresGetMappingTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresGetMappingTest extends BaseJresTest { @Test(expected = JresErrorReplyException.class) public void sad() { String index = "JresGetMappingRequestTest_sad".toLowerCase(); String type = "test"; jres.quest(new JresGetMapping(index, type)); } @Test public void happy() { String index = "JresGetMappingRequestTest_happy".toLowerCase(); String type = "test";
jres.quest(new JresCreateIndex(index));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/index/JresFlushTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresShardsReply.java // public class JresShardsReply extends JresJsonReply { // // @JsonProperty("_shards") // private Shards shards; // // public Shards getShards() { // return shards; // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.common.JresShardsReply; import com.google.common.collect.ImmutableMap; import org.junit.Assert; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresFlushTest extends BaseJresTest { @Test public void test() { String index = "JresFlushTest_test".toLowerCase(); jres.quest(new JresCreateIndex(index));
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresShardsReply.java // public class JresShardsReply extends JresJsonReply { // // @JsonProperty("_shards") // private Shards shards; // // public Shards getShards() { // return shards; // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/index/JresFlushTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.common.JresShardsReply; import com.google.common.collect.ImmutableMap; import org.junit.Assert; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresFlushTest extends BaseJresTest { @Test public void test() { String index = "JresFlushTest_test".toLowerCase(); jres.quest(new JresCreateIndex(index));
JresShardsReply flushReply = jres.quest(new JresFlush(index));
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/index/JresGetIndexSettings.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.JresJsonReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpGet;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-get-settings.html#indices-get-settings">Get Index Settings API</a> * <p> * Can throw {@link JresErrorReplyException}. */ public class JresGetIndexSettings extends JresJsonRequest<JresJsonReply> { private final String index; public JresGetIndexSettings(String index) { super(JresJsonReply.class); this.index = index; } @Override public String getHttpMethod() { return HttpGet.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresGetIndexSettings.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.JresJsonReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpGet; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-get-settings.html#indices-get-settings">Get Index Settings API</a> * <p> * Can throw {@link JresErrorReplyException}. */ public class JresGetIndexSettings extends JresJsonRequest<JresJsonReply> { private final String index; public JresGetIndexSettings(String index) { super(JresJsonReply.class); this.index = index; } @Override public String getHttpMethod() { return HttpGet.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(index) + "_settings";
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/index/JresIndexExistsTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.JresBooleanReply; import org.junit.Assert; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresIndexExistsTest extends BaseJresTest { @Test public void testHappy() { String index = "JresIndexExistsRequestTest".toLowerCase();
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/index/JresIndexExistsTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.JresBooleanReply; import org.junit.Assert; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresIndexExistsTest extends BaseJresTest { @Test public void testHappy() { String index = "JresIndexExistsRequestTest".toLowerCase();
JresBooleanReply res = jres.bool(new JresIndexExists(index));
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/response/common/JresIndicesReply.java
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Indices.java // public class Indices extends HashMap<String, Shards> { // // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // }
import com.blacklocus.jres.model.Indices; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.common; public class JresIndicesReply extends JresJsonReply { private Boolean ok; @JsonProperty("_indices")
// Path: jres-core/src/main/java/com/blacklocus/jres/model/Indices.java // public class Indices extends HashMap<String, Shards> { // // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java // public class JresJsonReply implements JresReply { // // private JsonNode node; // // @Override // public JsonNode node() { // return node; // } // // public JresJsonReply node(JsonNode node) { // this.node = node; // return this; // } // // @Override // public String toString() { // try { // return ObjectMappers.PRETTY.writeValueAsString(node()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresIndicesReply.java import com.blacklocus.jres.model.Indices; import com.blacklocus.jres.response.JresJsonReply; import com.fasterxml.jackson.annotation.JsonProperty; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response.common; public class JresIndicesReply extends JresJsonReply { private Boolean ok; @JsonProperty("_indices")
private Indices indices;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/alias/JresAddAlias.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpPut;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-aliases.html#alias-adding">Add Single Index Alias API</a> * <p> * Can throw {@link JresErrorReplyException}. */ public class JresAddAlias extends JresJsonRequest<JresAcknowledgedReply> { private final String index; private final String alias; /** * @param index the actual index * @param alias another name by which the actual index may be addressed */ public JresAddAlias(String index, String alias) { super(JresAcknowledgedReply.class); this.index = index; this.alias = alias; } @Override public String getHttpMethod() { return HttpPut.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/alias/JresAddAlias.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpPut; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-aliases.html#alias-adding">Add Single Index Alias API</a> * <p> * Can throw {@link JresErrorReplyException}. */ public class JresAddAlias extends JresJsonRequest<JresAcknowledgedReply> { private final String index; private final String alias; /** * @param index the actual index * @param alias another name by which the actual index may be addressed */ public JresAddAlias(String index, String alias) { super(JresAcknowledgedReply.class); this.index = index; this.alias = alias; } @Override public String getHttpMethod() { return HttpPut.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(index) + "_alias/" + alias;
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/index/JresDeleteIndexTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresDeleteIndexTest extends BaseJresTest { @Test public void testExisting() { String index = "JresDeleteIndexTest.testExisting".toLowerCase(); jres.quest(new JresCreateIndex(index)); Assert.assertTrue(jres.bool(new JresIndexExists(index)).verity());
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/index/JresDeleteIndexTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresDeleteIndexTest extends BaseJresTest { @Test public void testExisting() { String index = "JresDeleteIndexTest.testExisting".toLowerCase(); jres.quest(new JresCreateIndex(index)); Assert.assertTrue(jres.bool(new JresIndexExists(index)).verity());
JresAcknowledgedReply deleteReply = jres.quest(new JresDeleteIndex(index));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/index/JresDeleteIndexTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresDeleteIndexTest extends BaseJresTest { @Test public void testExisting() { String index = "JresDeleteIndexTest.testExisting".toLowerCase(); jres.quest(new JresCreateIndex(index)); Assert.assertTrue(jres.bool(new JresIndexExists(index)).verity()); JresAcknowledgedReply deleteReply = jres.quest(new JresDeleteIndex(index)); Assert.assertTrue(deleteReply.getAcknowledged()); }
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/index/JresDeleteIndexTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresDeleteIndexTest extends BaseJresTest { @Test public void testExisting() { String index = "JresDeleteIndexTest.testExisting".toLowerCase(); jres.quest(new JresCreateIndex(index)); Assert.assertTrue(jres.bool(new JresIndexExists(index)).verity()); JresAcknowledgedReply deleteReply = jres.quest(new JresDeleteIndex(index)); Assert.assertTrue(deleteReply.getAcknowledged()); }
@Test(expected = JresErrorReplyException.class)
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/search/query/JresRangeQuery.java
// Path: jres-core/src/main/java/com/blacklocus/misc/NoNullsMap.java // public class NoNullsMap<K, V> extends HashMap<K, V> { // // public static <K, V> ImmutableMap<K, V> of(K k1, V v1) { // NoNullsMap<K, V> map = new NoNullsMap<K, V>(1); // map.put(k1, v1); // return ImmutableMap.copyOf(map); // // } // // public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { // NoNullsMap<K, V> map = new NoNullsMap<K, V>(3); // map.put(k1, v1); // map.put(k2, v2); // map.put(k3, v3); // return ImmutableMap.copyOf(map); // } // // public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { // NoNullsMap<K, V> map = new NoNullsMap<K, V>(3); // map.put(k1, v1); // map.put(k2, v2); // map.put(k3, v3); // map.put(k4, v4); // return ImmutableMap.copyOf(map); // } // // public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { // NoNullsMap<K, V> map = new NoNullsMap<K, V>(3); // map.put(k1, v1); // map.put(k2, v2); // map.put(k3, v3); // map.put(k4, v4); // map.put(k5, v5); // return ImmutableMap.copyOf(map); // } // // private NoNullsMap(int initialCapacity) { // super(initialCapacity); // } // // /** // * Ignores null keys or values. The key won't be added at all if it is null or its value is null. // */ // @Override // public V put(K key, V value) { // return key != null && value != null ? super.put(key, value) : null; // } // }
import com.blacklocus.misc.NoNullsMap; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.collect.ImmutableMap;
} public JresRangeQuery gte(Object value) { this.gte = value; return this; } public JresRangeQuery gt(Object value) { this.gt = value; return this; } public JresRangeQuery lte(Object value) { this.lte = value; return this; } public JresRangeQuery lt(Object value) { this.lt = value; return this; } @Override public String queryType() { return "range"; } @JsonValue public Object getJsonValue() { return ImmutableMap.of(
// Path: jres-core/src/main/java/com/blacklocus/misc/NoNullsMap.java // public class NoNullsMap<K, V> extends HashMap<K, V> { // // public static <K, V> ImmutableMap<K, V> of(K k1, V v1) { // NoNullsMap<K, V> map = new NoNullsMap<K, V>(1); // map.put(k1, v1); // return ImmutableMap.copyOf(map); // // } // // public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { // NoNullsMap<K, V> map = new NoNullsMap<K, V>(3); // map.put(k1, v1); // map.put(k2, v2); // map.put(k3, v3); // return ImmutableMap.copyOf(map); // } // // public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { // NoNullsMap<K, V> map = new NoNullsMap<K, V>(3); // map.put(k1, v1); // map.put(k2, v2); // map.put(k3, v3); // map.put(k4, v4); // return ImmutableMap.copyOf(map); // } // // public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { // NoNullsMap<K, V> map = new NoNullsMap<K, V>(3); // map.put(k1, v1); // map.put(k2, v2); // map.put(k3, v3); // map.put(k4, v4); // map.put(k5, v5); // return ImmutableMap.copyOf(map); // } // // private NoNullsMap(int initialCapacity) { // super(initialCapacity); // } // // /** // * Ignores null keys or values. The key won't be added at all if it is null or its value is null. // */ // @Override // public V put(K key, V value) { // return key != null && value != null ? super.put(key, value) : null; // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/search/query/JresRangeQuery.java import com.blacklocus.misc.NoNullsMap; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.collect.ImmutableMap; } public JresRangeQuery gte(Object value) { this.gte = value; return this; } public JresRangeQuery gt(Object value) { this.gt = value; return this; } public JresRangeQuery lte(Object value) { this.lte = value; return this; } public JresRangeQuery lt(Object value) { this.lt = value; return this; } @Override public String queryType() { return "range"; } @JsonValue public Object getJsonValue() { return ImmutableMap.of(
field, NoNullsMap.of(
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/search/query/JresTermQuery.java
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.strings.ObjectMappers; import java.util.HashMap;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search.query; public class JresTermQuery extends HashMap<String, Object> implements JresQuery { public JresTermQuery() { } public JresTermQuery(String field, Object subquery) { put(field, subquery); } public JresTermQuery addField(String field, Object subquery) { put(field, subquery); return this; } @Override public String queryType() { return "term"; } @Override public String toString() {
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/search/query/JresTermQuery.java import com.blacklocus.jres.strings.ObjectMappers; import java.util.HashMap; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search.query; public class JresTermQuery extends HashMap<String, Object> implements JresQuery { public JresTermQuery() { } public JresTermQuery(String field, Object subquery) { put(field, subquery); } public JresTermQuery addField(String field, Object subquery) { put(field, subquery); return this; } @Override public String queryType() { return "term"; } @Override public String toString() {
return ObjectMappers.toJson(this);
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/index/JresGetIndexSettingsTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresGetIndexSettingsTest extends BaseJresTest { @Test public void testHappy() { String indexName = "JresGetIndexSettingsRequestTest_testHappy".toLowerCase(); jres.quest(new JresCreateIndex(indexName)); jres.quest(new JresGetIndexSettings(indexName)); }
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/index/JresGetIndexSettingsTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresGetIndexSettingsTest extends BaseJresTest { @Test public void testHappy() { String indexName = "JresGetIndexSettingsRequestTest_testHappy".toLowerCase(); jres.quest(new JresCreateIndex(indexName)); jres.quest(new JresGetIndexSettings(indexName)); }
@Test(expected = JresErrorReplyException.class)
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/alias/JresAddAliasTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresAddAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresAddAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias";
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/alias/JresAddAliasTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresAddAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresAddAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias";
jres.quest(new JresCreateIndex(index));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/alias/JresAddAliasTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresAddAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresAddAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); jres.quest(new JresAddAlias(index, alias));
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/alias/JresAddAliasTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresAddAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresAddAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); jres.quest(new JresAddAlias(index, alias));
JresRetrieveAliasesReply retrieveAliasesReply = jres.quest(new JresRetrieveAliases(index, alias));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/alias/JresAddAliasTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresAddAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresAddAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); jres.quest(new JresAddAlias(index, alias)); JresRetrieveAliasesReply retrieveAliasesReply = jres.quest(new JresRetrieveAliases(index, alias)); Assert.assertEquals(Arrays.asList(alias), retrieveAliasesReply.getAliases(index)); }
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/alias/JresAddAliasTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; public class JresAddAliasTest extends BaseJresTest { @Test public void happy() { String index = "JresAddAliasRequestTest_happy".toLowerCase(); String alias = index + "_alias"; jres.quest(new JresCreateIndex(index)); jres.quest(new JresAddAlias(index, alias)); JresRetrieveAliasesReply retrieveAliasesReply = jres.quest(new JresRetrieveAliases(index, alias)); Assert.assertEquals(Arrays.asList(alias), retrieveAliasesReply.getAliases(index)); }
@Test(expected = JresErrorReplyException.class)
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.databind.JsonNode; import java.io.IOException;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response; public class JresJsonReply implements JresReply { private JsonNode node; @Override public JsonNode node() { return node; } public JresJsonReply node(JsonNode node) { this.node = node; return this; } @Override public String toString() { try {
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresJsonReply.java import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.databind.JsonNode; import java.io.IOException; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.response; public class JresJsonReply implements JresReply { private JsonNode node; @Override public JsonNode node() { return node; } public JresJsonReply node(JsonNode node) { this.node = node; return this; } @Override public String toString() { try {
return ObjectMappers.PRETTY.writeValueAsString(node());
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/document/JresGetDocument.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/document/JresGetDocumentReply.java // public class JresGetDocumentReply extends JresJsonReply { // // @JsonProperty("_index") // private String index; // // @JsonProperty("_type") // private String type; // // @JsonProperty("_id") // private String id; // // @JsonProperty("_version") // private Integer version; // // private Boolean found; // // @JsonProperty("_source") // private JsonNode source; // // public String getIndex() { // return index; // } // // public String getType() { // return type; // } // // public String getId() { // return id; // } // // public Integer getVersion() { // return version; // } // // public Boolean getFound() { // return found; // } // // public JsonNode getSource() { // return source; // } // // public <T> T getSourceAsType(Class<T> klass) { // return ObjectMappers.fromJson(source, klass); // } // // public <T> T getSourceAsType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(source, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.document.JresGetDocumentReply; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpGet;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.document; public class JresGetDocument extends JresJsonRequest<JresGetDocumentReply> { private final String index; private final String type; private final String id; public JresGetDocument(String index, String type, String id) { super(JresGetDocumentReply.class); this.index = index; this.type = type; this.id = id; } @Override public String getHttpMethod() { return HttpGet.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/document/JresGetDocumentReply.java // public class JresGetDocumentReply extends JresJsonReply { // // @JsonProperty("_index") // private String index; // // @JsonProperty("_type") // private String type; // // @JsonProperty("_id") // private String id; // // @JsonProperty("_version") // private Integer version; // // private Boolean found; // // @JsonProperty("_source") // private JsonNode source; // // public String getIndex() { // return index; // } // // public String getType() { // return type; // } // // public String getId() { // return id; // } // // public Integer getVersion() { // return version; // } // // public Boolean getFound() { // return found; // } // // public JsonNode getSource() { // return source; // } // // public <T> T getSourceAsType(Class<T> klass) { // return ObjectMappers.fromJson(source, klass); // } // // public <T> T getSourceAsType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(source, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/document/JresGetDocument.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.document.JresGetDocumentReply; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpGet; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.document; public class JresGetDocument extends JresJsonRequest<JresGetDocumentReply> { private final String index; private final String type; private final String id; public JresGetDocument(String index, String type, String id) { super(JresGetDocumentReply.class); this.index = index; this.type = type; this.id = id; } @Override public String getHttpMethod() { return HttpGet.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(index, type) + id;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/alias/JresRetrieveAliases.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpGet;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-aliases.html#alias-adding">Add Single Index Alias API</a> * <p> * Can throw {@link JresErrorReplyException}. */ public class JresRetrieveAliases extends JresJsonRequest<JresRetrieveAliasesReply> { private final String indexPattern; private final String aliasPattern; /** * @param indexPattern which appears to accept any number of '*' wildcards interspersed with characters and multiple * expressions separated by ',' * @param aliasPattern which appears to accept any number of '*' wildcards interspersed with characters and multiple * expressions separated by ',' */ public JresRetrieveAliases(String indexPattern, String aliasPattern) { super(JresRetrieveAliasesReply.class); this.indexPattern = indexPattern; this.aliasPattern = aliasPattern; } @Override public String getHttpMethod() { return HttpGet.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/alias/JresRetrieveAliasesReply.java // public class JresRetrieveAliasesReply extends JresJsonReply { // // public List<String> getIndexes() { // return Lists.newArrayList(node().fieldNames()); // } // // public List<String> getAliases(String index) { // JsonNode indexAliases = node().get(index); // return indexAliases == null ? Collections.<String>emptyList() : // Lists.newArrayList(indexAliases.get("aliases").fieldNames()); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/alias/JresRetrieveAliases.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.alias.JresRetrieveAliasesReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpGet; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.alias; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-aliases.html#alias-adding">Add Single Index Alias API</a> * <p> * Can throw {@link JresErrorReplyException}. */ public class JresRetrieveAliases extends JresJsonRequest<JresRetrieveAliasesReply> { private final String indexPattern; private final String aliasPattern; /** * @param indexPattern which appears to accept any number of '*' wildcards interspersed with characters and multiple * expressions separated by ',' * @param aliasPattern which appears to accept any number of '*' wildcards interspersed with characters and multiple * expressions separated by ',' */ public JresRetrieveAliases(String indexPattern, String aliasPattern) { super(JresRetrieveAliasesReply.class); this.indexPattern = indexPattern; this.aliasPattern = aliasPattern; } @Override public String getHttpMethod() { return HttpGet.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(indexPattern) + "_alias/" + aliasPattern;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/index/JresFlush.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresShardsReply.java // public class JresShardsReply extends JresJsonReply { // // @JsonProperty("_shards") // private Shards shards; // // public Shards getShards() { // return shards; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.common.JresShardsReply; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpPost;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresFlush extends JresJsonRequest<JresShardsReply> { private final String index; public JresFlush(String index) { super(JresShardsReply.class); this.index = index; } @Override public String getHttpMethod() { return HttpPost.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresShardsReply.java // public class JresShardsReply extends JresJsonReply { // // @JsonProperty("_shards") // private Shards shards; // // public Shards getShards() { // return shards; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresFlush.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.common.JresShardsReply; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpPost; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresFlush extends JresJsonRequest<JresShardsReply> { private final String index; public JresFlush(String index) { super(JresShardsReply.class); this.index = index; } @Override public String getHttpMethod() { return HttpPost.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(index) + "_flush";
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/search/query/JresQueryStringQuery.java
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.annotation.JsonProperty;
public void setDefaultField(String defaultField) { this.defaultField = defaultField; } public JresQueryStringQuery withDefaultField(String defaultField) { this.defaultField = defaultField; return this; } public String getDefaultOperator() { return defaultOperator; } public void setDefaultOperator(String defaultOperator) { this.defaultOperator = defaultOperator; } public JresQueryStringQuery withDefaultOperator(String defaultOperator) { this.defaultOperator = defaultOperator; return this; } @Override public String queryType() { return "query_string"; } @Override public String toString() {
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/search/query/JresQueryStringQuery.java import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.annotation.JsonProperty; public void setDefaultField(String defaultField) { this.defaultField = defaultField; } public JresQueryStringQuery withDefaultField(String defaultField) { this.defaultField = defaultField; return this; } public String getDefaultOperator() { return defaultOperator; } public void setDefaultOperator(String defaultOperator) { this.defaultOperator = defaultOperator; } public JresQueryStringQuery withDefaultOperator(String defaultOperator) { this.defaultOperator = defaultOperator; return this; } @Override public String queryType() { return "query_string"; } @Override public String toString() {
return ObjectMappers.toJson(this);
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresPutMappingTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresPutMappingTest extends BaseJresTest { @Test public void sad() { String index = "JresPutMappingRequestTest_sad".toLowerCase(); String type = "test"; try { jres.quest(new JresPutMapping(index, type, "{\"test\":{}}")); Assert.fail("Shouldn't be able to put type mapping on non-existent index");
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresPutMappingTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresPutMappingTest extends BaseJresTest { @Test public void sad() { String index = "JresPutMappingRequestTest_sad".toLowerCase(); String type = "test"; try { jres.quest(new JresPutMapping(index, type, "{\"test\":{}}")); Assert.fail("Shouldn't be able to put type mapping on non-existent index");
} catch (JresErrorReplyException e) {
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresPutMappingTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresPutMappingTest extends BaseJresTest { @Test public void sad() { String index = "JresPutMappingRequestTest_sad".toLowerCase(); String type = "test"; try { jres.quest(new JresPutMapping(index, type, "{\"test\":{}}")); Assert.fail("Shouldn't be able to put type mapping on non-existent index"); } catch (JresErrorReplyException e) { // good }
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresPutMappingTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresPutMappingTest extends BaseJresTest { @Test public void sad() { String index = "JresPutMappingRequestTest_sad".toLowerCase(); String type = "test"; try { jres.quest(new JresPutMapping(index, type, "{\"test\":{}}")); Assert.fail("Shouldn't be able to put type mapping on non-existent index"); } catch (JresErrorReplyException e) { // good }
jres.quest(new JresCreateIndex(index));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresPutMappingTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test;
jres.quest(new JresCreateIndex(index)); try { jres.quest(new JresPutMapping(index, type, null)); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } try { jres.quest(new JresPutMapping(index, type, "")); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } try { jres.quest(new JresPutMapping(index, type, "{}")); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } } @Test public void happy() { String index = "JresPutMappingRequestTest_happy".toLowerCase(); String type = "test"; {
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresPutMappingTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; jres.quest(new JresCreateIndex(index)); try { jres.quest(new JresPutMapping(index, type, null)); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } try { jres.quest(new JresPutMapping(index, type, "")); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } try { jres.quest(new JresPutMapping(index, type, "{}")); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } } @Test public void happy() { String index = "JresPutMappingRequestTest_happy".toLowerCase(); String type = "test"; {
JresBooleanReply response = jres.bool(new JresTypeExists(index, type));
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresPutMappingTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test;
// good } try { jres.quest(new JresPutMapping(index, type, "")); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } try { jres.quest(new JresPutMapping(index, type, "{}")); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } } @Test public void happy() { String index = "JresPutMappingRequestTest_happy".toLowerCase(); String type = "test"; { JresBooleanReply response = jres.bool(new JresTypeExists(index, type)); Assert.assertFalse(response.verity()); } jres.quest(new JresCreateIndex(index)); {
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/index/JresCreateIndex.java // public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> { // // private final String index; // private final Object settings; // // public JresCreateIndex(String index) { // this(index, null); // } // // public JresCreateIndex(String index, String settingsJson) { // super(JresAcknowledgedReply.class); // this.index = index; // this.settings = settingsJson; // } // // @Override // public String getHttpMethod() { // return HttpPut.METHOD_NAME; // } // // @Override // public String getPath() { // return index; // } // // @Override // public Object getPayload() { // return settings; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresAcknowledgedReply.java // public class JresAcknowledgedReply extends JresJsonReply { // // private Boolean acknowledged; // // public Boolean getAcknowledged() { // return acknowledged; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresPutMappingTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; // good } try { jres.quest(new JresPutMapping(index, type, "")); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } try { jres.quest(new JresPutMapping(index, type, "{}")); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } } @Test public void happy() { String index = "JresPutMappingRequestTest_happy".toLowerCase(); String type = "test"; { JresBooleanReply response = jres.bool(new JresTypeExists(index, type)); Assert.assertFalse(response.verity()); } jres.quest(new JresCreateIndex(index)); {
JresAcknowledgedReply response = jres.quest(new JresPutMapping(index, type, "{\"test\":{}}"));
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/search/JresSearch.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/search/JresSearchReply.java // public class JresSearchReply extends JresJsonReply { // // private Integer took; // // @JsonProperty("timed_out") // private Boolean timedOut; // // @JsonProperty("_shards") // private Shards shards; // // private Hits hits; // // private Facets facets; // // // public Integer getTook() { // return took; // } // // public Boolean isTimedOut() { // return timedOut; // } // // public Shards getShards() { // return shards; // } // // public Hits getHits() { // return hits; // } // // public Facets getFacets() { // return facets; // } // // /** // * Shortcut to {@link Hit#getSourceAsType(Class)} // */ // public <T> List<T> getHitsAsType(final Class<T> klass) { // return Lists.transform(getHits().getHits(), new Function<Hit, T>() { // @Override // public T apply(Hit hit) { // return hit.getSourceAsType(klass); // } // }); // } // // /** // * Shortcut to {@link Hit#getSourceAsType(TypeReference)} // */ // public <T> List<T> getHitsAsType(final TypeReference<T> typeReference) { // return Lists.transform(getHits().getHits(), new Function<Hit, T>() { // @Override // public T apply(Hit hit) { // return hit.getSourceAsType(typeReference); // } // }); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.search.JresSearchReply; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpPost; import javax.annotation.Nullable;
public JresSearch(JresSearchBody searchBody) { this(null, null, searchBody); } public JresSearch(@Nullable String index) { this(index, null, new JresSearchBody()); } public JresSearch(@Nullable String index, @Nullable String type) { this(index, type, new JresSearchBody()); } public JresSearch(@Nullable String index, @Nullable String type, JresSearchBody searchBody) { this(index, type, (Object) searchBody); } public JresSearch(@Nullable String index, @Nullable String type, Object searchBody) { super(JresSearchReply.class); this.searchBody = searchBody; this.index = index; this.type = type; } @Override public String getHttpMethod() { return HttpPost.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/search/JresSearchReply.java // public class JresSearchReply extends JresJsonReply { // // private Integer took; // // @JsonProperty("timed_out") // private Boolean timedOut; // // @JsonProperty("_shards") // private Shards shards; // // private Hits hits; // // private Facets facets; // // // public Integer getTook() { // return took; // } // // public Boolean isTimedOut() { // return timedOut; // } // // public Shards getShards() { // return shards; // } // // public Hits getHits() { // return hits; // } // // public Facets getFacets() { // return facets; // } // // /** // * Shortcut to {@link Hit#getSourceAsType(Class)} // */ // public <T> List<T> getHitsAsType(final Class<T> klass) { // return Lists.transform(getHits().getHits(), new Function<Hit, T>() { // @Override // public T apply(Hit hit) { // return hit.getSourceAsType(klass); // } // }); // } // // /** // * Shortcut to {@link Hit#getSourceAsType(TypeReference)} // */ // public <T> List<T> getHitsAsType(final TypeReference<T> typeReference) { // return Lists.transform(getHits().getHits(), new Function<Hit, T>() { // @Override // public T apply(Hit hit) { // return hit.getSourceAsType(typeReference); // } // }); // } // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/search/JresSearch.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.response.search.JresSearchReply; import com.blacklocus.jres.strings.JresPaths; import org.apache.http.client.methods.HttpPost; import javax.annotation.Nullable; public JresSearch(JresSearchBody searchBody) { this(null, null, searchBody); } public JresSearch(@Nullable String index) { this(index, null, new JresSearchBody()); } public JresSearch(@Nullable String index, @Nullable String type) { this(index, type, new JresSearchBody()); } public JresSearch(@Nullable String index, @Nullable String type, JresSearchBody searchBody) { this(index, type, (Object) searchBody); } public JresSearch(@Nullable String index, @Nullable String type, Object searchBody) { super(JresSearchReply.class); this.searchBody = searchBody; this.index = index; this.type = type; } @Override public String getHttpMethod() { return HttpPost.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(index) + JresPaths.slashedPath(type) + "_search";
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/index/JresCreateIndexTest.java
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // }
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresCreateIndexTest extends BaseJresTest { @Test(expected = JresErrorReplyException.class) public void sad() { // index names must be lowercase String indexName = "JresCreateIndexRequestTest_sad";
// Path: jres-test/src/main/java/com/blacklocus/jres/BaseJresTest.java // public class BaseJresTest { // // @BeforeClass // public static void startLocalElasticSearch() { // ElasticSearchTestInstance.triggerStaticInit(); // } // // /** // * Configured to connect to a local ElasticSearch instance created specifically for unit testing // */ // protected Jres jres = new Jres(Suppliers.ofInstance("http://localhost:9201")); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/JresBooleanReply.java // public class JresBooleanReply implements JresReply { // // private final boolean verity; // // public JresBooleanReply(boolean verity) { // this.verity = verity; // } // // @Override // public JsonNode node() { // return null; // } // // public boolean verity() { // return verity; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresErrorReplyException.java // public class JresErrorReplyException extends RuntimeException implements JresReply { // // private final String error; // private final Integer status; // private final JsonNode node; // // public JresErrorReplyException(String error, Integer status, JsonNode node) { // super(error); // this.error = error; // this.status = status; // this.node = node; // } // // @Override // public JsonNode node() { // return node; // } // // public String getError() { // return error; // } // // public Integer getStatus() { // return status; // } // // public <T> T asType(Class<T> klass) { // return ObjectMappers.fromJson(node, klass); // } // // public <T> T asType(TypeReference<T> typeReference) { // return ObjectMappers.fromJson(node, typeReference); // } // } // Path: jres-test/src/test/java/com/blacklocus/jres/request/index/JresCreateIndexTest.java import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.index; public class JresCreateIndexTest extends BaseJresTest { @Test(expected = JresErrorReplyException.class) public void sad() { // index names must be lowercase String indexName = "JresCreateIndexRequestTest_sad";
JresBooleanReply indexExistsResponse = jres.bool(new JresIndexExists(indexName));
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/mapping/JresTypeExists.java
// Path: jres-core/src/main/java/com/blacklocus/jres/handler/JresPredicates.java // public class JresPredicates { // // public static final Predicate<HttpResponse> STATUS_200 = new Predicate<HttpResponse>() { // @Override // public boolean apply(HttpResponse input) { // return input.getStatusLine().getStatusCode() == 200; // } // }; // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/JresBooleanRequest.java // public abstract class JresBooleanRequest extends JresJsonRequest<JresBooleanReply> { // // protected JresBooleanRequest() { // super(JresBooleanReply.class); // } // // public abstract Predicate<HttpResponse> getPredicate(); // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.handler.JresPredicates; import com.blacklocus.jres.request.JresBooleanRequest; import com.blacklocus.jres.strings.JresPaths; import com.google.common.base.Predicate; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpHead;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresTypeExists extends JresBooleanRequest { private final String index; private final String type; public JresTypeExists(String index, String type) { this.index = index; this.type = type; } @Override public String getHttpMethod() { return HttpHead.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/handler/JresPredicates.java // public class JresPredicates { // // public static final Predicate<HttpResponse> STATUS_200 = new Predicate<HttpResponse>() { // @Override // public boolean apply(HttpResponse input) { // return input.getStatusLine().getStatusCode() == 200; // } // }; // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/JresBooleanRequest.java // public abstract class JresBooleanRequest extends JresJsonRequest<JresBooleanReply> { // // protected JresBooleanRequest() { // super(JresBooleanReply.class); // } // // public abstract Predicate<HttpResponse> getPredicate(); // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/mapping/JresTypeExists.java import com.blacklocus.jres.handler.JresPredicates; import com.blacklocus.jres.request.JresBooleanRequest; import com.blacklocus.jres.strings.JresPaths; import com.google.common.base.Predicate; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpHead; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresTypeExists extends JresBooleanRequest { private final String index; private final String type; public JresTypeExists(String index, String type) { this.index = index; this.type = type; } @Override public String getHttpMethod() { return HttpHead.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(index) + type;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/mapping/JresTypeExists.java
// Path: jres-core/src/main/java/com/blacklocus/jres/handler/JresPredicates.java // public class JresPredicates { // // public static final Predicate<HttpResponse> STATUS_200 = new Predicate<HttpResponse>() { // @Override // public boolean apply(HttpResponse input) { // return input.getStatusLine().getStatusCode() == 200; // } // }; // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/JresBooleanRequest.java // public abstract class JresBooleanRequest extends JresJsonRequest<JresBooleanReply> { // // protected JresBooleanRequest() { // super(JresBooleanReply.class); // } // // public abstract Predicate<HttpResponse> getPredicate(); // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.handler.JresPredicates; import com.blacklocus.jres.request.JresBooleanRequest; import com.blacklocus.jres.strings.JresPaths; import com.google.common.base.Predicate; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpHead;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresTypeExists extends JresBooleanRequest { private final String index; private final String type; public JresTypeExists(String index, String type) { this.index = index; this.type = type; } @Override public String getHttpMethod() { return HttpHead.METHOD_NAME; } @Override public String getPath() { return JresPaths.slashedPath(index) + type; } @Override public Object getPayload() { return null; } @Override public Predicate<HttpResponse> getPredicate() {
// Path: jres-core/src/main/java/com/blacklocus/jres/handler/JresPredicates.java // public class JresPredicates { // // public static final Predicate<HttpResponse> STATUS_200 = new Predicate<HttpResponse>() { // @Override // public boolean apply(HttpResponse input) { // return input.getStatusLine().getStatusCode() == 200; // } // }; // } // // Path: jres-core/src/main/java/com/blacklocus/jres/request/JresBooleanRequest.java // public abstract class JresBooleanRequest extends JresJsonRequest<JresBooleanReply> { // // protected JresBooleanRequest() { // super(JresBooleanReply.class); // } // // public abstract Predicate<HttpResponse> getPredicate(); // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/mapping/JresTypeExists.java import com.blacklocus.jres.handler.JresPredicates; import com.blacklocus.jres.request.JresBooleanRequest; import com.blacklocus.jres.strings.JresPaths; import com.google.common.base.Predicate; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpHead; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.mapping; public class JresTypeExists extends JresBooleanRequest { private final String index; private final String type; public JresTypeExists(String index, String type) { this.index = index; this.type = type; } @Override public String getHttpMethod() { return HttpHead.METHOD_NAME; } @Override public String getPath() { return JresPaths.slashedPath(index) + type; } @Override public Object getPayload() { return null; } @Override public Predicate<HttpResponse> getPredicate() {
return JresPredicates.STATUS_200;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/search/JresDeleteByQuery.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-api/src/main/java/com/blacklocus/jres/request/search/query/JresQuery.java // public interface JresQuery { // // String queryType(); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresIndicesReply.java // public class JresIndicesReply extends JresJsonReply { // // private Boolean ok; // // @JsonProperty("_indices") // private Indices indices; // // public Boolean getOk() { // return ok; // } // // public Indices getIndices() { // return indices; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.request.search.query.JresQuery; import com.blacklocus.jres.response.common.JresIndicesReply; import com.blacklocus.jres.strings.JresPaths; import com.google.common.collect.ImmutableMap; import org.apache.http.client.methods.HttpDelete; import javax.annotation.Nullable; import java.util.Map;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search; /** * <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html">Delete By Query API</a> * * @deprecated see ElasticSearch docs */ @Deprecated public class JresDeleteByQuery extends JresJsonRequest<JresIndicesReply> { private @Nullable String index; private @Nullable String type; /** Single entry from {@link JresQuery#queryType()} to the JresQuery itself. */
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-api/src/main/java/com/blacklocus/jres/request/search/query/JresQuery.java // public interface JresQuery { // // String queryType(); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresIndicesReply.java // public class JresIndicesReply extends JresJsonReply { // // private Boolean ok; // // @JsonProperty("_indices") // private Indices indices; // // public Boolean getOk() { // return ok; // } // // public Indices getIndices() { // return indices; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/search/JresDeleteByQuery.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.request.search.query.JresQuery; import com.blacklocus.jres.response.common.JresIndicesReply; import com.blacklocus.jres.strings.JresPaths; import com.google.common.collect.ImmutableMap; import org.apache.http.client.methods.HttpDelete; import javax.annotation.Nullable; import java.util.Map; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search; /** * <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html">Delete By Query API</a> * * @deprecated see ElasticSearch docs */ @Deprecated public class JresDeleteByQuery extends JresJsonRequest<JresIndicesReply> { private @Nullable String index; private @Nullable String type; /** Single entry from {@link JresQuery#queryType()} to the JresQuery itself. */
private final Map<String, JresQuery> query;
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/search/JresDeleteByQuery.java
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-api/src/main/java/com/blacklocus/jres/request/search/query/JresQuery.java // public interface JresQuery { // // String queryType(); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresIndicesReply.java // public class JresIndicesReply extends JresJsonReply { // // private Boolean ok; // // @JsonProperty("_indices") // private Indices indices; // // public Boolean getOk() { // return ok; // } // // public Indices getIndices() { // return indices; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.request.search.query.JresQuery; import com.blacklocus.jres.response.common.JresIndicesReply; import com.blacklocus.jres.strings.JresPaths; import com.google.common.collect.ImmutableMap; import org.apache.http.client.methods.HttpDelete; import javax.annotation.Nullable; import java.util.Map;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search; /** * <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html">Delete By Query API</a> * * @deprecated see ElasticSearch docs */ @Deprecated public class JresDeleteByQuery extends JresJsonRequest<JresIndicesReply> { private @Nullable String index; private @Nullable String type; /** Single entry from {@link JresQuery#queryType()} to the JresQuery itself. */ private final Map<String, JresQuery> query; public JresDeleteByQuery(@Nullable String index, JresQuery query) { this(index, null, query); } public JresDeleteByQuery(@Nullable String index, @Nullable String type, JresQuery query) { super(JresIndicesReply.class); this.index = index; this.type = type; this.query = ImmutableMap.of(query.queryType(), query); } @Override public String getHttpMethod() { return HttpDelete.METHOD_NAME; } @Override public String getPath() {
// Path: jres-core/src/main/java/com/blacklocus/jres/request/JresJsonRequest.java // public abstract class JresJsonRequest<REPLY extends JresReply> implements JresRequest<REPLY> { // // private final Class<REPLY> responseClass; // // protected JresJsonRequest(Class<REPLY> responseClass) { // this.responseClass = responseClass; // } // // @Override // public final Class<REPLY> getResponseClass() { // return responseClass; // } // } // // Path: jres-api/src/main/java/com/blacklocus/jres/request/search/query/JresQuery.java // public interface JresQuery { // // String queryType(); // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/response/common/JresIndicesReply.java // public class JresIndicesReply extends JresJsonReply { // // private Boolean ok; // // @JsonProperty("_indices") // private Indices indices; // // public Boolean getOk() { // return ok; // } // // public Indices getIndices() { // return indices; // } // // } // // Path: jres-core/src/main/java/com/blacklocus/jres/strings/JresPaths.java // public class JresPaths { // // /** // * @return fragments each appended with '/' if not present, and concatenated together // */ // public static String slashed(String... fragments) { // StringBuilder sb = new StringBuilder(); // for (String fragment : fragments) { // sb.append(StringUtils.isBlank(fragment) || fragment.endsWith("/") ? // (fragment == null ? "" : fragment) : // fragment + "/"); // } // return sb.toString(); // } // // /** // * @return fragments encoded as valid URI path sections, each appended with '/' if not present. <code>null</code>s // * upgraded to empty strings. Appends nothing to blank strings (and nulls). Any leading slashes will be dropped. // */ // public static String slashedPath(String... fragments) { // String slashed = slashed(fragments); // try { // // Encode (anything that needs to be) in the path. Surprisingly this works. // String encodedPath = new URI(null, null, slashed, null).getRawPath(); // // Strip leading slash. Omitting it is slightly more portable where URIs are being constructed. // return encodedPath.startsWith("/") ? encodedPath.substring(1) : encodedPath; // } catch (URISyntaxException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/request/search/JresDeleteByQuery.java import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.request.search.query.JresQuery; import com.blacklocus.jres.response.common.JresIndicesReply; import com.blacklocus.jres.strings.JresPaths; import com.google.common.collect.ImmutableMap; import org.apache.http.client.methods.HttpDelete; import javax.annotation.Nullable; import java.util.Map; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.request.search; /** * <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html">Delete By Query API</a> * * @deprecated see ElasticSearch docs */ @Deprecated public class JresDeleteByQuery extends JresJsonRequest<JresIndicesReply> { private @Nullable String index; private @Nullable String type; /** Single entry from {@link JresQuery#queryType()} to the JresQuery itself. */ private final Map<String, JresQuery> query; public JresDeleteByQuery(@Nullable String index, JresQuery query) { this(index, null, query); } public JresDeleteByQuery(@Nullable String index, @Nullable String type, JresQuery query) { super(JresIndicesReply.class); this.index = index; this.type = type; this.query = ImmutableMap.of(query.queryType(), query); } @Override public String getHttpMethod() { return HttpDelete.METHOD_NAME; } @Override public String getPath() {
return JresPaths.slashedPath(index) + JresPaths.slashedPath(type) + "_query";
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/model/search/Facets.java
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.databind.JsonNode; import java.util.HashMap;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.model.search; public class Facets extends HashMap<String, JsonNode> { public <T extends Facet> T get(String facetName, Class<T> klass) {
// Path: jres-core/src/main/java/com/blacklocus/jres/strings/ObjectMappers.java // public class ObjectMappers { // // public static final ObjectMapper NORMAL = newConfiguredObjectMapper(); // // public static final ObjectMapper PRETTY = newConfiguredObjectMapper(); // static { // PRETTY.configure(SerializationFeature.INDENT_OUTPUT, true); // } // // static ObjectMapper newConfiguredObjectMapper() { // return new ObjectMapper() // // ElasticSearch is usually more okay with absence of properties rather than presence with null values. // .setSerializationInclusion(JsonInclude.Include.NON_NULL) // // Allow empty JSON objects where they might occur. // .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) // // Not all properties need to be mapped back into POJOs. // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJson(Object o) { // try { // return NORMAL.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#writeValueAsString(Object)} with {@link ObjectMappers#PRETTY} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static String toJsonPretty(Object o) { // try { // return PRETTY.writeValueAsString(o); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(String, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(String json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, Class<T> klass) { // try { // return NORMAL.readValue(json, klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(InputStream, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(InputStream json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json, typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, Class)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, Class<T> klass) { // try { // return NORMAL.readValue(json.traverse(NORMAL), klass); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Convenience around {@link ObjectMapper#readValue(JsonParser, TypeReference)} with {@link ObjectMappers#NORMAL} wrapping // * checked exceptions in {@link RuntimeException} // */ // public static <T> T fromJson(JsonNode json, TypeReference<T> typeReference) { // try { // return NORMAL.readValue(json.traverse(NORMAL), typeReference); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: jres-core/src/main/java/com/blacklocus/jres/model/search/Facets.java import com.blacklocus.jres.strings.ObjectMappers; import com.fasterxml.jackson.databind.JsonNode; import java.util.HashMap; /** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacklocus.jres.model.search; public class Facets extends HashMap<String, JsonNode> { public <T extends Facet> T get(String facetName, Class<T> klass) {
return ObjectMappers.fromJson(get(facetName), klass);
rvillars/edoras-one-initializr
src/main/java/com/edorasware/one/initializr/web/support/EdorasoneMetadataReader.java
// Path: src/main/java/com/edorasware/one/initializr/metadata/DefaultMetadataElement.java // public class DefaultMetadataElement extends MetadataElement { // // private boolean defaultValue; // // public DefaultMetadataElement() { // } // // public DefaultMetadataElement(String id, String name, boolean defaultValue) { // super(id, name); // this.defaultValue = defaultValue; // } // // public DefaultMetadataElement(String id, boolean defaultValue) { // this(id, null, defaultValue); // } // // public void setDefault(boolean defaultValue) { // this.defaultValue = defaultValue; // } // // public boolean isDefault() { // return this.defaultValue; // } // // public static DefaultMetadataElement create(String id, boolean defaultValue) { // return new DefaultMetadataElement(id, defaultValue); // } // // public static DefaultMetadataElement create(String id, String name, boolean defaultValue) { // return new DefaultMetadataElement(id, name, defaultValue); // } // // }
import com.edorasware.one.initializr.metadata.DefaultMetadataElement; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.List;
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edorasware.one.initializr.web.support; /** * Reads metadata from the main spring.io website. This is a stateful service: create a * new instance whenever you need to refresh the content. * * @author Stephane Nicoll */ public class EdorasoneMetadataReader { private final JSONObject content; /** * Parse the content of the metadata at the specified url */ public EdorasoneMetadataReader(RestTemplate restTemplate, String url) { this.content = new JSONObject(restTemplate.getForObject(url, String.class)); } /** * Return the edoras one versions parsed by this instance. */
// Path: src/main/java/com/edorasware/one/initializr/metadata/DefaultMetadataElement.java // public class DefaultMetadataElement extends MetadataElement { // // private boolean defaultValue; // // public DefaultMetadataElement() { // } // // public DefaultMetadataElement(String id, String name, boolean defaultValue) { // super(id, name); // this.defaultValue = defaultValue; // } // // public DefaultMetadataElement(String id, boolean defaultValue) { // this(id, null, defaultValue); // } // // public void setDefault(boolean defaultValue) { // this.defaultValue = defaultValue; // } // // public boolean isDefault() { // return this.defaultValue; // } // // public static DefaultMetadataElement create(String id, boolean defaultValue) { // return new DefaultMetadataElement(id, defaultValue); // } // // public static DefaultMetadataElement create(String id, String name, boolean defaultValue) { // return new DefaultMetadataElement(id, name, defaultValue); // } // // } // Path: src/main/java/com/edorasware/one/initializr/web/support/EdorasoneMetadataReader.java import com.edorasware.one.initializr.metadata.DefaultMetadataElement; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.List; /* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edorasware.one.initializr.web.support; /** * Reads metadata from the main spring.io website. This is a stateful service: create a * new instance whenever you need to refresh the content. * * @author Stephane Nicoll */ public class EdorasoneMetadataReader { private final JSONObject content; /** * Parse the content of the metadata at the specified url */ public EdorasoneMetadataReader(RestTemplate restTemplate, String url) { this.content = new JSONObject(restTemplate.getForObject(url, String.class)); } /** * Return the edoras one versions parsed by this instance. */
public List<DefaultMetadataElement> getEdorasoneVersions() {
rvillars/edoras-one-initializr
src/main/java/com/edorasware/one/initializr/web/support/OfflineInitializrMetadataBuilder.java
// Path: src/main/java/com/edorasware/one/initializr/metadata/InitializrConfiguration.java // public static class ParentPom { // // /** // * Parent pom groupId. // */ // private String groupId; // // /** // * Parent pom artifactId. // */ // private String artifactId; // // /** // * Parent pom version. // */ // private String version; // // public ParentPom(String groupId, String artifactId, String version) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // } // // public ParentPom() { // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public void validate() { // if (!((!StringUtils.hasText(groupId) // && !StringUtils.hasText(artifactId) // && !StringUtils.hasText(version)) // || (StringUtils.hasText(groupId) // && StringUtils.hasText(artifactId) // && StringUtils.hasText(version)))) { // throw new InvalidInitializrMetadataException("Custom maven pom " // + "requires groupId, artifactId and version"); // } // } // // }
import com.edorasware.one.initializr.metadata.*; import com.edorasware.one.initializr.metadata.InitializrConfiguration.Env.Maven.ParentPom; import org.springframework.util.StringUtils; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays;
; } public OfflineInitializrMetadataBuilder addBom(String id, String groupId, String artifactId, String version) { BillOfMaterials bom = BillOfMaterials.create(groupId, artifactId, version); return addBom(id, bom); } public OfflineInitializrMetadataBuilder addBom(String id, BillOfMaterials bom) { builder.withCustomizer(it -> it.getConfiguration().getEnv() .getBoms().put(id, bom)); return this; } public OfflineInitializrMetadataBuilder setGradleEnv(String dependencyManagementPluginVersion) { builder.withCustomizer(it -> it.getConfiguration().getEnv().getGradle(). setDependencyManagementPluginVersion(dependencyManagementPluginVersion)); return this; } public OfflineInitializrMetadataBuilder setKotlinEnv(String kotlinVersion) { builder.withCustomizer(it -> it.getConfiguration().getEnv() .getKotlin().setVersion(kotlinVersion)); return this; } public OfflineInitializrMetadataBuilder setMavenParent(String groupId, String artifactId, String version) { builder.withCustomizer(it -> {
// Path: src/main/java/com/edorasware/one/initializr/metadata/InitializrConfiguration.java // public static class ParentPom { // // /** // * Parent pom groupId. // */ // private String groupId; // // /** // * Parent pom artifactId. // */ // private String artifactId; // // /** // * Parent pom version. // */ // private String version; // // public ParentPom(String groupId, String artifactId, String version) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // } // // public ParentPom() { // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public void validate() { // if (!((!StringUtils.hasText(groupId) // && !StringUtils.hasText(artifactId) // && !StringUtils.hasText(version)) // || (StringUtils.hasText(groupId) // && StringUtils.hasText(artifactId) // && StringUtils.hasText(version)))) { // throw new InvalidInitializrMetadataException("Custom maven pom " // + "requires groupId, artifactId and version"); // } // } // // } // Path: src/main/java/com/edorasware/one/initializr/web/support/OfflineInitializrMetadataBuilder.java import com.edorasware.one.initializr.metadata.*; import com.edorasware.one.initializr.metadata.InitializrConfiguration.Env.Maven.ParentPom; import org.springframework.util.StringUtils; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; ; } public OfflineInitializrMetadataBuilder addBom(String id, String groupId, String artifactId, String version) { BillOfMaterials bom = BillOfMaterials.create(groupId, artifactId, version); return addBom(id, bom); } public OfflineInitializrMetadataBuilder addBom(String id, BillOfMaterials bom) { builder.withCustomizer(it -> it.getConfiguration().getEnv() .getBoms().put(id, bom)); return this; } public OfflineInitializrMetadataBuilder setGradleEnv(String dependencyManagementPluginVersion) { builder.withCustomizer(it -> it.getConfiguration().getEnv().getGradle(). setDependencyManagementPluginVersion(dependencyManagementPluginVersion)); return this; } public OfflineInitializrMetadataBuilder setKotlinEnv(String kotlinVersion) { builder.withCustomizer(it -> it.getConfiguration().getEnv() .getKotlin().setVersion(kotlinVersion)); return this; } public OfflineInitializrMetadataBuilder setMavenParent(String groupId, String artifactId, String version) { builder.withCustomizer(it -> {
ParentPom parent = it.getConfiguration().getEnv().getMaven().getParent();
rvillars/edoras-one-initializr
src/main/java/com/edorasware/one/initializr/generator/BuildProperties.java
// Path: src/main/java/com/edorasware/one/initializr/util/VersionProperty.java // public class VersionProperty implements Serializable, Comparable<VersionProperty> { // // private static final List<Character> SUPPORTED_CHARS = Arrays.asList('.', '-'); // // private final String property; // // public VersionProperty(String property) { // this.property = validateFormat(property); // } // // /** // * Return a camel cased representation of this instance. // */ // public String toCamelCaseFormat() { // String[] tokens = this.property.split("\\-|\\."); // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < tokens.length; i++) { // String part = tokens[i]; // if (i > 0) { // part = StringUtils.capitalize(part); // } // sb.append(part); // } // return sb.toString(); // } // // public String toStandardFormat() { // return this.property; // } // // // private static String validateFormat(String property) { // for (char c : property.toCharArray()) { // if (Character.isUpperCase(c)) { // throw new IllegalArgumentException( // "Invalid property '" + property + "', must not contain upper case"); // } // if (!Character.isLetterOrDigit(c) && !SUPPORTED_CHARS.contains(c)) { // throw new IllegalArgumentException( // "Unsupported character '" + c + "' for '" + property + "'"); // } // } // return property; // } // // @Override // public int compareTo(VersionProperty o) { // return this.property.compareTo(o.property); // } // // @Override // public String toString() { // return this.property; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // VersionProperty that = (VersionProperty) o; // // return property.equals(that.property); // } // // @Override // public int hashCode() { // return property.hashCode(); // } // // }
import com.edorasware.one.initializr.util.VersionProperty; import java.util.Map; import java.util.TreeMap; import java.util.function.Supplier;
/* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edorasware.one.initializr.generator; /** * Build properties associated to a project request. * * @author Stephane Nicoll */ public class BuildProperties { /** * Maven-specific build properties, added to the regular {@code properties} element. */ private final TreeMap<String, Supplier<String>> maven = new TreeMap<>(); /** * Gradle-specific build properties, added to the {@code buildscript} section * of the gradle build. */ private final TreeMap<String, Supplier<String>> gradle = new TreeMap<>(); /** * Version properties. Shared between the two build systems. */
// Path: src/main/java/com/edorasware/one/initializr/util/VersionProperty.java // public class VersionProperty implements Serializable, Comparable<VersionProperty> { // // private static final List<Character> SUPPORTED_CHARS = Arrays.asList('.', '-'); // // private final String property; // // public VersionProperty(String property) { // this.property = validateFormat(property); // } // // /** // * Return a camel cased representation of this instance. // */ // public String toCamelCaseFormat() { // String[] tokens = this.property.split("\\-|\\."); // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < tokens.length; i++) { // String part = tokens[i]; // if (i > 0) { // part = StringUtils.capitalize(part); // } // sb.append(part); // } // return sb.toString(); // } // // public String toStandardFormat() { // return this.property; // } // // // private static String validateFormat(String property) { // for (char c : property.toCharArray()) { // if (Character.isUpperCase(c)) { // throw new IllegalArgumentException( // "Invalid property '" + property + "', must not contain upper case"); // } // if (!Character.isLetterOrDigit(c) && !SUPPORTED_CHARS.contains(c)) { // throw new IllegalArgumentException( // "Unsupported character '" + c + "' for '" + property + "'"); // } // } // return property; // } // // @Override // public int compareTo(VersionProperty o) { // return this.property.compareTo(o.property); // } // // @Override // public String toString() { // return this.property; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // VersionProperty that = (VersionProperty) o; // // return property.equals(that.property); // } // // @Override // public int hashCode() { // return property.hashCode(); // } // // } // Path: src/main/java/com/edorasware/one/initializr/generator/BuildProperties.java import com.edorasware.one.initializr.util.VersionProperty; import java.util.Map; import java.util.TreeMap; import java.util.function.Supplier; /* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edorasware.one.initializr.generator; /** * Build properties associated to a project request. * * @author Stephane Nicoll */ public class BuildProperties { /** * Maven-specific build properties, added to the regular {@code properties} element. */ private final TreeMap<String, Supplier<String>> maven = new TreeMap<>(); /** * Gradle-specific build properties, added to the {@code buildscript} section * of the gradle build. */ private final TreeMap<String, Supplier<String>> gradle = new TreeMap<>(); /** * Version properties. Shared between the two build systems. */
private final TreeMap<VersionProperty, Supplier<String>> versions = new TreeMap<>();
rvillars/edoras-one-initializr
src/main/java/com/edorasware/one/initializr/util/VersionParser.java
// Path: src/main/java/com/edorasware/one/initializr/util/Version.java // public static class Qualifier implements Serializable { // // public Qualifier(String qualifier) { // this.qualifier = qualifier; // } // // private String qualifier; // private Integer version; // // public String getQualifier() { // return qualifier; // } // // public void setQualifier(String qualifier) { // this.qualifier = qualifier; // } // // public Integer getVersion() { // return version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // @Override // public String toString() { // return "Qualifier [" // + (qualifier != null ? "qualifier=" + qualifier + ", " : "") // + (version != null ? "version=" + version : "") + "]"; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((qualifier == null) ? 0 : qualifier.hashCode()); // result = prime * result + ((version == null) ? 0 : version.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Qualifier other = (Qualifier) obj; // if (qualifier == null) { // if (other.qualifier != null) // return false; // } // else if (!qualifier.equals(other.qualifier)) // return false; // if (version == null) { // if (other.version != null) // return false; // } // else if (!version.equals(other.version)) // return false; // return true; // } // }
import com.edorasware.one.initializr.util.Version.Qualifier; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors;
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edorasware.one.initializr.util; /** * Parser for {@link Version} and {@link VersionRange} that allows to resolve the minor * and patch value against a configurable list of "latest versions". * <p> * For example a parser that is configured with {@code 1.3.7.RELEASE} and * {@code 1.4.2.RELEASE} as latest versions can parse {@code 1.3.x.RELEASE} to * {@code 1.3.7.RELEASE}. Note that the qualifier is important here: * {@code 1.3.8.BUILD-SNAPSHOT} would be parsed as {@code 1.3.999.BUILD-SNAPSHOT} as the * parser doesn't know the latest {@code BUILD-SNAPSHOT} in the {@code 1.3.x} release * line. * * @author Stephane Nicoll */ public class VersionParser { public static final VersionParser DEFAULT = new VersionParser(Collections.emptyList()); private static final Pattern VERSION_REGEX = Pattern.compile("^(\\d+)\\.(\\d+|x)\\.(\\d+|x)(?:-([^0-9]+)(\\d+)?(-\\d+)?(-SNAPSHOT)?)?$"); private static final Pattern RANGE_REGEX = Pattern.compile("(\\(|\\[)(.*),(.*)(\\)|\\])"); private final List<Version> latestVersions; public VersionParser(List<Version> latestVersions) { this.latestVersions = latestVersions; } /** * Parse the string representation of a {@link Version}. Throws an * {@link InvalidVersionException} if the version could not be parsed. * @param text the version text * @return a Version instance for the specified version text * @throws InvalidVersionException if the version text could not be parsed * @see #safeParse(String) */ public Version parse(String text) { Assert.notNull(text, "Text must not be null"); Matcher matcher = VERSION_REGEX.matcher(text.trim()); if (!matcher.matches()) { throw new InvalidVersionException("Could not determine version based on '" + text + "': version format " + "is Minor.Major.Patch-Qualifier-StarterVersion-StarterQualifier " + "(e.g. 2.0.0-M6-1-SNAPSHOT)"); } Integer major = Integer.valueOf(matcher.group(1)); String minor = matcher.group(2); String patch = matcher.group(3);
// Path: src/main/java/com/edorasware/one/initializr/util/Version.java // public static class Qualifier implements Serializable { // // public Qualifier(String qualifier) { // this.qualifier = qualifier; // } // // private String qualifier; // private Integer version; // // public String getQualifier() { // return qualifier; // } // // public void setQualifier(String qualifier) { // this.qualifier = qualifier; // } // // public Integer getVersion() { // return version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // @Override // public String toString() { // return "Qualifier [" // + (qualifier != null ? "qualifier=" + qualifier + ", " : "") // + (version != null ? "version=" + version : "") + "]"; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((qualifier == null) ? 0 : qualifier.hashCode()); // result = prime * result + ((version == null) ? 0 : version.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Qualifier other = (Qualifier) obj; // if (qualifier == null) { // if (other.qualifier != null) // return false; // } // else if (!qualifier.equals(other.qualifier)) // return false; // if (version == null) { // if (other.version != null) // return false; // } // else if (!version.equals(other.version)) // return false; // return true; // } // } // Path: src/main/java/com/edorasware/one/initializr/util/VersionParser.java import com.edorasware.one.initializr.util.Version.Qualifier; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.edorasware.one.initializr.util; /** * Parser for {@link Version} and {@link VersionRange} that allows to resolve the minor * and patch value against a configurable list of "latest versions". * <p> * For example a parser that is configured with {@code 1.3.7.RELEASE} and * {@code 1.4.2.RELEASE} as latest versions can parse {@code 1.3.x.RELEASE} to * {@code 1.3.7.RELEASE}. Note that the qualifier is important here: * {@code 1.3.8.BUILD-SNAPSHOT} would be parsed as {@code 1.3.999.BUILD-SNAPSHOT} as the * parser doesn't know the latest {@code BUILD-SNAPSHOT} in the {@code 1.3.x} release * line. * * @author Stephane Nicoll */ public class VersionParser { public static final VersionParser DEFAULT = new VersionParser(Collections.emptyList()); private static final Pattern VERSION_REGEX = Pattern.compile("^(\\d+)\\.(\\d+|x)\\.(\\d+|x)(?:-([^0-9]+)(\\d+)?(-\\d+)?(-SNAPSHOT)?)?$"); private static final Pattern RANGE_REGEX = Pattern.compile("(\\(|\\[)(.*),(.*)(\\)|\\])"); private final List<Version> latestVersions; public VersionParser(List<Version> latestVersions) { this.latestVersions = latestVersions; } /** * Parse the string representation of a {@link Version}. Throws an * {@link InvalidVersionException} if the version could not be parsed. * @param text the version text * @return a Version instance for the specified version text * @throws InvalidVersionException if the version text could not be parsed * @see #safeParse(String) */ public Version parse(String text) { Assert.notNull(text, "Text must not be null"); Matcher matcher = VERSION_REGEX.matcher(text.trim()); if (!matcher.matches()) { throw new InvalidVersionException("Could not determine version based on '" + text + "': version format " + "is Minor.Major.Patch-Qualifier-StarterVersion-StarterQualifier " + "(e.g. 2.0.0-M6-1-SNAPSHOT)"); } Integer major = Integer.valueOf(matcher.group(1)); String minor = matcher.group(2); String patch = matcher.group(3);
Qualifier qualifier = null;
rvillars/edoras-one-initializr
src/test/java/com/edorasware/one/initializr/test/metadata/InitializrMetadataTestBuilder.java
// Path: src/main/java/com/edorasware/one/initializr/metadata/InitializrConfiguration.java // public static class ParentPom { // // /** // * Parent pom groupId. // */ // private String groupId; // // /** // * Parent pom artifactId. // */ // private String artifactId; // // /** // * Parent pom version. // */ // private String version; // // public ParentPom(String groupId, String artifactId, String version) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // } // // public ParentPom() { // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public void validate() { // if (!((!StringUtils.hasText(groupId) // && !StringUtils.hasText(artifactId) // && !StringUtils.hasText(version)) // || (StringUtils.hasText(groupId) // && StringUtils.hasText(artifactId) // && StringUtils.hasText(version)))) { // throw new InvalidInitializrMetadataException("Custom maven pom " // + "requires groupId, artifactId and version"); // } // } // // }
import com.edorasware.one.initializr.metadata.*; import com.edorasware.one.initializr.metadata.InitializrConfiguration.Env.Maven.ParentPom; import org.springframework.util.StringUtils; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays;
return this; } public InitializrMetadataTestBuilder addBom(String id, String groupId, String artifactId, String version) { BillOfMaterials bom = BillOfMaterials.create(groupId, artifactId, version); return addBom(id, bom); } public InitializrMetadataTestBuilder addBom(String id, BillOfMaterials bom) { builder.withCustomizer(it -> it.getConfiguration().getEnv() .getBoms().put(id, bom)); return this; } public InitializrMetadataTestBuilder setGradleEnv(String dependencyManagementPluginVersion) { builder.withCustomizer(it -> it.getConfiguration().getEnv().getGradle(). setDependencyManagementPluginVersion(dependencyManagementPluginVersion)); return this; } public InitializrMetadataTestBuilder setKotlinEnv(String kotlinVersion) { builder.withCustomizer(it -> it.getConfiguration().getEnv() .getKotlin().setVersion(kotlinVersion)); return this; } public InitializrMetadataTestBuilder setMavenParent(String groupId, String artifactId, String version) { builder.withCustomizer(it -> {
// Path: src/main/java/com/edorasware/one/initializr/metadata/InitializrConfiguration.java // public static class ParentPom { // // /** // * Parent pom groupId. // */ // private String groupId; // // /** // * Parent pom artifactId. // */ // private String artifactId; // // /** // * Parent pom version. // */ // private String version; // // public ParentPom(String groupId, String artifactId, String version) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // } // // public ParentPom() { // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public void validate() { // if (!((!StringUtils.hasText(groupId) // && !StringUtils.hasText(artifactId) // && !StringUtils.hasText(version)) // || (StringUtils.hasText(groupId) // && StringUtils.hasText(artifactId) // && StringUtils.hasText(version)))) { // throw new InvalidInitializrMetadataException("Custom maven pom " // + "requires groupId, artifactId and version"); // } // } // // } // Path: src/test/java/com/edorasware/one/initializr/test/metadata/InitializrMetadataTestBuilder.java import com.edorasware.one.initializr.metadata.*; import com.edorasware.one.initializr.metadata.InitializrConfiguration.Env.Maven.ParentPom; import org.springframework.util.StringUtils; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; return this; } public InitializrMetadataTestBuilder addBom(String id, String groupId, String artifactId, String version) { BillOfMaterials bom = BillOfMaterials.create(groupId, artifactId, version); return addBom(id, bom); } public InitializrMetadataTestBuilder addBom(String id, BillOfMaterials bom) { builder.withCustomizer(it -> it.getConfiguration().getEnv() .getBoms().put(id, bom)); return this; } public InitializrMetadataTestBuilder setGradleEnv(String dependencyManagementPluginVersion) { builder.withCustomizer(it -> it.getConfiguration().getEnv().getGradle(). setDependencyManagementPluginVersion(dependencyManagementPluginVersion)); return this; } public InitializrMetadataTestBuilder setKotlinEnv(String kotlinVersion) { builder.withCustomizer(it -> it.getConfiguration().getEnv() .getKotlin().setVersion(kotlinVersion)); return this; } public InitializrMetadataTestBuilder setMavenParent(String groupId, String artifactId, String version) { builder.withCustomizer(it -> {
ParentPom parent = it.getConfiguration().getEnv().getMaven().getParent();
rvillars/edoras-one-initializr
src/main/java/com/edorasware/one/initializr/generator/ProjectGenerator.java
// Path: src/main/java/com/edorasware/one/initializr/InitializrException.java // @SuppressWarnings("serial") // public class InitializrException extends RuntimeException { // // public InitializrException(String message, Throwable cause) { // super(message, cause); // } // // public InitializrException(String message) { // super(message); // } // // } // // Path: src/main/java/com/edorasware/one/initializr/metadata/InitializrConfiguration.java // public static class ParentPom { // // /** // * Parent pom groupId. // */ // private String groupId; // // /** // * Parent pom artifactId. // */ // private String artifactId; // // /** // * Parent pom version. // */ // private String version; // // public ParentPom(String groupId, String artifactId, String version) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // } // // public ParentPom() { // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public void validate() { // if (!((!StringUtils.hasText(groupId) // && !StringUtils.hasText(artifactId) // && !StringUtils.hasText(version)) // || (StringUtils.hasText(groupId) // && StringUtils.hasText(artifactId) // && StringUtils.hasText(version)))) { // throw new InvalidInitializrMetadataException("Custom maven pom " // + "requires groupId, artifactId and version"); // } // } // // }
import com.edorasware.one.initializr.InitializrException; import com.edorasware.one.initializr.metadata.*; import com.edorasware.one.initializr.metadata.InitializrConfiguration.Env.Maven.ParentPom; import com.edorasware.one.initializr.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationEventPublisher; import org.springframework.util.Assert; import org.springframework.util.FileSystemUtils; import org.springframework.util.StreamUtils; import java.beans.PropertyDescriptor; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.*; import java.util.stream.Collectors;
public void setProjectResourceLocator(ProjectResourceLocator projectResourceLocator) { this.projectResourceLocator = projectResourceLocator; } public void setTmpdir(String tmpdir) { this.tmpdir = tmpdir; } public void setTemporaryDirectory(File temporaryDirectory) { this.temporaryDirectory = temporaryDirectory; } public void setTemporaryFiles(Map<String, List<File>> temporaryFiles) { this.temporaryFiles = temporaryFiles; } /** * Generate a Maven pom for the specified {@link ProjectRequest}. */ public byte[] generateMavenPom(ProjectRequest request) { try { Map<String, Object> model = resolveModel(request); if (!isMavenBuild(request)) { throw new InvalidProjectRequestException("Could not generate Maven pom, " + "invalid project type " + request.getType()); } byte[] content = doGenerateMavenPom(model); publishProjectGeneratedEvent(request); return content; }
// Path: src/main/java/com/edorasware/one/initializr/InitializrException.java // @SuppressWarnings("serial") // public class InitializrException extends RuntimeException { // // public InitializrException(String message, Throwable cause) { // super(message, cause); // } // // public InitializrException(String message) { // super(message); // } // // } // // Path: src/main/java/com/edorasware/one/initializr/metadata/InitializrConfiguration.java // public static class ParentPom { // // /** // * Parent pom groupId. // */ // private String groupId; // // /** // * Parent pom artifactId. // */ // private String artifactId; // // /** // * Parent pom version. // */ // private String version; // // public ParentPom(String groupId, String artifactId, String version) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // } // // public ParentPom() { // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public void validate() { // if (!((!StringUtils.hasText(groupId) // && !StringUtils.hasText(artifactId) // && !StringUtils.hasText(version)) // || (StringUtils.hasText(groupId) // && StringUtils.hasText(artifactId) // && StringUtils.hasText(version)))) { // throw new InvalidInitializrMetadataException("Custom maven pom " // + "requires groupId, artifactId and version"); // } // } // // } // Path: src/main/java/com/edorasware/one/initializr/generator/ProjectGenerator.java import com.edorasware.one.initializr.InitializrException; import com.edorasware.one.initializr.metadata.*; import com.edorasware.one.initializr.metadata.InitializrConfiguration.Env.Maven.ParentPom; import com.edorasware.one.initializr.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationEventPublisher; import org.springframework.util.Assert; import org.springframework.util.FileSystemUtils; import org.springframework.util.StreamUtils; import java.beans.PropertyDescriptor; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.*; import java.util.stream.Collectors; public void setProjectResourceLocator(ProjectResourceLocator projectResourceLocator) { this.projectResourceLocator = projectResourceLocator; } public void setTmpdir(String tmpdir) { this.tmpdir = tmpdir; } public void setTemporaryDirectory(File temporaryDirectory) { this.temporaryDirectory = temporaryDirectory; } public void setTemporaryFiles(Map<String, List<File>> temporaryFiles) { this.temporaryFiles = temporaryFiles; } /** * Generate a Maven pom for the specified {@link ProjectRequest}. */ public byte[] generateMavenPom(ProjectRequest request) { try { Map<String, Object> model = resolveModel(request); if (!isMavenBuild(request)) { throw new InvalidProjectRequestException("Could not generate Maven pom, " + "invalid project type " + request.getType()); } byte[] content = doGenerateMavenPom(model); publishProjectGeneratedEvent(request); return content; }
catch (InitializrException ex) {
rvillars/edoras-one-initializr
src/main/java/com/edorasware/one/initializr/generator/ProjectGenerator.java
// Path: src/main/java/com/edorasware/one/initializr/InitializrException.java // @SuppressWarnings("serial") // public class InitializrException extends RuntimeException { // // public InitializrException(String message, Throwable cause) { // super(message, cause); // } // // public InitializrException(String message) { // super(message); // } // // } // // Path: src/main/java/com/edorasware/one/initializr/metadata/InitializrConfiguration.java // public static class ParentPom { // // /** // * Parent pom groupId. // */ // private String groupId; // // /** // * Parent pom artifactId. // */ // private String artifactId; // // /** // * Parent pom version. // */ // private String version; // // public ParentPom(String groupId, String artifactId, String version) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // } // // public ParentPom() { // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public void validate() { // if (!((!StringUtils.hasText(groupId) // && !StringUtils.hasText(artifactId) // && !StringUtils.hasText(version)) // || (StringUtils.hasText(groupId) // && StringUtils.hasText(artifactId) // && StringUtils.hasText(version)))) { // throw new InvalidInitializrMetadataException("Custom maven pom " // + "requires groupId, artifactId and version"); // } // } // // }
import com.edorasware.one.initializr.InitializrException; import com.edorasware.one.initializr.metadata.*; import com.edorasware.one.initializr.metadata.InitializrConfiguration.Env.Maven.ParentPom; import com.edorasware.one.initializr.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationEventPublisher; import org.springframework.util.Assert; import org.springframework.util.FileSystemUtils; import org.springframework.util.StreamUtils; import java.beans.PropertyDescriptor; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.*; import java.util.stream.Collectors;
write(new File(dir, ".gitignore"), "gitignore.tmpl", model); } /** * Resolve the specified {@link ProjectRequest} and return the model to use to * generate the project * @param originalRequest the request to handle * @return a model for that request */ protected Map<String, Object> resolveModel(ProjectRequest originalRequest) { Assert.notNull(originalRequest.getEdorasoneVersion(), "edorasone version must not be null"); Map<String, Object> model = new LinkedHashMap<>(); InitializrMetadata metadata = metadataProvider.get(); ProjectRequest request = requestResolver.resolve(originalRequest, metadata); // request resolved so we can log what has been requested List<Dependency> dependencies = request.getResolvedDependencies(); List<String> dependencyIds = dependencies.stream().map(Dependency::getId) .collect(Collectors.toList()); log.info("Processing request{type=" + request.getType() + ", dependencies=" + dependencyIds); if (isWar(request)) { model.put("war", true); } if (isMavenBuild(request)) { model.put("mavenBuild", true);
// Path: src/main/java/com/edorasware/one/initializr/InitializrException.java // @SuppressWarnings("serial") // public class InitializrException extends RuntimeException { // // public InitializrException(String message, Throwable cause) { // super(message, cause); // } // // public InitializrException(String message) { // super(message); // } // // } // // Path: src/main/java/com/edorasware/one/initializr/metadata/InitializrConfiguration.java // public static class ParentPom { // // /** // * Parent pom groupId. // */ // private String groupId; // // /** // * Parent pom artifactId. // */ // private String artifactId; // // /** // * Parent pom version. // */ // private String version; // // public ParentPom(String groupId, String artifactId, String version) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // } // // public ParentPom() { // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public void validate() { // if (!((!StringUtils.hasText(groupId) // && !StringUtils.hasText(artifactId) // && !StringUtils.hasText(version)) // || (StringUtils.hasText(groupId) // && StringUtils.hasText(artifactId) // && StringUtils.hasText(version)))) { // throw new InvalidInitializrMetadataException("Custom maven pom " // + "requires groupId, artifactId and version"); // } // } // // } // Path: src/main/java/com/edorasware/one/initializr/generator/ProjectGenerator.java import com.edorasware.one.initializr.InitializrException; import com.edorasware.one.initializr.metadata.*; import com.edorasware.one.initializr.metadata.InitializrConfiguration.Env.Maven.ParentPom; import com.edorasware.one.initializr.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationEventPublisher; import org.springframework.util.Assert; import org.springframework.util.FileSystemUtils; import org.springframework.util.StreamUtils; import java.beans.PropertyDescriptor; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.*; import java.util.stream.Collectors; write(new File(dir, ".gitignore"), "gitignore.tmpl", model); } /** * Resolve the specified {@link ProjectRequest} and return the model to use to * generate the project * @param originalRequest the request to handle * @return a model for that request */ protected Map<String, Object> resolveModel(ProjectRequest originalRequest) { Assert.notNull(originalRequest.getEdorasoneVersion(), "edorasone version must not be null"); Map<String, Object> model = new LinkedHashMap<>(); InitializrMetadata metadata = metadataProvider.get(); ProjectRequest request = requestResolver.resolve(originalRequest, metadata); // request resolved so we can log what has been requested List<Dependency> dependencies = request.getResolvedDependencies(); List<String> dependencyIds = dependencies.stream().map(Dependency::getId) .collect(Collectors.toList()); log.info("Processing request{type=" + request.getType() + ", dependencies=" + dependencyIds); if (isWar(request)) { model.put("war", true); } if (isMavenBuild(request)) { model.put("mavenBuild", true);
ParentPom parentPom = null;