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 |
|---|---|---|---|---|---|---|
evolvingstuff/RecurrentJava | src/datasets/EmbeddedReberGrammar.java | // Path: src/datastructs/DataSequence.java
// public class DataSequence implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public List<DataStep> steps = new ArrayList<>();
//
// public DataSequence() {
//
// }
//
// public DataSequence(List<DataStep> steps) {
// this.steps = steps;
// }
//
// @Override
// public String toString() {
// String result = "";
// result += "========================================================\n";
// for (DataStep step : steps) {
// result += step.toString() + "\n";
// }
// result += "========================================================\n";
// return result;
// }
// }
//
// Path: src/datastructs/DataSet.java
// public abstract class DataSet implements Serializable {
// public int inputDimension;
// public int outputDimension;
// public Loss lossTraining;
// public Loss lossReporting;
// public List<DataSequence> training;
// public List<DataSequence> validation;
// public List<DataSequence> testing;
// public abstract void DisplayReport(Model model, Random rng) throws Exception;
// public abstract Nonlinearity getModelOutputUnitToUse();
// }
//
// Path: src/datastructs/DataStep.java
// public class DataStep implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public Matrix input = null;
// public Matrix targetOutput = null;
//
// public DataStep() {
//
// }
//
// public DataStep(double[] input, double[] targetOutput) {
// this.input = new Matrix(input);
// if (targetOutput != null) {
// this.targetOutput = new Matrix(targetOutput);
// }
// }
//
// @Override
// public String toString() {
// String result = "";
// for (int i = 0; i < input.w.length; i++) {
// result += String.format("%.5f", input.w[i]) + "\t";
// }
// result += "\t->\t";
// if (targetOutput != null) {
// for (int i = 0; i < targetOutput.w.length; i++) {
// result += String.format("%.5f", targetOutput.w[i]) + "\t";
// }
// }
// else {
// result += "___\t";
// }
// return result;
// }
// }
//
// Path: src/loss/LossMultiDimensionalBinary.java
// public class LossMultiDimensionalBinary implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// throw new Exception("not implemented");
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// if (actualOutput.w.length != targetOutput.w.length) {
// throw new Exception("mismatch");
// }
//
// for (int i = 0; i < targetOutput.w.length; i++) {
// if (targetOutput.w[i] >= 0.5 && actualOutput.w[i] < 0.5) {
// return 1;
// }
// if (targetOutput.w[i] < 0.5 && actualOutput.w[i] >= 0.5) {
// return 1;
// }
// }
// return 0;
// }
//
// }
//
// Path: src/loss/LossSumOfSquares.java
// public class LossSumOfSquares implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// actualOutput.dw[i] += errDelta;
// }
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// double sum = 0;
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// sum += 0.5 * errDelta * errDelta;
// }
// return sum;
// }
// }
//
// Path: src/model/Model.java
// public interface Model extends Serializable {
// Matrix forward(Matrix input, Graph g) throws Exception;
// void resetState();
// List<Matrix> getParameters();
// }
//
// Path: src/model/SigmoidUnit.java
// public class SigmoidUnit implements Nonlinearity {
//
// private static final long serialVersionUID = 1L;
//
// @Override
// public double forward(double x) {
// return 1 / (1 + Math.exp(-x));
// }
//
// @Override
// public double backward(double x) {
// double act = forward(x);
// return act * (1 - act);
// }
// }
| import java.util.*;
import datastructs.DataSequence;
import datastructs.DataSet;
import datastructs.DataStep;
import loss.LossMultiDimensionalBinary;
import loss.LossSumOfSquares;
import model.Model;
import model.Nonlinearity;
import model.SigmoidUnit; | package datasets;
public class EmbeddedReberGrammar extends DataSet {
static public class State {
public State(Transition[] transitions) {
this.transitions = transitions;
}
public Transition[] transitions;
}
static public class Transition {
public Transition(int next_state_id, int token) {
this.next_state_id = next_state_id;
this.token = token;
}
public int next_state_id;
public int token;
}
public EmbeddedReberGrammar(Random r) throws Exception {
int total_sequences = 1000;
inputDimension = 7;
outputDimension = 7; | // Path: src/datastructs/DataSequence.java
// public class DataSequence implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public List<DataStep> steps = new ArrayList<>();
//
// public DataSequence() {
//
// }
//
// public DataSequence(List<DataStep> steps) {
// this.steps = steps;
// }
//
// @Override
// public String toString() {
// String result = "";
// result += "========================================================\n";
// for (DataStep step : steps) {
// result += step.toString() + "\n";
// }
// result += "========================================================\n";
// return result;
// }
// }
//
// Path: src/datastructs/DataSet.java
// public abstract class DataSet implements Serializable {
// public int inputDimension;
// public int outputDimension;
// public Loss lossTraining;
// public Loss lossReporting;
// public List<DataSequence> training;
// public List<DataSequence> validation;
// public List<DataSequence> testing;
// public abstract void DisplayReport(Model model, Random rng) throws Exception;
// public abstract Nonlinearity getModelOutputUnitToUse();
// }
//
// Path: src/datastructs/DataStep.java
// public class DataStep implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public Matrix input = null;
// public Matrix targetOutput = null;
//
// public DataStep() {
//
// }
//
// public DataStep(double[] input, double[] targetOutput) {
// this.input = new Matrix(input);
// if (targetOutput != null) {
// this.targetOutput = new Matrix(targetOutput);
// }
// }
//
// @Override
// public String toString() {
// String result = "";
// for (int i = 0; i < input.w.length; i++) {
// result += String.format("%.5f", input.w[i]) + "\t";
// }
// result += "\t->\t";
// if (targetOutput != null) {
// for (int i = 0; i < targetOutput.w.length; i++) {
// result += String.format("%.5f", targetOutput.w[i]) + "\t";
// }
// }
// else {
// result += "___\t";
// }
// return result;
// }
// }
//
// Path: src/loss/LossMultiDimensionalBinary.java
// public class LossMultiDimensionalBinary implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// throw new Exception("not implemented");
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// if (actualOutput.w.length != targetOutput.w.length) {
// throw new Exception("mismatch");
// }
//
// for (int i = 0; i < targetOutput.w.length; i++) {
// if (targetOutput.w[i] >= 0.5 && actualOutput.w[i] < 0.5) {
// return 1;
// }
// if (targetOutput.w[i] < 0.5 && actualOutput.w[i] >= 0.5) {
// return 1;
// }
// }
// return 0;
// }
//
// }
//
// Path: src/loss/LossSumOfSquares.java
// public class LossSumOfSquares implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// actualOutput.dw[i] += errDelta;
// }
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// double sum = 0;
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// sum += 0.5 * errDelta * errDelta;
// }
// return sum;
// }
// }
//
// Path: src/model/Model.java
// public interface Model extends Serializable {
// Matrix forward(Matrix input, Graph g) throws Exception;
// void resetState();
// List<Matrix> getParameters();
// }
//
// Path: src/model/SigmoidUnit.java
// public class SigmoidUnit implements Nonlinearity {
//
// private static final long serialVersionUID = 1L;
//
// @Override
// public double forward(double x) {
// return 1 / (1 + Math.exp(-x));
// }
//
// @Override
// public double backward(double x) {
// double act = forward(x);
// return act * (1 - act);
// }
// }
// Path: src/datasets/EmbeddedReberGrammar.java
import java.util.*;
import datastructs.DataSequence;
import datastructs.DataSet;
import datastructs.DataStep;
import loss.LossMultiDimensionalBinary;
import loss.LossSumOfSquares;
import model.Model;
import model.Nonlinearity;
import model.SigmoidUnit;
package datasets;
public class EmbeddedReberGrammar extends DataSet {
static public class State {
public State(Transition[] transitions) {
this.transitions = transitions;
}
public Transition[] transitions;
}
static public class Transition {
public Transition(int next_state_id, int token) {
this.next_state_id = next_state_id;
this.token = token;
}
public int next_state_id;
public int token;
}
public EmbeddedReberGrammar(Random r) throws Exception {
int total_sequences = 1000;
inputDimension = 7;
outputDimension = 7; | lossTraining = new LossSumOfSquares(); |
evolvingstuff/RecurrentJava | src/datasets/EmbeddedReberGrammar.java | // Path: src/datastructs/DataSequence.java
// public class DataSequence implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public List<DataStep> steps = new ArrayList<>();
//
// public DataSequence() {
//
// }
//
// public DataSequence(List<DataStep> steps) {
// this.steps = steps;
// }
//
// @Override
// public String toString() {
// String result = "";
// result += "========================================================\n";
// for (DataStep step : steps) {
// result += step.toString() + "\n";
// }
// result += "========================================================\n";
// return result;
// }
// }
//
// Path: src/datastructs/DataSet.java
// public abstract class DataSet implements Serializable {
// public int inputDimension;
// public int outputDimension;
// public Loss lossTraining;
// public Loss lossReporting;
// public List<DataSequence> training;
// public List<DataSequence> validation;
// public List<DataSequence> testing;
// public abstract void DisplayReport(Model model, Random rng) throws Exception;
// public abstract Nonlinearity getModelOutputUnitToUse();
// }
//
// Path: src/datastructs/DataStep.java
// public class DataStep implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public Matrix input = null;
// public Matrix targetOutput = null;
//
// public DataStep() {
//
// }
//
// public DataStep(double[] input, double[] targetOutput) {
// this.input = new Matrix(input);
// if (targetOutput != null) {
// this.targetOutput = new Matrix(targetOutput);
// }
// }
//
// @Override
// public String toString() {
// String result = "";
// for (int i = 0; i < input.w.length; i++) {
// result += String.format("%.5f", input.w[i]) + "\t";
// }
// result += "\t->\t";
// if (targetOutput != null) {
// for (int i = 0; i < targetOutput.w.length; i++) {
// result += String.format("%.5f", targetOutput.w[i]) + "\t";
// }
// }
// else {
// result += "___\t";
// }
// return result;
// }
// }
//
// Path: src/loss/LossMultiDimensionalBinary.java
// public class LossMultiDimensionalBinary implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// throw new Exception("not implemented");
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// if (actualOutput.w.length != targetOutput.w.length) {
// throw new Exception("mismatch");
// }
//
// for (int i = 0; i < targetOutput.w.length; i++) {
// if (targetOutput.w[i] >= 0.5 && actualOutput.w[i] < 0.5) {
// return 1;
// }
// if (targetOutput.w[i] < 0.5 && actualOutput.w[i] >= 0.5) {
// return 1;
// }
// }
// return 0;
// }
//
// }
//
// Path: src/loss/LossSumOfSquares.java
// public class LossSumOfSquares implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// actualOutput.dw[i] += errDelta;
// }
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// double sum = 0;
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// sum += 0.5 * errDelta * errDelta;
// }
// return sum;
// }
// }
//
// Path: src/model/Model.java
// public interface Model extends Serializable {
// Matrix forward(Matrix input, Graph g) throws Exception;
// void resetState();
// List<Matrix> getParameters();
// }
//
// Path: src/model/SigmoidUnit.java
// public class SigmoidUnit implements Nonlinearity {
//
// private static final long serialVersionUID = 1L;
//
// @Override
// public double forward(double x) {
// return 1 / (1 + Math.exp(-x));
// }
//
// @Override
// public double backward(double x) {
// double act = forward(x);
// return act * (1 - act);
// }
// }
| import java.util.*;
import datastructs.DataSequence;
import datastructs.DataSet;
import datastructs.DataStep;
import loss.LossMultiDimensionalBinary;
import loss.LossSumOfSquares;
import model.Model;
import model.Nonlinearity;
import model.SigmoidUnit; | package datasets;
public class EmbeddedReberGrammar extends DataSet {
static public class State {
public State(Transition[] transitions) {
this.transitions = transitions;
}
public Transition[] transitions;
}
static public class Transition {
public Transition(int next_state_id, int token) {
this.next_state_id = next_state_id;
this.token = token;
}
public int next_state_id;
public int token;
}
public EmbeddedReberGrammar(Random r) throws Exception {
int total_sequences = 1000;
inputDimension = 7;
outputDimension = 7;
lossTraining = new LossSumOfSquares(); | // Path: src/datastructs/DataSequence.java
// public class DataSequence implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public List<DataStep> steps = new ArrayList<>();
//
// public DataSequence() {
//
// }
//
// public DataSequence(List<DataStep> steps) {
// this.steps = steps;
// }
//
// @Override
// public String toString() {
// String result = "";
// result += "========================================================\n";
// for (DataStep step : steps) {
// result += step.toString() + "\n";
// }
// result += "========================================================\n";
// return result;
// }
// }
//
// Path: src/datastructs/DataSet.java
// public abstract class DataSet implements Serializable {
// public int inputDimension;
// public int outputDimension;
// public Loss lossTraining;
// public Loss lossReporting;
// public List<DataSequence> training;
// public List<DataSequence> validation;
// public List<DataSequence> testing;
// public abstract void DisplayReport(Model model, Random rng) throws Exception;
// public abstract Nonlinearity getModelOutputUnitToUse();
// }
//
// Path: src/datastructs/DataStep.java
// public class DataStep implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public Matrix input = null;
// public Matrix targetOutput = null;
//
// public DataStep() {
//
// }
//
// public DataStep(double[] input, double[] targetOutput) {
// this.input = new Matrix(input);
// if (targetOutput != null) {
// this.targetOutput = new Matrix(targetOutput);
// }
// }
//
// @Override
// public String toString() {
// String result = "";
// for (int i = 0; i < input.w.length; i++) {
// result += String.format("%.5f", input.w[i]) + "\t";
// }
// result += "\t->\t";
// if (targetOutput != null) {
// for (int i = 0; i < targetOutput.w.length; i++) {
// result += String.format("%.5f", targetOutput.w[i]) + "\t";
// }
// }
// else {
// result += "___\t";
// }
// return result;
// }
// }
//
// Path: src/loss/LossMultiDimensionalBinary.java
// public class LossMultiDimensionalBinary implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// throw new Exception("not implemented");
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// if (actualOutput.w.length != targetOutput.w.length) {
// throw new Exception("mismatch");
// }
//
// for (int i = 0; i < targetOutput.w.length; i++) {
// if (targetOutput.w[i] >= 0.5 && actualOutput.w[i] < 0.5) {
// return 1;
// }
// if (targetOutput.w[i] < 0.5 && actualOutput.w[i] >= 0.5) {
// return 1;
// }
// }
// return 0;
// }
//
// }
//
// Path: src/loss/LossSumOfSquares.java
// public class LossSumOfSquares implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// actualOutput.dw[i] += errDelta;
// }
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// double sum = 0;
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// sum += 0.5 * errDelta * errDelta;
// }
// return sum;
// }
// }
//
// Path: src/model/Model.java
// public interface Model extends Serializable {
// Matrix forward(Matrix input, Graph g) throws Exception;
// void resetState();
// List<Matrix> getParameters();
// }
//
// Path: src/model/SigmoidUnit.java
// public class SigmoidUnit implements Nonlinearity {
//
// private static final long serialVersionUID = 1L;
//
// @Override
// public double forward(double x) {
// return 1 / (1 + Math.exp(-x));
// }
//
// @Override
// public double backward(double x) {
// double act = forward(x);
// return act * (1 - act);
// }
// }
// Path: src/datasets/EmbeddedReberGrammar.java
import java.util.*;
import datastructs.DataSequence;
import datastructs.DataSet;
import datastructs.DataStep;
import loss.LossMultiDimensionalBinary;
import loss.LossSumOfSquares;
import model.Model;
import model.Nonlinearity;
import model.SigmoidUnit;
package datasets;
public class EmbeddedReberGrammar extends DataSet {
static public class State {
public State(Transition[] transitions) {
this.transitions = transitions;
}
public Transition[] transitions;
}
static public class Transition {
public Transition(int next_state_id, int token) {
this.next_state_id = next_state_id;
this.token = token;
}
public int next_state_id;
public int token;
}
public EmbeddedReberGrammar(Random r) throws Exception {
int total_sequences = 1000;
inputDimension = 7;
outputDimension = 7;
lossTraining = new LossSumOfSquares(); | lossReporting = new LossMultiDimensionalBinary(); |
evolvingstuff/RecurrentJava | src/datasets/EmbeddedReberGrammar.java | // Path: src/datastructs/DataSequence.java
// public class DataSequence implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public List<DataStep> steps = new ArrayList<>();
//
// public DataSequence() {
//
// }
//
// public DataSequence(List<DataStep> steps) {
// this.steps = steps;
// }
//
// @Override
// public String toString() {
// String result = "";
// result += "========================================================\n";
// for (DataStep step : steps) {
// result += step.toString() + "\n";
// }
// result += "========================================================\n";
// return result;
// }
// }
//
// Path: src/datastructs/DataSet.java
// public abstract class DataSet implements Serializable {
// public int inputDimension;
// public int outputDimension;
// public Loss lossTraining;
// public Loss lossReporting;
// public List<DataSequence> training;
// public List<DataSequence> validation;
// public List<DataSequence> testing;
// public abstract void DisplayReport(Model model, Random rng) throws Exception;
// public abstract Nonlinearity getModelOutputUnitToUse();
// }
//
// Path: src/datastructs/DataStep.java
// public class DataStep implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public Matrix input = null;
// public Matrix targetOutput = null;
//
// public DataStep() {
//
// }
//
// public DataStep(double[] input, double[] targetOutput) {
// this.input = new Matrix(input);
// if (targetOutput != null) {
// this.targetOutput = new Matrix(targetOutput);
// }
// }
//
// @Override
// public String toString() {
// String result = "";
// for (int i = 0; i < input.w.length; i++) {
// result += String.format("%.5f", input.w[i]) + "\t";
// }
// result += "\t->\t";
// if (targetOutput != null) {
// for (int i = 0; i < targetOutput.w.length; i++) {
// result += String.format("%.5f", targetOutput.w[i]) + "\t";
// }
// }
// else {
// result += "___\t";
// }
// return result;
// }
// }
//
// Path: src/loss/LossMultiDimensionalBinary.java
// public class LossMultiDimensionalBinary implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// throw new Exception("not implemented");
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// if (actualOutput.w.length != targetOutput.w.length) {
// throw new Exception("mismatch");
// }
//
// for (int i = 0; i < targetOutput.w.length; i++) {
// if (targetOutput.w[i] >= 0.5 && actualOutput.w[i] < 0.5) {
// return 1;
// }
// if (targetOutput.w[i] < 0.5 && actualOutput.w[i] >= 0.5) {
// return 1;
// }
// }
// return 0;
// }
//
// }
//
// Path: src/loss/LossSumOfSquares.java
// public class LossSumOfSquares implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// actualOutput.dw[i] += errDelta;
// }
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// double sum = 0;
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// sum += 0.5 * errDelta * errDelta;
// }
// return sum;
// }
// }
//
// Path: src/model/Model.java
// public interface Model extends Serializable {
// Matrix forward(Matrix input, Graph g) throws Exception;
// void resetState();
// List<Matrix> getParameters();
// }
//
// Path: src/model/SigmoidUnit.java
// public class SigmoidUnit implements Nonlinearity {
//
// private static final long serialVersionUID = 1L;
//
// @Override
// public double forward(double x) {
// return 1 / (1 + Math.exp(-x));
// }
//
// @Override
// public double backward(double x) {
// double act = forward(x);
// return act * (1 - act);
// }
// }
| import java.util.*;
import datastructs.DataSequence;
import datastructs.DataSet;
import datastructs.DataStep;
import loss.LossMultiDimensionalBinary;
import loss.LossSumOfSquares;
import model.Model;
import model.Nonlinearity;
import model.SigmoidUnit; | package datasets;
public class EmbeddedReberGrammar extends DataSet {
static public class State {
public State(Transition[] transitions) {
this.transitions = transitions;
}
public Transition[] transitions;
}
static public class Transition {
public Transition(int next_state_id, int token) {
this.next_state_id = next_state_id;
this.token = token;
}
public int next_state_id;
public int token;
}
public EmbeddedReberGrammar(Random r) throws Exception {
int total_sequences = 1000;
inputDimension = 7;
outputDimension = 7;
lossTraining = new LossSumOfSquares();
lossReporting = new LossMultiDimensionalBinary();
training = generateSequences(r, total_sequences);
validation = generateSequences(r, total_sequences);
testing = generateSequences(r, total_sequences);
}
| // Path: src/datastructs/DataSequence.java
// public class DataSequence implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public List<DataStep> steps = new ArrayList<>();
//
// public DataSequence() {
//
// }
//
// public DataSequence(List<DataStep> steps) {
// this.steps = steps;
// }
//
// @Override
// public String toString() {
// String result = "";
// result += "========================================================\n";
// for (DataStep step : steps) {
// result += step.toString() + "\n";
// }
// result += "========================================================\n";
// return result;
// }
// }
//
// Path: src/datastructs/DataSet.java
// public abstract class DataSet implements Serializable {
// public int inputDimension;
// public int outputDimension;
// public Loss lossTraining;
// public Loss lossReporting;
// public List<DataSequence> training;
// public List<DataSequence> validation;
// public List<DataSequence> testing;
// public abstract void DisplayReport(Model model, Random rng) throws Exception;
// public abstract Nonlinearity getModelOutputUnitToUse();
// }
//
// Path: src/datastructs/DataStep.java
// public class DataStep implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public Matrix input = null;
// public Matrix targetOutput = null;
//
// public DataStep() {
//
// }
//
// public DataStep(double[] input, double[] targetOutput) {
// this.input = new Matrix(input);
// if (targetOutput != null) {
// this.targetOutput = new Matrix(targetOutput);
// }
// }
//
// @Override
// public String toString() {
// String result = "";
// for (int i = 0; i < input.w.length; i++) {
// result += String.format("%.5f", input.w[i]) + "\t";
// }
// result += "\t->\t";
// if (targetOutput != null) {
// for (int i = 0; i < targetOutput.w.length; i++) {
// result += String.format("%.5f", targetOutput.w[i]) + "\t";
// }
// }
// else {
// result += "___\t";
// }
// return result;
// }
// }
//
// Path: src/loss/LossMultiDimensionalBinary.java
// public class LossMultiDimensionalBinary implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// throw new Exception("not implemented");
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// if (actualOutput.w.length != targetOutput.w.length) {
// throw new Exception("mismatch");
// }
//
// for (int i = 0; i < targetOutput.w.length; i++) {
// if (targetOutput.w[i] >= 0.5 && actualOutput.w[i] < 0.5) {
// return 1;
// }
// if (targetOutput.w[i] < 0.5 && actualOutput.w[i] >= 0.5) {
// return 1;
// }
// }
// return 0;
// }
//
// }
//
// Path: src/loss/LossSumOfSquares.java
// public class LossSumOfSquares implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// actualOutput.dw[i] += errDelta;
// }
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// double sum = 0;
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// sum += 0.5 * errDelta * errDelta;
// }
// return sum;
// }
// }
//
// Path: src/model/Model.java
// public interface Model extends Serializable {
// Matrix forward(Matrix input, Graph g) throws Exception;
// void resetState();
// List<Matrix> getParameters();
// }
//
// Path: src/model/SigmoidUnit.java
// public class SigmoidUnit implements Nonlinearity {
//
// private static final long serialVersionUID = 1L;
//
// @Override
// public double forward(double x) {
// return 1 / (1 + Math.exp(-x));
// }
//
// @Override
// public double backward(double x) {
// double act = forward(x);
// return act * (1 - act);
// }
// }
// Path: src/datasets/EmbeddedReberGrammar.java
import java.util.*;
import datastructs.DataSequence;
import datastructs.DataSet;
import datastructs.DataStep;
import loss.LossMultiDimensionalBinary;
import loss.LossSumOfSquares;
import model.Model;
import model.Nonlinearity;
import model.SigmoidUnit;
package datasets;
public class EmbeddedReberGrammar extends DataSet {
static public class State {
public State(Transition[] transitions) {
this.transitions = transitions;
}
public Transition[] transitions;
}
static public class Transition {
public Transition(int next_state_id, int token) {
this.next_state_id = next_state_id;
this.token = token;
}
public int next_state_id;
public int token;
}
public EmbeddedReberGrammar(Random r) throws Exception {
int total_sequences = 1000;
inputDimension = 7;
outputDimension = 7;
lossTraining = new LossSumOfSquares();
lossReporting = new LossMultiDimensionalBinary();
training = generateSequences(r, total_sequences);
validation = generateSequences(r, total_sequences);
testing = generateSequences(r, total_sequences);
}
| public static List<DataSequence> generateSequences(Random r, int sequences) { |
evolvingstuff/RecurrentJava | src/datasets/EmbeddedReberGrammar.java | // Path: src/datastructs/DataSequence.java
// public class DataSequence implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public List<DataStep> steps = new ArrayList<>();
//
// public DataSequence() {
//
// }
//
// public DataSequence(List<DataStep> steps) {
// this.steps = steps;
// }
//
// @Override
// public String toString() {
// String result = "";
// result += "========================================================\n";
// for (DataStep step : steps) {
// result += step.toString() + "\n";
// }
// result += "========================================================\n";
// return result;
// }
// }
//
// Path: src/datastructs/DataSet.java
// public abstract class DataSet implements Serializable {
// public int inputDimension;
// public int outputDimension;
// public Loss lossTraining;
// public Loss lossReporting;
// public List<DataSequence> training;
// public List<DataSequence> validation;
// public List<DataSequence> testing;
// public abstract void DisplayReport(Model model, Random rng) throws Exception;
// public abstract Nonlinearity getModelOutputUnitToUse();
// }
//
// Path: src/datastructs/DataStep.java
// public class DataStep implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public Matrix input = null;
// public Matrix targetOutput = null;
//
// public DataStep() {
//
// }
//
// public DataStep(double[] input, double[] targetOutput) {
// this.input = new Matrix(input);
// if (targetOutput != null) {
// this.targetOutput = new Matrix(targetOutput);
// }
// }
//
// @Override
// public String toString() {
// String result = "";
// for (int i = 0; i < input.w.length; i++) {
// result += String.format("%.5f", input.w[i]) + "\t";
// }
// result += "\t->\t";
// if (targetOutput != null) {
// for (int i = 0; i < targetOutput.w.length; i++) {
// result += String.format("%.5f", targetOutput.w[i]) + "\t";
// }
// }
// else {
// result += "___\t";
// }
// return result;
// }
// }
//
// Path: src/loss/LossMultiDimensionalBinary.java
// public class LossMultiDimensionalBinary implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// throw new Exception("not implemented");
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// if (actualOutput.w.length != targetOutput.w.length) {
// throw new Exception("mismatch");
// }
//
// for (int i = 0; i < targetOutput.w.length; i++) {
// if (targetOutput.w[i] >= 0.5 && actualOutput.w[i] < 0.5) {
// return 1;
// }
// if (targetOutput.w[i] < 0.5 && actualOutput.w[i] >= 0.5) {
// return 1;
// }
// }
// return 0;
// }
//
// }
//
// Path: src/loss/LossSumOfSquares.java
// public class LossSumOfSquares implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// actualOutput.dw[i] += errDelta;
// }
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// double sum = 0;
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// sum += 0.5 * errDelta * errDelta;
// }
// return sum;
// }
// }
//
// Path: src/model/Model.java
// public interface Model extends Serializable {
// Matrix forward(Matrix input, Graph g) throws Exception;
// void resetState();
// List<Matrix> getParameters();
// }
//
// Path: src/model/SigmoidUnit.java
// public class SigmoidUnit implements Nonlinearity {
//
// private static final long serialVersionUID = 1L;
//
// @Override
// public double forward(double x) {
// return 1 / (1 + Math.exp(-x));
// }
//
// @Override
// public double backward(double x) {
// double act = forward(x);
// return act * (1 - act);
// }
// }
| import java.util.*;
import datastructs.DataSequence;
import datastructs.DataSet;
import datastructs.DataStep;
import loss.LossMultiDimensionalBinary;
import loss.LossSumOfSquares;
import model.Model;
import model.Nonlinearity;
import model.SigmoidUnit; | transition = r.nextInt(2);
}
double[] observation = null;
observation = new double[7];
observation[states[state_id].transitions[transition].token] = 1.0;
state_id = states[state_id].transitions[transition].next_state_id;
if (state_id == 0) { //exit at end of sequence
break;
}
double[] target_output = new double[7];
for (int i = 0; i < states[state_id].transitions.length; i++) {
target_output[states[state_id].transitions[i].token] = 1.0;
}
steps.add(new DataStep(observation, target_output));
}
result.add(new DataSequence(steps));
}
return result;
}
@Override
public void DisplayReport(Model model, Random rng) throws Exception {
// TODO Auto-generated method stub
}
@Override
public Nonlinearity getModelOutputUnitToUse() { | // Path: src/datastructs/DataSequence.java
// public class DataSequence implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public List<DataStep> steps = new ArrayList<>();
//
// public DataSequence() {
//
// }
//
// public DataSequence(List<DataStep> steps) {
// this.steps = steps;
// }
//
// @Override
// public String toString() {
// String result = "";
// result += "========================================================\n";
// for (DataStep step : steps) {
// result += step.toString() + "\n";
// }
// result += "========================================================\n";
// return result;
// }
// }
//
// Path: src/datastructs/DataSet.java
// public abstract class DataSet implements Serializable {
// public int inputDimension;
// public int outputDimension;
// public Loss lossTraining;
// public Loss lossReporting;
// public List<DataSequence> training;
// public List<DataSequence> validation;
// public List<DataSequence> testing;
// public abstract void DisplayReport(Model model, Random rng) throws Exception;
// public abstract Nonlinearity getModelOutputUnitToUse();
// }
//
// Path: src/datastructs/DataStep.java
// public class DataStep implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public Matrix input = null;
// public Matrix targetOutput = null;
//
// public DataStep() {
//
// }
//
// public DataStep(double[] input, double[] targetOutput) {
// this.input = new Matrix(input);
// if (targetOutput != null) {
// this.targetOutput = new Matrix(targetOutput);
// }
// }
//
// @Override
// public String toString() {
// String result = "";
// for (int i = 0; i < input.w.length; i++) {
// result += String.format("%.5f", input.w[i]) + "\t";
// }
// result += "\t->\t";
// if (targetOutput != null) {
// for (int i = 0; i < targetOutput.w.length; i++) {
// result += String.format("%.5f", targetOutput.w[i]) + "\t";
// }
// }
// else {
// result += "___\t";
// }
// return result;
// }
// }
//
// Path: src/loss/LossMultiDimensionalBinary.java
// public class LossMultiDimensionalBinary implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// throw new Exception("not implemented");
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// if (actualOutput.w.length != targetOutput.w.length) {
// throw new Exception("mismatch");
// }
//
// for (int i = 0; i < targetOutput.w.length; i++) {
// if (targetOutput.w[i] >= 0.5 && actualOutput.w[i] < 0.5) {
// return 1;
// }
// if (targetOutput.w[i] < 0.5 && actualOutput.w[i] >= 0.5) {
// return 1;
// }
// }
// return 0;
// }
//
// }
//
// Path: src/loss/LossSumOfSquares.java
// public class LossSumOfSquares implements Loss {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// actualOutput.dw[i] += errDelta;
// }
// }
//
// @Override
// public double measure(Matrix actualOutput, Matrix targetOutput) throws Exception {
// double sum = 0;
// for (int i = 0; i < targetOutput.w.length; i++) {
// double errDelta = actualOutput.w[i] - targetOutput.w[i];
// sum += 0.5 * errDelta * errDelta;
// }
// return sum;
// }
// }
//
// Path: src/model/Model.java
// public interface Model extends Serializable {
// Matrix forward(Matrix input, Graph g) throws Exception;
// void resetState();
// List<Matrix> getParameters();
// }
//
// Path: src/model/SigmoidUnit.java
// public class SigmoidUnit implements Nonlinearity {
//
// private static final long serialVersionUID = 1L;
//
// @Override
// public double forward(double x) {
// return 1 / (1 + Math.exp(-x));
// }
//
// @Override
// public double backward(double x) {
// double act = forward(x);
// return act * (1 - act);
// }
// }
// Path: src/datasets/EmbeddedReberGrammar.java
import java.util.*;
import datastructs.DataSequence;
import datastructs.DataSet;
import datastructs.DataStep;
import loss.LossMultiDimensionalBinary;
import loss.LossSumOfSquares;
import model.Model;
import model.Nonlinearity;
import model.SigmoidUnit;
transition = r.nextInt(2);
}
double[] observation = null;
observation = new double[7];
observation[states[state_id].transitions[transition].token] = 1.0;
state_id = states[state_id].transitions[transition].next_state_id;
if (state_id == 0) { //exit at end of sequence
break;
}
double[] target_output = new double[7];
for (int i = 0; i < states[state_id].transitions.length; i++) {
target_output[states[state_id].transitions[i].token] = 1.0;
}
steps.add(new DataStep(observation, target_output));
}
result.add(new DataSequence(steps));
}
return result;
}
@Override
public void DisplayReport(Model model, Random rng) throws Exception {
// TODO Auto-generated method stub
}
@Override
public Nonlinearity getModelOutputUnitToUse() { | return new SigmoidUnit(); |
evolvingstuff/RecurrentJava | src/loss/LossSumOfSquares.java | // Path: src/matrix/Matrix.java
// public class Matrix implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public int rows;
// public int cols;
// public double[] w;
// public double[] dw;
// public double[] stepCache;
//
// @Override
// public String toString() {
// String result = "";
// for (int r = 0; r < rows; r++) {
// for (int c = 0; c < cols; c++) {
// result += String.format("%.4f",getW(r, c)) + "\t";
// }
// result += "\n";
// }
// return result;
// }
//
// public Matrix clone() {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < w.length; i++) {
// result.w[i] = w[i];
// result.dw[i] = dw[i];
// result.stepCache[i] = stepCache[i];
// }
// return result;
// }
//
// public void resetDw() {
// for (int i = 0; i < dw.length; i++) {
// dw[i] = 0;
// }
// }
//
// public void resetStepCache() {
// for (int i = 0; i < stepCache.length; i++) {
// stepCache[i] = 0;
// }
// }
//
// public static Matrix transpose(Matrix m) {
// Matrix result = new Matrix(m.cols, m.rows);
// for (int r = 0; r < m.rows; r++) {
// for (int c = 0; c < m.cols; c++) {
// result.setW(c, r, m.getW(r, c));
// }
// }
// return result;
// }
//
// public static Matrix rand(int rows, int cols, double initParamsStdDev, Random rng) {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < result.w.length; i++) {
// result.w[i] = rng.nextGaussian() * initParamsStdDev;
// }
// return result;
// }
//
// public static Matrix ident(int dim) {
// Matrix result = new Matrix(dim, dim);
// for (int i = 0; i < dim; i++) {
// result.setW(i, i, 1.0);
// }
// return result;
// }
//
// public static Matrix uniform(int rows, int cols, double s) {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < result.w.length; i++) {
// result.w[i] = s;
// }
// return result;
// }
//
// public static Matrix ones(int rows, int cols) {
// return uniform(rows, cols, 1.0);
// }
//
// public static Matrix negones(int rows, int cols) {
// return uniform(rows, cols, -1.0);
// }
//
// public Matrix(int dim) {
// this.rows = dim;
// this.cols = 1;
// this.w = new double[rows * cols];
// this.dw = new double[rows * cols];
// this.stepCache = new double[rows * cols];
// }
//
// public Matrix(int rows, int cols) {
// this.rows = rows;
// this.cols = cols;
// this.w = new double[rows * cols];
// this.dw = new double[rows * cols];
// this.stepCache = new double[rows * cols];
// }
//
// public Matrix(double[] vector) {
// this.rows = vector.length;
// this.cols = 1;
// this.w = vector;
// this.dw = new double[vector.length];
// this.stepCache = new double[vector.length];
// }
//
// private int index(int row, int col) {
// int ix = cols * row + col;
// return ix;
// }
//
// private double getW(int row, int col) {
// return w[index(row, col)];
// }
//
// private void setW(int row, int col, double val) {
// w[index(row, col)] = val;
// }
// }
| import matrix.Matrix; | package loss;
public class LossSumOfSquares implements Loss {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override | // Path: src/matrix/Matrix.java
// public class Matrix implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public int rows;
// public int cols;
// public double[] w;
// public double[] dw;
// public double[] stepCache;
//
// @Override
// public String toString() {
// String result = "";
// for (int r = 0; r < rows; r++) {
// for (int c = 0; c < cols; c++) {
// result += String.format("%.4f",getW(r, c)) + "\t";
// }
// result += "\n";
// }
// return result;
// }
//
// public Matrix clone() {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < w.length; i++) {
// result.w[i] = w[i];
// result.dw[i] = dw[i];
// result.stepCache[i] = stepCache[i];
// }
// return result;
// }
//
// public void resetDw() {
// for (int i = 0; i < dw.length; i++) {
// dw[i] = 0;
// }
// }
//
// public void resetStepCache() {
// for (int i = 0; i < stepCache.length; i++) {
// stepCache[i] = 0;
// }
// }
//
// public static Matrix transpose(Matrix m) {
// Matrix result = new Matrix(m.cols, m.rows);
// for (int r = 0; r < m.rows; r++) {
// for (int c = 0; c < m.cols; c++) {
// result.setW(c, r, m.getW(r, c));
// }
// }
// return result;
// }
//
// public static Matrix rand(int rows, int cols, double initParamsStdDev, Random rng) {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < result.w.length; i++) {
// result.w[i] = rng.nextGaussian() * initParamsStdDev;
// }
// return result;
// }
//
// public static Matrix ident(int dim) {
// Matrix result = new Matrix(dim, dim);
// for (int i = 0; i < dim; i++) {
// result.setW(i, i, 1.0);
// }
// return result;
// }
//
// public static Matrix uniform(int rows, int cols, double s) {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < result.w.length; i++) {
// result.w[i] = s;
// }
// return result;
// }
//
// public static Matrix ones(int rows, int cols) {
// return uniform(rows, cols, 1.0);
// }
//
// public static Matrix negones(int rows, int cols) {
// return uniform(rows, cols, -1.0);
// }
//
// public Matrix(int dim) {
// this.rows = dim;
// this.cols = 1;
// this.w = new double[rows * cols];
// this.dw = new double[rows * cols];
// this.stepCache = new double[rows * cols];
// }
//
// public Matrix(int rows, int cols) {
// this.rows = rows;
// this.cols = cols;
// this.w = new double[rows * cols];
// this.dw = new double[rows * cols];
// this.stepCache = new double[rows * cols];
// }
//
// public Matrix(double[] vector) {
// this.rows = vector.length;
// this.cols = 1;
// this.w = vector;
// this.dw = new double[vector.length];
// this.stepCache = new double[vector.length];
// }
//
// private int index(int row, int col) {
// int ix = cols * row + col;
// return ix;
// }
//
// private double getW(int row, int col) {
// return w[index(row, col)];
// }
//
// private void setW(int row, int col, double val) {
// w[index(row, col)] = val;
// }
// }
// Path: src/loss/LossSumOfSquares.java
import matrix.Matrix;
package loss;
public class LossSumOfSquares implements Loss {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override | public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception { |
evolvingstuff/RecurrentJava | src/autodiff/Graph.java | // Path: src/matrix/Matrix.java
// public class Matrix implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public int rows;
// public int cols;
// public double[] w;
// public double[] dw;
// public double[] stepCache;
//
// @Override
// public String toString() {
// String result = "";
// for (int r = 0; r < rows; r++) {
// for (int c = 0; c < cols; c++) {
// result += String.format("%.4f",getW(r, c)) + "\t";
// }
// result += "\n";
// }
// return result;
// }
//
// public Matrix clone() {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < w.length; i++) {
// result.w[i] = w[i];
// result.dw[i] = dw[i];
// result.stepCache[i] = stepCache[i];
// }
// return result;
// }
//
// public void resetDw() {
// for (int i = 0; i < dw.length; i++) {
// dw[i] = 0;
// }
// }
//
// public void resetStepCache() {
// for (int i = 0; i < stepCache.length; i++) {
// stepCache[i] = 0;
// }
// }
//
// public static Matrix transpose(Matrix m) {
// Matrix result = new Matrix(m.cols, m.rows);
// for (int r = 0; r < m.rows; r++) {
// for (int c = 0; c < m.cols; c++) {
// result.setW(c, r, m.getW(r, c));
// }
// }
// return result;
// }
//
// public static Matrix rand(int rows, int cols, double initParamsStdDev, Random rng) {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < result.w.length; i++) {
// result.w[i] = rng.nextGaussian() * initParamsStdDev;
// }
// return result;
// }
//
// public static Matrix ident(int dim) {
// Matrix result = new Matrix(dim, dim);
// for (int i = 0; i < dim; i++) {
// result.setW(i, i, 1.0);
// }
// return result;
// }
//
// public static Matrix uniform(int rows, int cols, double s) {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < result.w.length; i++) {
// result.w[i] = s;
// }
// return result;
// }
//
// public static Matrix ones(int rows, int cols) {
// return uniform(rows, cols, 1.0);
// }
//
// public static Matrix negones(int rows, int cols) {
// return uniform(rows, cols, -1.0);
// }
//
// public Matrix(int dim) {
// this.rows = dim;
// this.cols = 1;
// this.w = new double[rows * cols];
// this.dw = new double[rows * cols];
// this.stepCache = new double[rows * cols];
// }
//
// public Matrix(int rows, int cols) {
// this.rows = rows;
// this.cols = cols;
// this.w = new double[rows * cols];
// this.dw = new double[rows * cols];
// this.stepCache = new double[rows * cols];
// }
//
// public Matrix(double[] vector) {
// this.rows = vector.length;
// this.cols = 1;
// this.w = vector;
// this.dw = new double[vector.length];
// this.stepCache = new double[vector.length];
// }
//
// private int index(int row, int col) {
// int ix = cols * row + col;
// return ix;
// }
//
// private double getW(int row, int col) {
// return w[index(row, col)];
// }
//
// private void setW(int row, int col, double val) {
// w[index(row, col)] = val;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import matrix.Matrix;
import model.Nonlinearity; | package autodiff;
public class Graph {
boolean applyBackprop;
List<Runnable> backprop = new ArrayList<>();
public Graph() {
this.applyBackprop = true;
}
public Graph(boolean applyBackprop) {
this.applyBackprop = applyBackprop;
}
public void backward() {
for (int i = backprop.size()-1; i >= 0; i--) {
backprop.get(i).run();
}
}
| // Path: src/matrix/Matrix.java
// public class Matrix implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public int rows;
// public int cols;
// public double[] w;
// public double[] dw;
// public double[] stepCache;
//
// @Override
// public String toString() {
// String result = "";
// for (int r = 0; r < rows; r++) {
// for (int c = 0; c < cols; c++) {
// result += String.format("%.4f",getW(r, c)) + "\t";
// }
// result += "\n";
// }
// return result;
// }
//
// public Matrix clone() {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < w.length; i++) {
// result.w[i] = w[i];
// result.dw[i] = dw[i];
// result.stepCache[i] = stepCache[i];
// }
// return result;
// }
//
// public void resetDw() {
// for (int i = 0; i < dw.length; i++) {
// dw[i] = 0;
// }
// }
//
// public void resetStepCache() {
// for (int i = 0; i < stepCache.length; i++) {
// stepCache[i] = 0;
// }
// }
//
// public static Matrix transpose(Matrix m) {
// Matrix result = new Matrix(m.cols, m.rows);
// for (int r = 0; r < m.rows; r++) {
// for (int c = 0; c < m.cols; c++) {
// result.setW(c, r, m.getW(r, c));
// }
// }
// return result;
// }
//
// public static Matrix rand(int rows, int cols, double initParamsStdDev, Random rng) {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < result.w.length; i++) {
// result.w[i] = rng.nextGaussian() * initParamsStdDev;
// }
// return result;
// }
//
// public static Matrix ident(int dim) {
// Matrix result = new Matrix(dim, dim);
// for (int i = 0; i < dim; i++) {
// result.setW(i, i, 1.0);
// }
// return result;
// }
//
// public static Matrix uniform(int rows, int cols, double s) {
// Matrix result = new Matrix(rows, cols);
// for (int i = 0; i < result.w.length; i++) {
// result.w[i] = s;
// }
// return result;
// }
//
// public static Matrix ones(int rows, int cols) {
// return uniform(rows, cols, 1.0);
// }
//
// public static Matrix negones(int rows, int cols) {
// return uniform(rows, cols, -1.0);
// }
//
// public Matrix(int dim) {
// this.rows = dim;
// this.cols = 1;
// this.w = new double[rows * cols];
// this.dw = new double[rows * cols];
// this.stepCache = new double[rows * cols];
// }
//
// public Matrix(int rows, int cols) {
// this.rows = rows;
// this.cols = cols;
// this.w = new double[rows * cols];
// this.dw = new double[rows * cols];
// this.stepCache = new double[rows * cols];
// }
//
// public Matrix(double[] vector) {
// this.rows = vector.length;
// this.cols = 1;
// this.w = vector;
// this.dw = new double[vector.length];
// this.stepCache = new double[vector.length];
// }
//
// private int index(int row, int col) {
// int ix = cols * row + col;
// return ix;
// }
//
// private double getW(int row, int col) {
// return w[index(row, col)];
// }
//
// private void setW(int row, int col, double val) {
// w[index(row, col)] = val;
// }
// }
// Path: src/autodiff/Graph.java
import java.util.ArrayList;
import java.util.List;
import matrix.Matrix;
import model.Nonlinearity;
package autodiff;
public class Graph {
boolean applyBackprop;
List<Runnable> backprop = new ArrayList<>();
public Graph() {
this.applyBackprop = true;
}
public Graph(boolean applyBackprop) {
this.applyBackprop = applyBackprop;
}
public void backward() {
for (int i = backprop.size()-1; i >= 0; i--) {
backprop.get(i).run();
}
}
| public Matrix concatVectors(final Matrix m1, final Matrix m2) throws Exception { |
gizwits/Gizwits-WaterHeater_Android | src/com/gizwits/framework/sdk/CmdCenter.java | // Path: src/com/gizwits/framework/config/Configs.java
// public class Configs {
//
// /** 设定是否为debug版本. */
// public static final boolean DEBUG = true;
//
// /** 设定AppID,参数为机智云官网中查看产品信息得到的AppID. */
// public static final String APPID = "your_app_id";
//
// /** 指定该app对应设备的product_key,如果设定了过滤,会过滤出该peoduct_key对应的设备. */
// public static final String PRODUCT_KEY = "your_product_key";
//
// /** 设定日志打印级别. */
// public static final XPGWifiLogLevel LOG_LEVEL = XPGWifiLogLevel.XPGWifiLogLevelAll;
//
// /** 日志保存文件名. */
// public static final String LOG_FILE_NAME = "BassApp.log";
//
// /** 产品密钥 */
// public static final String APP_SECRET = "your_app_secret";
// }
//
// Path: src/com/gizwits/framework/config/JsonKeys.java
// public class JsonKeys {
//
// /** 产品名. */
// public final static String PRODUCT_NAME = "机智云智能热水器";
//
// /** 实体字段名,代表对应的项目. */
// public final static String KEY_ACTION = "entity0";
//
// /** 开关. */
// public final static String ON_OFF = "Switch";
//
// /** 目标温度 30 - 75. */
// public final static String SET_TEMP = "Set_Temp";
//
// /** 当前温度 0 - 99. */
// public final static String ROOM_TEMP = "Room_Temp";
//
// /** 模式切换 0、智能模式 1、节能模式 2、速热模式 3、加热模式 4、保温模式 5、安全模式. */
// public final static String MODE = "Mode";
//
//
// /** 倒计时预约. */
// public final static String COUNT_DOWN_RESERVE = "CountDown_Reserve";
//
// /** 定时预约. */
// public final static String TIME_RESERVE = "Time_Reserve";
//
// /** 预约开关. */
// public final static String RESERVE_ON_OFF = "Reserve_OnOff";
//
// /** 时钟校准. */
// public final static String CALIBRATION_TIME = "Calibration_Time";
//
//
//
// /** 干烧故障. */
// public final static String FAULT_BURNING = "Fault_burning";
//
// /** 传感器开路故障. */
// public final static String FAULT_SENSOR_OPEN = "Fault_SensorOpen";
//
// /** 传感器短路故障. */
// public final static String FAULT_SENSOR_SHORT = "Fault_SensorShort";
//
// /** 超温故障. */
// public final static String FAULT_OVER_TEMP = "Fault_OverTemp";
// }
| import com.xtremeprog.xpgconnect.XPGWifiSDK.XPGWifiConfigureMode;
import com.xtremeprog.xpgconnect.XPGWifiSDK.XPGWifiGAgentType;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import com.gizwits.framework.config.Configs;
import com.gizwits.framework.config.JsonKeys;
import com.xpg.common.useful.StringUtils;
import com.xtremeprog.xpgconnect.XPGWifiDevice;
import com.xtremeprog.xpgconnect.XPGWifiSDK; | */
xpgWifiGCC.setDeviceWifi(wifi, password, XPGWifiConfigureMode.XPGWifiConfigureModeAirLink, null, 60, types);
}
/**
* softap,把需要连接的wifi的ssid和password发给模块。.
*
* @param wifi
* wifi名字
* @param password
* wifi密码
*/
public void cSetSoftAp(String wifi, String password, String ssidAP) {
/*
* xpgWifiGCC.setDeviceWifi(wifi, password,
* XPGWifiConfigureMode.XPGWifiConfigureModeSoftAP, 30);
*/
xpgWifiGCC.setDeviceWifi(wifi, password, XPGWifiConfigureMode.XPGWifiConfigureModeSoftAP, ssidAP, 60, null);
}
/**
* 绑定后刷新设备列表,该方法会同时获取本地设备以及远程设备列表.
*
* @param uid
* 用户名
* @param token
* 令牌
*/
public void cGetBoundDevices(String uid, String token) { | // Path: src/com/gizwits/framework/config/Configs.java
// public class Configs {
//
// /** 设定是否为debug版本. */
// public static final boolean DEBUG = true;
//
// /** 设定AppID,参数为机智云官网中查看产品信息得到的AppID. */
// public static final String APPID = "your_app_id";
//
// /** 指定该app对应设备的product_key,如果设定了过滤,会过滤出该peoduct_key对应的设备. */
// public static final String PRODUCT_KEY = "your_product_key";
//
// /** 设定日志打印级别. */
// public static final XPGWifiLogLevel LOG_LEVEL = XPGWifiLogLevel.XPGWifiLogLevelAll;
//
// /** 日志保存文件名. */
// public static final String LOG_FILE_NAME = "BassApp.log";
//
// /** 产品密钥 */
// public static final String APP_SECRET = "your_app_secret";
// }
//
// Path: src/com/gizwits/framework/config/JsonKeys.java
// public class JsonKeys {
//
// /** 产品名. */
// public final static String PRODUCT_NAME = "机智云智能热水器";
//
// /** 实体字段名,代表对应的项目. */
// public final static String KEY_ACTION = "entity0";
//
// /** 开关. */
// public final static String ON_OFF = "Switch";
//
// /** 目标温度 30 - 75. */
// public final static String SET_TEMP = "Set_Temp";
//
// /** 当前温度 0 - 99. */
// public final static String ROOM_TEMP = "Room_Temp";
//
// /** 模式切换 0、智能模式 1、节能模式 2、速热模式 3、加热模式 4、保温模式 5、安全模式. */
// public final static String MODE = "Mode";
//
//
// /** 倒计时预约. */
// public final static String COUNT_DOWN_RESERVE = "CountDown_Reserve";
//
// /** 定时预约. */
// public final static String TIME_RESERVE = "Time_Reserve";
//
// /** 预约开关. */
// public final static String RESERVE_ON_OFF = "Reserve_OnOff";
//
// /** 时钟校准. */
// public final static String CALIBRATION_TIME = "Calibration_Time";
//
//
//
// /** 干烧故障. */
// public final static String FAULT_BURNING = "Fault_burning";
//
// /** 传感器开路故障. */
// public final static String FAULT_SENSOR_OPEN = "Fault_SensorOpen";
//
// /** 传感器短路故障. */
// public final static String FAULT_SENSOR_SHORT = "Fault_SensorShort";
//
// /** 超温故障. */
// public final static String FAULT_OVER_TEMP = "Fault_OverTemp";
// }
// Path: src/com/gizwits/framework/sdk/CmdCenter.java
import com.xtremeprog.xpgconnect.XPGWifiSDK.XPGWifiConfigureMode;
import com.xtremeprog.xpgconnect.XPGWifiSDK.XPGWifiGAgentType;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import com.gizwits.framework.config.Configs;
import com.gizwits.framework.config.JsonKeys;
import com.xpg.common.useful.StringUtils;
import com.xtremeprog.xpgconnect.XPGWifiDevice;
import com.xtremeprog.xpgconnect.XPGWifiSDK;
*/
xpgWifiGCC.setDeviceWifi(wifi, password, XPGWifiConfigureMode.XPGWifiConfigureModeAirLink, null, 60, types);
}
/**
* softap,把需要连接的wifi的ssid和password发给模块。.
*
* @param wifi
* wifi名字
* @param password
* wifi密码
*/
public void cSetSoftAp(String wifi, String password, String ssidAP) {
/*
* xpgWifiGCC.setDeviceWifi(wifi, password,
* XPGWifiConfigureMode.XPGWifiConfigureModeSoftAP, 30);
*/
xpgWifiGCC.setDeviceWifi(wifi, password, XPGWifiConfigureMode.XPGWifiConfigureModeSoftAP, ssidAP, 60, null);
}
/**
* 绑定后刷新设备列表,该方法会同时获取本地设备以及远程设备列表.
*
* @param uid
* 用户名
* @param token
* 令牌
*/
public void cGetBoundDevices(String uid, String token) { | xpgWifiGCC.getBoundDevices(uid, token, Configs.PRODUCT_KEY); |
gizwits/Gizwits-WaterHeater_Android | src/com/gizwits/framework/sdk/CmdCenter.java | // Path: src/com/gizwits/framework/config/Configs.java
// public class Configs {
//
// /** 设定是否为debug版本. */
// public static final boolean DEBUG = true;
//
// /** 设定AppID,参数为机智云官网中查看产品信息得到的AppID. */
// public static final String APPID = "your_app_id";
//
// /** 指定该app对应设备的product_key,如果设定了过滤,会过滤出该peoduct_key对应的设备. */
// public static final String PRODUCT_KEY = "your_product_key";
//
// /** 设定日志打印级别. */
// public static final XPGWifiLogLevel LOG_LEVEL = XPGWifiLogLevel.XPGWifiLogLevelAll;
//
// /** 日志保存文件名. */
// public static final String LOG_FILE_NAME = "BassApp.log";
//
// /** 产品密钥 */
// public static final String APP_SECRET = "your_app_secret";
// }
//
// Path: src/com/gizwits/framework/config/JsonKeys.java
// public class JsonKeys {
//
// /** 产品名. */
// public final static String PRODUCT_NAME = "机智云智能热水器";
//
// /** 实体字段名,代表对应的项目. */
// public final static String KEY_ACTION = "entity0";
//
// /** 开关. */
// public final static String ON_OFF = "Switch";
//
// /** 目标温度 30 - 75. */
// public final static String SET_TEMP = "Set_Temp";
//
// /** 当前温度 0 - 99. */
// public final static String ROOM_TEMP = "Room_Temp";
//
// /** 模式切换 0、智能模式 1、节能模式 2、速热模式 3、加热模式 4、保温模式 5、安全模式. */
// public final static String MODE = "Mode";
//
//
// /** 倒计时预约. */
// public final static String COUNT_DOWN_RESERVE = "CountDown_Reserve";
//
// /** 定时预约. */
// public final static String TIME_RESERVE = "Time_Reserve";
//
// /** 预约开关. */
// public final static String RESERVE_ON_OFF = "Reserve_OnOff";
//
// /** 时钟校准. */
// public final static String CALIBRATION_TIME = "Calibration_Time";
//
//
//
// /** 干烧故障. */
// public final static String FAULT_BURNING = "Fault_burning";
//
// /** 传感器开路故障. */
// public final static String FAULT_SENSOR_OPEN = "Fault_SensorOpen";
//
// /** 传感器短路故障. */
// public final static String FAULT_SENSOR_SHORT = "Fault_SensorShort";
//
// /** 超温故障. */
// public final static String FAULT_OVER_TEMP = "Fault_OverTemp";
// }
| import com.xtremeprog.xpgconnect.XPGWifiSDK.XPGWifiConfigureMode;
import com.xtremeprog.xpgconnect.XPGWifiSDK.XPGWifiGAgentType;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import com.gizwits.framework.config.Configs;
import com.gizwits.framework.config.JsonKeys;
import com.xpg.common.useful.StringUtils;
import com.xtremeprog.xpgconnect.XPGWifiDevice;
import com.xtremeprog.xpgconnect.XPGWifiSDK; | * passcode
* @param remark
* 备注
*/
public void cBindDevice(String uid, String token, String did,
String passcode, String remark) {
xpgWifiGCC.bindDevice(uid, token, did, passcode, remark);
}
// =================================================================
//
// 关于控制设备的指令
//
// =================================================================
/**
* 发送指令.
*
* @param xpgWifiDevice the xpg wifi device
* @param key the key
* @param value the value
*/
public void cWrite(XPGWifiDevice xpgWifiDevice, String key, Object value) {
try {
final JSONObject jsonsend = new JSONObject();
JSONObject jsonparam = new JSONObject();
jsonsend.put("cmd", 1);
jsonparam.put(key, value); | // Path: src/com/gizwits/framework/config/Configs.java
// public class Configs {
//
// /** 设定是否为debug版本. */
// public static final boolean DEBUG = true;
//
// /** 设定AppID,参数为机智云官网中查看产品信息得到的AppID. */
// public static final String APPID = "your_app_id";
//
// /** 指定该app对应设备的product_key,如果设定了过滤,会过滤出该peoduct_key对应的设备. */
// public static final String PRODUCT_KEY = "your_product_key";
//
// /** 设定日志打印级别. */
// public static final XPGWifiLogLevel LOG_LEVEL = XPGWifiLogLevel.XPGWifiLogLevelAll;
//
// /** 日志保存文件名. */
// public static final String LOG_FILE_NAME = "BassApp.log";
//
// /** 产品密钥 */
// public static final String APP_SECRET = "your_app_secret";
// }
//
// Path: src/com/gizwits/framework/config/JsonKeys.java
// public class JsonKeys {
//
// /** 产品名. */
// public final static String PRODUCT_NAME = "机智云智能热水器";
//
// /** 实体字段名,代表对应的项目. */
// public final static String KEY_ACTION = "entity0";
//
// /** 开关. */
// public final static String ON_OFF = "Switch";
//
// /** 目标温度 30 - 75. */
// public final static String SET_TEMP = "Set_Temp";
//
// /** 当前温度 0 - 99. */
// public final static String ROOM_TEMP = "Room_Temp";
//
// /** 模式切换 0、智能模式 1、节能模式 2、速热模式 3、加热模式 4、保温模式 5、安全模式. */
// public final static String MODE = "Mode";
//
//
// /** 倒计时预约. */
// public final static String COUNT_DOWN_RESERVE = "CountDown_Reserve";
//
// /** 定时预约. */
// public final static String TIME_RESERVE = "Time_Reserve";
//
// /** 预约开关. */
// public final static String RESERVE_ON_OFF = "Reserve_OnOff";
//
// /** 时钟校准. */
// public final static String CALIBRATION_TIME = "Calibration_Time";
//
//
//
// /** 干烧故障. */
// public final static String FAULT_BURNING = "Fault_burning";
//
// /** 传感器开路故障. */
// public final static String FAULT_SENSOR_OPEN = "Fault_SensorOpen";
//
// /** 传感器短路故障. */
// public final static String FAULT_SENSOR_SHORT = "Fault_SensorShort";
//
// /** 超温故障. */
// public final static String FAULT_OVER_TEMP = "Fault_OverTemp";
// }
// Path: src/com/gizwits/framework/sdk/CmdCenter.java
import com.xtremeprog.xpgconnect.XPGWifiSDK.XPGWifiConfigureMode;
import com.xtremeprog.xpgconnect.XPGWifiSDK.XPGWifiGAgentType;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import com.gizwits.framework.config.Configs;
import com.gizwits.framework.config.JsonKeys;
import com.xpg.common.useful.StringUtils;
import com.xtremeprog.xpgconnect.XPGWifiDevice;
import com.xtremeprog.xpgconnect.XPGWifiSDK;
* passcode
* @param remark
* 备注
*/
public void cBindDevice(String uid, String token, String did,
String passcode, String remark) {
xpgWifiGCC.bindDevice(uid, token, did, passcode, remark);
}
// =================================================================
//
// 关于控制设备的指令
//
// =================================================================
/**
* 发送指令.
*
* @param xpgWifiDevice the xpg wifi device
* @param key the key
* @param value the value
*/
public void cWrite(XPGWifiDevice xpgWifiDevice, String key, Object value) {
try {
final JSONObject jsonsend = new JSONObject();
JSONObject jsonparam = new JSONObject();
jsonsend.put("cmd", 1);
jsonparam.put(key, value); | jsonsend.put(JsonKeys.KEY_ACTION, jsonparam); |
nantaphop/AomYim-Pantip | app/src/main/java/com/nantaphop/pantipfanapp/model/ReadLog.java | // Path: app/src/main/java/com/nantaphop/pantipfanapp/response/Topic.java
// public class Topic implements Serializable {
//
// @SerializedName("cover_img")
// String coverImg;
//
// Boolean brightCover;
//
//
// @SerializedName("_id")
// int id;
//
// @SerializedName("topic_id")
// int id2;
//
// @SerializedName("disp_topic")
// String title;
//
//
// @SerializedName("disp_msg")
// String desc;
//
// int comments;
// int votes;
//
//
// @SerializedName("utime")
// Date date;
//
// @SerializedName("stime")
// long stime;
//
// @SerializedName("topic_type")
// int topicType;
//
// @SerializedName("abbr_title")
// String dateString;
//
// String author;
// String name;
//
// boolean read;
//
// public boolean isRead() {
// return read;
// }
//
// public void setRead(boolean read) {
// this.read = read;
// }
//
// ArrayList<Tag> tags;
//
// public String getCoverImg() {
// return coverImg;
// }
//
// public void setCoverImg(String coverImg) {
// this.coverImg = coverImg;
// }
//
// public int getId() {
// // id2 is topic when operate with user topic like bookmark etc.
// return id2 > 0 ? id2 : id;
// }
//
// public Boolean isBrightCover() {
// return brightCover;
// }
//
// public void setBrightCover(Boolean brightCover) {
// this.brightCover = brightCover;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public int getComments() {
// return comments;
// }
//
// public void setComments(int comments) {
// this.comments = comments;
// }
//
// public int getVotes() {
// return votes;
// }
//
// public void setVotes(int votes) {
// this.votes = votes;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
// public int getTopicType() {
// return topicType;
// }
//
// public void setTopicType(int topicType) {
// this.topicType = topicType;
// }
//
// public String getDateString() {
// return dateString;
// }
//
// public void setDateString(String dateString) {
// this.dateString = dateString;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public ArrayList<Tag> getTags() {
// return tags;
// }
//
// public void setTags(ArrayList<Tag> tags) {
// this.tags = tags;
// }
//
// @Override
// public String toString() {
// return title + " - " + author;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
| import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;
import com.nantaphop.pantipfanapp.response.Topic;
import java.io.Serializable;
import java.util.Date; | package com.nantaphop.pantipfanapp.model;
/**
* Created by nantaphop on 20-Jan-15.
*/
@Table(name = "ReadLogs")
public class ReadLog extends Model implements Serializable {
@Column
public String coverImg;
@Column(name = "topicid")
public int topic_id;
@Column
public String title;
@Column
public long date;
@Column
public String sdate;
@Column
public int topicType;
@Column
public String author;
@Column
public long readTime;
public ReadLog() {
}
public ReadLog(int topic_id, String title, long readTime) {
this.topic_id = topic_id;
this.title = title;
this.readTime = readTime;
}
| // Path: app/src/main/java/com/nantaphop/pantipfanapp/response/Topic.java
// public class Topic implements Serializable {
//
// @SerializedName("cover_img")
// String coverImg;
//
// Boolean brightCover;
//
//
// @SerializedName("_id")
// int id;
//
// @SerializedName("topic_id")
// int id2;
//
// @SerializedName("disp_topic")
// String title;
//
//
// @SerializedName("disp_msg")
// String desc;
//
// int comments;
// int votes;
//
//
// @SerializedName("utime")
// Date date;
//
// @SerializedName("stime")
// long stime;
//
// @SerializedName("topic_type")
// int topicType;
//
// @SerializedName("abbr_title")
// String dateString;
//
// String author;
// String name;
//
// boolean read;
//
// public boolean isRead() {
// return read;
// }
//
// public void setRead(boolean read) {
// this.read = read;
// }
//
// ArrayList<Tag> tags;
//
// public String getCoverImg() {
// return coverImg;
// }
//
// public void setCoverImg(String coverImg) {
// this.coverImg = coverImg;
// }
//
// public int getId() {
// // id2 is topic when operate with user topic like bookmark etc.
// return id2 > 0 ? id2 : id;
// }
//
// public Boolean isBrightCover() {
// return brightCover;
// }
//
// public void setBrightCover(Boolean brightCover) {
// this.brightCover = brightCover;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public int getComments() {
// return comments;
// }
//
// public void setComments(int comments) {
// this.comments = comments;
// }
//
// public int getVotes() {
// return votes;
// }
//
// public void setVotes(int votes) {
// this.votes = votes;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
// public int getTopicType() {
// return topicType;
// }
//
// public void setTopicType(int topicType) {
// this.topicType = topicType;
// }
//
// public String getDateString() {
// return dateString;
// }
//
// public void setDateString(String dateString) {
// this.dateString = dateString;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public ArrayList<Tag> getTags() {
// return tags;
// }
//
// public void setTags(ArrayList<Tag> tags) {
// this.tags = tags;
// }
//
// @Override
// public String toString() {
// return title + " - " + author;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
// Path: app/src/main/java/com/nantaphop/pantipfanapp/model/ReadLog.java
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;
import com.nantaphop.pantipfanapp.response.Topic;
import java.io.Serializable;
import java.util.Date;
package com.nantaphop.pantipfanapp.model;
/**
* Created by nantaphop on 20-Jan-15.
*/
@Table(name = "ReadLogs")
public class ReadLog extends Model implements Serializable {
@Column
public String coverImg;
@Column(name = "topicid")
public int topic_id;
@Column
public String title;
@Column
public long date;
@Column
public String sdate;
@Column
public int topicType;
@Column
public String author;
@Column
public long readTime;
public ReadLog() {
}
public ReadLog(int topic_id, String title, long readTime) {
this.topic_id = topic_id;
this.title = title;
this.readTime = readTime;
}
| public ReadLog(Topic t, long readTime){ |
nantaphop/AomYim-Pantip | app/src/main/java/com/nantaphop/pantipfanapp/view/NoCommentView.java | // Path: app/src/main/java/com/nantaphop/pantipfanapp/response/Topic.java
// public class Topic implements Serializable {
//
// @SerializedName("cover_img")
// String coverImg;
//
// Boolean brightCover;
//
//
// @SerializedName("_id")
// int id;
//
// @SerializedName("topic_id")
// int id2;
//
// @SerializedName("disp_topic")
// String title;
//
//
// @SerializedName("disp_msg")
// String desc;
//
// int comments;
// int votes;
//
//
// @SerializedName("utime")
// Date date;
//
// @SerializedName("stime")
// long stime;
//
// @SerializedName("topic_type")
// int topicType;
//
// @SerializedName("abbr_title")
// String dateString;
//
// String author;
// String name;
//
// boolean read;
//
// public boolean isRead() {
// return read;
// }
//
// public void setRead(boolean read) {
// this.read = read;
// }
//
// ArrayList<Tag> tags;
//
// public String getCoverImg() {
// return coverImg;
// }
//
// public void setCoverImg(String coverImg) {
// this.coverImg = coverImg;
// }
//
// public int getId() {
// // id2 is topic when operate with user topic like bookmark etc.
// return id2 > 0 ? id2 : id;
// }
//
// public Boolean isBrightCover() {
// return brightCover;
// }
//
// public void setBrightCover(Boolean brightCover) {
// this.brightCover = brightCover;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public int getComments() {
// return comments;
// }
//
// public void setComments(int comments) {
// this.comments = comments;
// }
//
// public int getVotes() {
// return votes;
// }
//
// public void setVotes(int votes) {
// this.votes = votes;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
// public int getTopicType() {
// return topicType;
// }
//
// public void setTopicType(int topicType) {
// this.topicType = topicType;
// }
//
// public String getDateString() {
// return dateString;
// }
//
// public void setDateString(String dateString) {
// this.dateString = dateString;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public ArrayList<Tag> getTags() {
// return tags;
// }
//
// public void setTags(ArrayList<Tag> tags) {
// this.tags = tags;
// }
//
// @Override
// public String toString() {
// return title + " - " + author;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
| import android.content.Context;
import android.widget.LinearLayout;
import com.nantaphop.pantipfanapp.R;
import com.nantaphop.pantipfanapp.response.Topic;
import org.androidannotations.annotations.EViewGroup; | package com.nantaphop.pantipfanapp.view;
/**
* Created by nantaphop on 09-Sep-14.
*/
@EViewGroup(R.layout.view_no_comment)
public class NoCommentView extends LinearLayout { | // Path: app/src/main/java/com/nantaphop/pantipfanapp/response/Topic.java
// public class Topic implements Serializable {
//
// @SerializedName("cover_img")
// String coverImg;
//
// Boolean brightCover;
//
//
// @SerializedName("_id")
// int id;
//
// @SerializedName("topic_id")
// int id2;
//
// @SerializedName("disp_topic")
// String title;
//
//
// @SerializedName("disp_msg")
// String desc;
//
// int comments;
// int votes;
//
//
// @SerializedName("utime")
// Date date;
//
// @SerializedName("stime")
// long stime;
//
// @SerializedName("topic_type")
// int topicType;
//
// @SerializedName("abbr_title")
// String dateString;
//
// String author;
// String name;
//
// boolean read;
//
// public boolean isRead() {
// return read;
// }
//
// public void setRead(boolean read) {
// this.read = read;
// }
//
// ArrayList<Tag> tags;
//
// public String getCoverImg() {
// return coverImg;
// }
//
// public void setCoverImg(String coverImg) {
// this.coverImg = coverImg;
// }
//
// public int getId() {
// // id2 is topic when operate with user topic like bookmark etc.
// return id2 > 0 ? id2 : id;
// }
//
// public Boolean isBrightCover() {
// return brightCover;
// }
//
// public void setBrightCover(Boolean brightCover) {
// this.brightCover = brightCover;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public int getComments() {
// return comments;
// }
//
// public void setComments(int comments) {
// this.comments = comments;
// }
//
// public int getVotes() {
// return votes;
// }
//
// public void setVotes(int votes) {
// this.votes = votes;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
// public int getTopicType() {
// return topicType;
// }
//
// public void setTopicType(int topicType) {
// this.topicType = topicType;
// }
//
// public String getDateString() {
// return dateString;
// }
//
// public void setDateString(String dateString) {
// this.dateString = dateString;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public ArrayList<Tag> getTags() {
// return tags;
// }
//
// public void setTags(ArrayList<Tag> tags) {
// this.tags = tags;
// }
//
// @Override
// public String toString() {
// return title + " - " + author;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
// Path: app/src/main/java/com/nantaphop/pantipfanapp/view/NoCommentView.java
import android.content.Context;
import android.widget.LinearLayout;
import com.nantaphop.pantipfanapp.R;
import com.nantaphop.pantipfanapp.response.Topic;
import org.androidannotations.annotations.EViewGroup;
package com.nantaphop.pantipfanapp.view;
/**
* Created by nantaphop on 09-Sep-14.
*/
@EViewGroup(R.layout.view_no_comment)
public class NoCommentView extends LinearLayout { | private Topic topic; |
nantaphop/AomYim-Pantip | app/src/main/java/com/nantaphop/pantipfanapp/view/AddCommentView.java | // Path: app/src/main/java/com/nantaphop/pantipfanapp/response/Topic.java
// public class Topic implements Serializable {
//
// @SerializedName("cover_img")
// String coverImg;
//
// Boolean brightCover;
//
//
// @SerializedName("_id")
// int id;
//
// @SerializedName("topic_id")
// int id2;
//
// @SerializedName("disp_topic")
// String title;
//
//
// @SerializedName("disp_msg")
// String desc;
//
// int comments;
// int votes;
//
//
// @SerializedName("utime")
// Date date;
//
// @SerializedName("stime")
// long stime;
//
// @SerializedName("topic_type")
// int topicType;
//
// @SerializedName("abbr_title")
// String dateString;
//
// String author;
// String name;
//
// boolean read;
//
// public boolean isRead() {
// return read;
// }
//
// public void setRead(boolean read) {
// this.read = read;
// }
//
// ArrayList<Tag> tags;
//
// public String getCoverImg() {
// return coverImg;
// }
//
// public void setCoverImg(String coverImg) {
// this.coverImg = coverImg;
// }
//
// public int getId() {
// // id2 is topic when operate with user topic like bookmark etc.
// return id2 > 0 ? id2 : id;
// }
//
// public Boolean isBrightCover() {
// return brightCover;
// }
//
// public void setBrightCover(Boolean brightCover) {
// this.brightCover = brightCover;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public int getComments() {
// return comments;
// }
//
// public void setComments(int comments) {
// this.comments = comments;
// }
//
// public int getVotes() {
// return votes;
// }
//
// public void setVotes(int votes) {
// this.votes = votes;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
// public int getTopicType() {
// return topicType;
// }
//
// public void setTopicType(int topicType) {
// this.topicType = topicType;
// }
//
// public String getDateString() {
// return dateString;
// }
//
// public void setDateString(String dateString) {
// this.dateString = dateString;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public ArrayList<Tag> getTags() {
// return tags;
// }
//
// public void setTags(ArrayList<Tag> tags) {
// this.tags = tags;
// }
//
// @Override
// public String toString() {
// return title + " - " + author;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
| import android.content.Context;
import android.widget.LinearLayout;
import com.nantaphop.pantipfanapp.R;
import com.nantaphop.pantipfanapp.response.Topic;
import org.androidannotations.annotations.EViewGroup; | package com.nantaphop.pantipfanapp.view;
/**
* Created by nantaphop on 09-Sep-14.
*/
@EViewGroup(R.layout.view_add_comment)
public class AddCommentView extends LinearLayout { | // Path: app/src/main/java/com/nantaphop/pantipfanapp/response/Topic.java
// public class Topic implements Serializable {
//
// @SerializedName("cover_img")
// String coverImg;
//
// Boolean brightCover;
//
//
// @SerializedName("_id")
// int id;
//
// @SerializedName("topic_id")
// int id2;
//
// @SerializedName("disp_topic")
// String title;
//
//
// @SerializedName("disp_msg")
// String desc;
//
// int comments;
// int votes;
//
//
// @SerializedName("utime")
// Date date;
//
// @SerializedName("stime")
// long stime;
//
// @SerializedName("topic_type")
// int topicType;
//
// @SerializedName("abbr_title")
// String dateString;
//
// String author;
// String name;
//
// boolean read;
//
// public boolean isRead() {
// return read;
// }
//
// public void setRead(boolean read) {
// this.read = read;
// }
//
// ArrayList<Tag> tags;
//
// public String getCoverImg() {
// return coverImg;
// }
//
// public void setCoverImg(String coverImg) {
// this.coverImg = coverImg;
// }
//
// public int getId() {
// // id2 is topic when operate with user topic like bookmark etc.
// return id2 > 0 ? id2 : id;
// }
//
// public Boolean isBrightCover() {
// return brightCover;
// }
//
// public void setBrightCover(Boolean brightCover) {
// this.brightCover = brightCover;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public int getComments() {
// return comments;
// }
//
// public void setComments(int comments) {
// this.comments = comments;
// }
//
// public int getVotes() {
// return votes;
// }
//
// public void setVotes(int votes) {
// this.votes = votes;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(Date date) {
// this.date = date;
// }
//
// public int getTopicType() {
// return topicType;
// }
//
// public void setTopicType(int topicType) {
// this.topicType = topicType;
// }
//
// public String getDateString() {
// return dateString;
// }
//
// public void setDateString(String dateString) {
// this.dateString = dateString;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public ArrayList<Tag> getTags() {
// return tags;
// }
//
// public void setTags(ArrayList<Tag> tags) {
// this.tags = tags;
// }
//
// @Override
// public String toString() {
// return title + " - " + author;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
// Path: app/src/main/java/com/nantaphop/pantipfanapp/view/AddCommentView.java
import android.content.Context;
import android.widget.LinearLayout;
import com.nantaphop.pantipfanapp.R;
import com.nantaphop.pantipfanapp.response.Topic;
import org.androidannotations.annotations.EViewGroup;
package com.nantaphop.pantipfanapp.view;
/**
* Created by nantaphop on 09-Sep-14.
*/
@EViewGroup(R.layout.view_add_comment)
public class AddCommentView extends LinearLayout { | private Topic topic; |
seasarorg/sa-struts | src/main/java/org/seasar/struts/util/S2ModuleConfigUtil.java | // Path: src/main/java/org/seasar/struts/config/S2ModuleConfig.java
// public class S2ModuleConfig extends ModuleConfigImpl implements Disposable {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * 初期化されたかどうかです。
// */
// protected volatile boolean initialized;
//
// /**
// * インスタンスを構築します。
// *
// * @param prefix
// * プレフィックス
// */
// public S2ModuleConfig(String prefix) {
// super(prefix);
// initialize();
// }
//
// /**
// * 初期化を行ないます。
// */
// public void initialize() {
// DisposableUtil.add(this);
// initialized = true;
// }
//
// public void dispose() {
// actionConfigs.clear();
// actionConfigList.clear();
// formBeans.clear();
// BeanUtilsBean.setInstance(new BeanUtilsBean());
// initialized = false;
// }
//
// @Override
// public ActionConfig findActionConfig(String path) {
// if (!initialized) {
// initialize();
// }
// ActionConfig ac = (ActionConfig) actionConfigs.get(path);
// if (ac == null && HotdeployUtil.isHotdeploy()) {
// SingletonS2ContainerFactory.getContainer().getComponent(
// ActionUtil.fromPathToActionName(path));
// }
// return (ActionConfig) actionConfigs.get(path);
// }
//
// @Override
// public void freeze() {
// }
// }
| import org.apache.struts.Globals;
import org.seasar.struts.config.S2ModuleConfig;
| /*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.util;
/**
* モジュール設定に関するユーティリティです。
*
* @author higa
*
*/
public final class S2ModuleConfigUtil {
private S2ModuleConfigUtil() {
}
/**
* モジュール設定を返します。
*
* @return モジュール設定
*/
| // Path: src/main/java/org/seasar/struts/config/S2ModuleConfig.java
// public class S2ModuleConfig extends ModuleConfigImpl implements Disposable {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * 初期化されたかどうかです。
// */
// protected volatile boolean initialized;
//
// /**
// * インスタンスを構築します。
// *
// * @param prefix
// * プレフィックス
// */
// public S2ModuleConfig(String prefix) {
// super(prefix);
// initialize();
// }
//
// /**
// * 初期化を行ないます。
// */
// public void initialize() {
// DisposableUtil.add(this);
// initialized = true;
// }
//
// public void dispose() {
// actionConfigs.clear();
// actionConfigList.clear();
// formBeans.clear();
// BeanUtilsBean.setInstance(new BeanUtilsBean());
// initialized = false;
// }
//
// @Override
// public ActionConfig findActionConfig(String path) {
// if (!initialized) {
// initialize();
// }
// ActionConfig ac = (ActionConfig) actionConfigs.get(path);
// if (ac == null && HotdeployUtil.isHotdeploy()) {
// SingletonS2ContainerFactory.getContainer().getComponent(
// ActionUtil.fromPathToActionName(path));
// }
// return (ActionConfig) actionConfigs.get(path);
// }
//
// @Override
// public void freeze() {
// }
// }
// Path: src/main/java/org/seasar/struts/util/S2ModuleConfigUtil.java
import org.apache.struts.Globals;
import org.seasar.struts.config.S2ModuleConfig;
/*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.util;
/**
* モジュール設定に関するユーティリティです。
*
* @author higa
*
*/
public final class S2ModuleConfigUtil {
private S2ModuleConfigUtil() {
}
/**
* モジュール設定を返します。
*
* @return モジュール設定
*/
| public static S2ModuleConfig getModuleConfig() {
|
seasarorg/sa-struts | src/test/java/org/seasar/struts/util/S2ModuleConfigUtilTest.java | // Path: src/main/java/org/seasar/struts/config/S2ModuleConfig.java
// public class S2ModuleConfig extends ModuleConfigImpl implements Disposable {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * 初期化されたかどうかです。
// */
// protected volatile boolean initialized;
//
// /**
// * インスタンスを構築します。
// *
// * @param prefix
// * プレフィックス
// */
// public S2ModuleConfig(String prefix) {
// super(prefix);
// initialize();
// }
//
// /**
// * 初期化を行ないます。
// */
// public void initialize() {
// DisposableUtil.add(this);
// initialized = true;
// }
//
// public void dispose() {
// actionConfigs.clear();
// actionConfigList.clear();
// formBeans.clear();
// BeanUtilsBean.setInstance(new BeanUtilsBean());
// initialized = false;
// }
//
// @Override
// public ActionConfig findActionConfig(String path) {
// if (!initialized) {
// initialize();
// }
// ActionConfig ac = (ActionConfig) actionConfigs.get(path);
// if (ac == null && HotdeployUtil.isHotdeploy()) {
// SingletonS2ContainerFactory.getContainer().getComponent(
// ActionUtil.fromPathToActionName(path));
// }
// return (ActionConfig) actionConfigs.get(path);
// }
//
// @Override
// public void freeze() {
// }
// }
| import org.apache.struts.Globals;
import org.seasar.extension.unit.S2TestCase;
import org.seasar.struts.config.S2ModuleConfig;
| /*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.util;
/**
* @author higa
*
*/
public class S2ModuleConfigUtilTest extends S2TestCase {
/**
* @throws Exception
*/
public void testGetModuleConfig() throws Exception {
getServletContext().setAttribute(Globals.MODULE_KEY,
| // Path: src/main/java/org/seasar/struts/config/S2ModuleConfig.java
// public class S2ModuleConfig extends ModuleConfigImpl implements Disposable {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * 初期化されたかどうかです。
// */
// protected volatile boolean initialized;
//
// /**
// * インスタンスを構築します。
// *
// * @param prefix
// * プレフィックス
// */
// public S2ModuleConfig(String prefix) {
// super(prefix);
// initialize();
// }
//
// /**
// * 初期化を行ないます。
// */
// public void initialize() {
// DisposableUtil.add(this);
// initialized = true;
// }
//
// public void dispose() {
// actionConfigs.clear();
// actionConfigList.clear();
// formBeans.clear();
// BeanUtilsBean.setInstance(new BeanUtilsBean());
// initialized = false;
// }
//
// @Override
// public ActionConfig findActionConfig(String path) {
// if (!initialized) {
// initialize();
// }
// ActionConfig ac = (ActionConfig) actionConfigs.get(path);
// if (ac == null && HotdeployUtil.isHotdeploy()) {
// SingletonS2ContainerFactory.getContainer().getComponent(
// ActionUtil.fromPathToActionName(path));
// }
// return (ActionConfig) actionConfigs.get(path);
// }
//
// @Override
// public void freeze() {
// }
// }
// Path: src/test/java/org/seasar/struts/util/S2ModuleConfigUtilTest.java
import org.apache.struts.Globals;
import org.seasar.extension.unit.S2TestCase;
import org.seasar.struts.config.S2ModuleConfig;
/*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.util;
/**
* @author higa
*
*/
public class S2ModuleConfigUtilTest extends S2TestCase {
/**
* @throws Exception
*/
public void testGetModuleConfig() throws Exception {
getServletContext().setAttribute(Globals.MODULE_KEY,
| new S2ModuleConfig(""));
|
seasarorg/sa-struts | src/test/java/org/seasar/struts/config/S2FormBeanConfigTest.java | // Path: src/main/java/org/seasar/struts/action/ActionFormWrapperClass.java
// public class ActionFormWrapperClass implements DynaClass {
//
// /**
// * アクションマッピングです。
// */
// protected S2ActionMapping actionMapping;
//
// /**
// * 動的プロパティ用のマップです。
// */
// protected Map<String, DynaProperty> propertyMap = new HashMap<String, DynaProperty>();
//
// /**
// * インスタンスを構築します。
// *
// * @param actionMapping
// * アクションマッピング
// */
// public ActionFormWrapperClass(S2ActionMapping actionMapping) {
// this.actionMapping = actionMapping;
// }
//
// public DynaProperty[] getDynaProperties() {
// return propertyMap.values().toArray(
// new DynaProperty[propertyMap.size()]);
// }
//
// public DynaProperty getDynaProperty(String name) {
// if (name == null) {
// throw new NullPointerException("name");
// }
// return propertyMap.get(name);
// }
//
// /**
// * 動的プロパティを追加します。
// *
// * @param property
// * 動的プロパティ
// */
// public void addDynaProperty(DynaProperty property) {
// propertyMap.put(property.getName(), property);
// }
//
// public String getName() {
// return actionMapping.getName();
// }
//
// public DynaBean newInstance() throws IllegalAccessException,
// InstantiationException {
// return new ActionFormWrapper(this);
// }
//
// /**
// * アクションマッピングを返します。
// *
// * @return アクションマッピング
// */
// public S2ActionMapping getActionMapping() {
// return actionMapping;
// }
// }
| import org.seasar.extension.unit.S2TestCase;
import org.seasar.struts.action.ActionFormWrapperClass;
| /*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.config;
/**
* @author higa
*
*/
public class S2FormBeanConfigTest extends S2TestCase {
/**
* @throws Exception
*/
public void testCreateActionForm() throws Exception {
register(MyAction.class, "myAction");
S2ActionMapping actionMapping = new S2ActionMapping();
actionMapping.setComponentDef(getComponentDef("myAction"));
| // Path: src/main/java/org/seasar/struts/action/ActionFormWrapperClass.java
// public class ActionFormWrapperClass implements DynaClass {
//
// /**
// * アクションマッピングです。
// */
// protected S2ActionMapping actionMapping;
//
// /**
// * 動的プロパティ用のマップです。
// */
// protected Map<String, DynaProperty> propertyMap = new HashMap<String, DynaProperty>();
//
// /**
// * インスタンスを構築します。
// *
// * @param actionMapping
// * アクションマッピング
// */
// public ActionFormWrapperClass(S2ActionMapping actionMapping) {
// this.actionMapping = actionMapping;
// }
//
// public DynaProperty[] getDynaProperties() {
// return propertyMap.values().toArray(
// new DynaProperty[propertyMap.size()]);
// }
//
// public DynaProperty getDynaProperty(String name) {
// if (name == null) {
// throw new NullPointerException("name");
// }
// return propertyMap.get(name);
// }
//
// /**
// * 動的プロパティを追加します。
// *
// * @param property
// * 動的プロパティ
// */
// public void addDynaProperty(DynaProperty property) {
// propertyMap.put(property.getName(), property);
// }
//
// public String getName() {
// return actionMapping.getName();
// }
//
// public DynaBean newInstance() throws IllegalAccessException,
// InstantiationException {
// return new ActionFormWrapper(this);
// }
//
// /**
// * アクションマッピングを返します。
// *
// * @return アクションマッピング
// */
// public S2ActionMapping getActionMapping() {
// return actionMapping;
// }
// }
// Path: src/test/java/org/seasar/struts/config/S2FormBeanConfigTest.java
import org.seasar.extension.unit.S2TestCase;
import org.seasar.struts.action.ActionFormWrapperClass;
/*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.config;
/**
* @author higa
*
*/
public class S2FormBeanConfigTest extends S2TestCase {
/**
* @throws Exception
*/
public void testCreateActionForm() throws Exception {
register(MyAction.class, "myAction");
S2ActionMapping actionMapping = new S2ActionMapping();
actionMapping.setComponentDef(getComponentDef("myAction"));
| ActionFormWrapperClass wrapperClass = new ActionFormWrapperClass(
|
seasarorg/sa-struts | src/main/java/org/seasar/struts/config/S2ActionMapping.java | // Path: src/main/java/org/seasar/struts/util/S2ExecuteConfigUtil.java
// public final class S2ExecuteConfigUtil {
//
// private static final String KEY = S2ExecuteConfigUtil.class.getName();
//
// private S2ExecuteConfigUtil() {
// }
//
// /**
// * 実行設定を返します。
// *
// * @return 実行設定
// */
// public static S2ExecuteConfig getExecuteConfig() {
// return (S2ExecuteConfig) RequestUtil.getRequest().getAttribute(KEY);
// }
//
// /**
// * 実行設定を設定します。
// *
// * @param executeConfig
// * 実行設定
// */
// public static void setExecuteConfig(S2ExecuteConfig executeConfig) {
// RequestUtil.getRequest().setAttribute(KEY, executeConfig);
// }
//
// /**
// * 実行設定を探します。
// *
// * @param actionPath
// * アクションパス
// * @param paramPath
// * パラメータパス
// * @return 実行設定
// */
// public static S2ExecuteConfig findExecuteConfig(String actionPath,
// String paramPath) {
// S2ModuleConfig moduleConfig = S2ModuleConfigUtil.getModuleConfig();
// S2ActionMapping actionMapping = (S2ActionMapping) moduleConfig
// .findActionConfig(actionPath);
// return actionMapping.findExecuteConfig(paramPath);
// }
//
// /**
// * 実行設定を探します。
// *
// * @param actionPath
// * アクションパス
// * @param request
// * リクエスト
// * @return 実行設定
// */
// public static S2ExecuteConfig findExecuteConfig(String actionPath,
// HttpServletRequest request) {
// S2ModuleConfig moduleConfig = S2ModuleConfigUtil.getModuleConfig();
// S2ActionMapping actionMapping = (S2ActionMapping) moduleConfig
// .findActionConfig(actionPath);
// return actionMapping.findExecuteConfig(request);
// }
// }
| import org.seasar.struts.util.ServletContextUtil;
import java.lang.reflect.Field;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.seasar.framework.beans.BeanDesc;
import org.seasar.framework.beans.factory.BeanDescFactory;
import org.seasar.framework.container.ComponentDef;
import org.seasar.framework.container.S2Container;
import org.seasar.framework.container.factory.SingletonS2ContainerFactory;
import org.seasar.framework.util.ArrayMap;
import org.seasar.framework.util.StringUtil;
import org.seasar.struts.util.RoutingUtil;
import org.seasar.struts.util.S2ExecuteConfigUtil;
| }
/**
* ルーティング用のパスを作成します。
*
* @param path
* パス
* @return ルーティング用のパス
*/
protected String createRoutingPath(String path) {
String originalPath = path;
String queryString = "";
int index = path.indexOf('?');
if (index >= 0) {
queryString = path.substring(index);
path = path.substring(0, index);
}
String[] names = StringUtil.split(path, "/");
S2Container container = SingletonS2ContainerFactory.getContainer();
StringBuilder sb = new StringBuilder(50);
for (int i = 0; i < names.length; i++) {
if (container.hasComponentDef(sb + names[i] + "Action")) {
String actionPath = RoutingUtil.getActionPath(names, i);
String paramPath = RoutingUtil.getParamPath(names, i + 1);
if (StringUtil.isEmpty(paramPath)) {
return actionPath
+ ".do"
+ getQueryString(queryString, actionPath,
paramPath, null);
}
| // Path: src/main/java/org/seasar/struts/util/S2ExecuteConfigUtil.java
// public final class S2ExecuteConfigUtil {
//
// private static final String KEY = S2ExecuteConfigUtil.class.getName();
//
// private S2ExecuteConfigUtil() {
// }
//
// /**
// * 実行設定を返します。
// *
// * @return 実行設定
// */
// public static S2ExecuteConfig getExecuteConfig() {
// return (S2ExecuteConfig) RequestUtil.getRequest().getAttribute(KEY);
// }
//
// /**
// * 実行設定を設定します。
// *
// * @param executeConfig
// * 実行設定
// */
// public static void setExecuteConfig(S2ExecuteConfig executeConfig) {
// RequestUtil.getRequest().setAttribute(KEY, executeConfig);
// }
//
// /**
// * 実行設定を探します。
// *
// * @param actionPath
// * アクションパス
// * @param paramPath
// * パラメータパス
// * @return 実行設定
// */
// public static S2ExecuteConfig findExecuteConfig(String actionPath,
// String paramPath) {
// S2ModuleConfig moduleConfig = S2ModuleConfigUtil.getModuleConfig();
// S2ActionMapping actionMapping = (S2ActionMapping) moduleConfig
// .findActionConfig(actionPath);
// return actionMapping.findExecuteConfig(paramPath);
// }
//
// /**
// * 実行設定を探します。
// *
// * @param actionPath
// * アクションパス
// * @param request
// * リクエスト
// * @return 実行設定
// */
// public static S2ExecuteConfig findExecuteConfig(String actionPath,
// HttpServletRequest request) {
// S2ModuleConfig moduleConfig = S2ModuleConfigUtil.getModuleConfig();
// S2ActionMapping actionMapping = (S2ActionMapping) moduleConfig
// .findActionConfig(actionPath);
// return actionMapping.findExecuteConfig(request);
// }
// }
// Path: src/main/java/org/seasar/struts/config/S2ActionMapping.java
import org.seasar.struts.util.ServletContextUtil;
import java.lang.reflect.Field;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.seasar.framework.beans.BeanDesc;
import org.seasar.framework.beans.factory.BeanDescFactory;
import org.seasar.framework.container.ComponentDef;
import org.seasar.framework.container.S2Container;
import org.seasar.framework.container.factory.SingletonS2ContainerFactory;
import org.seasar.framework.util.ArrayMap;
import org.seasar.framework.util.StringUtil;
import org.seasar.struts.util.RoutingUtil;
import org.seasar.struts.util.S2ExecuteConfigUtil;
}
/**
* ルーティング用のパスを作成します。
*
* @param path
* パス
* @return ルーティング用のパス
*/
protected String createRoutingPath(String path) {
String originalPath = path;
String queryString = "";
int index = path.indexOf('?');
if (index >= 0) {
queryString = path.substring(index);
path = path.substring(0, index);
}
String[] names = StringUtil.split(path, "/");
S2Container container = SingletonS2ContainerFactory.getContainer();
StringBuilder sb = new StringBuilder(50);
for (int i = 0; i < names.length; i++) {
if (container.hasComponentDef(sb + names[i] + "Action")) {
String actionPath = RoutingUtil.getActionPath(names, i);
String paramPath = RoutingUtil.getParamPath(names, i + 1);
if (StringUtil.isEmpty(paramPath)) {
return actionPath
+ ".do"
+ getQueryString(queryString, actionPath,
paramPath, null);
}
| S2ExecuteConfig executeConfig = S2ExecuteConfigUtil
|
seasarorg/sa-struts | src/main/java/org/seasar/struts/config/S2ExecuteConfig.java | // Path: src/main/java/org/seasar/struts/enums/SaveType.java
// public enum SaveType {
//
// /**
// * リクエストです。
// */
// REQUEST,
// /**
// * セッションです。
// */
// SESSION
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalInputPatternRuntimeException.java
// public class IllegalInputPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String inputPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param inputPattern
// * inputパターン
// */
// public IllegalInputPatternRuntimeException(String inputPattern) {
// super("ESAS0010", new Object[] { inputPattern });
// this.inputPattern = inputPattern;
// }
//
// /**
// * inputパターンを返します。
// *
// * @return inputパターン
// */
// public String getInputPattern() {
// return inputPattern;
// }
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalUrlPatternRuntimeException.java
// public class IllegalUrlPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String urlPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param urlPattern
// * URLパターン
// */
// public IllegalUrlPatternRuntimeException(String urlPattern) {
// super("ESAS0007", new Object[] { urlPattern });
// this.urlPattern = urlPattern;
// }
//
// /**
// * URLパターンを返します。
// *
// * @return URLパターン
// */
// public String getUrlPattern() {
// return urlPattern;
// }
// }
| import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.seasar.framework.util.StringUtil;
import org.seasar.struts.enums.SaveType;
import org.seasar.struts.exception.IllegalInputPatternRuntimeException;
import org.seasar.struts.exception.IllegalUrlPatternRuntimeException;
import org.seasar.struts.util.URLEncoderUtil;
| /*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.config;
/**
* Actionの実行メソッド用の設定です。
*
* @author higa
*
*/
public class S2ExecuteConfig implements Serializable {
private static final long serialVersionUID = 1L;
private static final String METHOD_NAME = "SAStruts.method";
/**
* メソッドです。
*/
protected Method method;
/**
* 検証メソッドです。
*/
protected List<S2ValidationConfig> validationConfigs;
/**
* エラーメッセージの保存場所です。
*/
| // Path: src/main/java/org/seasar/struts/enums/SaveType.java
// public enum SaveType {
//
// /**
// * リクエストです。
// */
// REQUEST,
// /**
// * セッションです。
// */
// SESSION
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalInputPatternRuntimeException.java
// public class IllegalInputPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String inputPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param inputPattern
// * inputパターン
// */
// public IllegalInputPatternRuntimeException(String inputPattern) {
// super("ESAS0010", new Object[] { inputPattern });
// this.inputPattern = inputPattern;
// }
//
// /**
// * inputパターンを返します。
// *
// * @return inputパターン
// */
// public String getInputPattern() {
// return inputPattern;
// }
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalUrlPatternRuntimeException.java
// public class IllegalUrlPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String urlPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param urlPattern
// * URLパターン
// */
// public IllegalUrlPatternRuntimeException(String urlPattern) {
// super("ESAS0007", new Object[] { urlPattern });
// this.urlPattern = urlPattern;
// }
//
// /**
// * URLパターンを返します。
// *
// * @return URLパターン
// */
// public String getUrlPattern() {
// return urlPattern;
// }
// }
// Path: src/main/java/org/seasar/struts/config/S2ExecuteConfig.java
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.seasar.framework.util.StringUtil;
import org.seasar.struts.enums.SaveType;
import org.seasar.struts.exception.IllegalInputPatternRuntimeException;
import org.seasar.struts.exception.IllegalUrlPatternRuntimeException;
import org.seasar.struts.util.URLEncoderUtil;
/*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.config;
/**
* Actionの実行メソッド用の設定です。
*
* @author higa
*
*/
public class S2ExecuteConfig implements Serializable {
private static final long serialVersionUID = 1L;
private static final String METHOD_NAME = "SAStruts.method";
/**
* メソッドです。
*/
protected Method method;
/**
* 検証メソッドです。
*/
protected List<S2ValidationConfig> validationConfigs;
/**
* エラーメッセージの保存場所です。
*/
| protected SaveType saveErrors = SaveType.REQUEST;
|
seasarorg/sa-struts | src/main/java/org/seasar/struts/config/S2ExecuteConfig.java | // Path: src/main/java/org/seasar/struts/enums/SaveType.java
// public enum SaveType {
//
// /**
// * リクエストです。
// */
// REQUEST,
// /**
// * セッションです。
// */
// SESSION
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalInputPatternRuntimeException.java
// public class IllegalInputPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String inputPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param inputPattern
// * inputパターン
// */
// public IllegalInputPatternRuntimeException(String inputPattern) {
// super("ESAS0010", new Object[] { inputPattern });
// this.inputPattern = inputPattern;
// }
//
// /**
// * inputパターンを返します。
// *
// * @return inputパターン
// */
// public String getInputPattern() {
// return inputPattern;
// }
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalUrlPatternRuntimeException.java
// public class IllegalUrlPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String urlPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param urlPattern
// * URLパターン
// */
// public IllegalUrlPatternRuntimeException(String urlPattern) {
// super("ESAS0007", new Object[] { urlPattern });
// this.urlPattern = urlPattern;
// }
//
// /**
// * URLパターンを返します。
// *
// * @return URLパターン
// */
// public String getUrlPattern() {
// return urlPattern;
// }
// }
| import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.seasar.framework.util.StringUtil;
import org.seasar.struts.enums.SaveType;
import org.seasar.struts.exception.IllegalInputPatternRuntimeException;
import org.seasar.struts.exception.IllegalUrlPatternRuntimeException;
import org.seasar.struts.util.URLEncoderUtil;
| * 検証エラー時の遷移先を返します。
*
* @return 検証エラー時の遷移先
*/
public String getInput() {
return input;
}
/**
* 検証エラー時の遷移先を設定します。
*
* @param input
* 検証エラー時の遷移先
*/
public void setInput(String input) {
this.input = input;
if (StringUtil.isEmpty(input)) {
return;
}
char[] chars = input.toCharArray();
int length = chars.length;
int index = -1;
for (int i = 0; i < length; i++) {
if (chars[i] == '{') {
index = i;
} else if (chars[i] == '}') {
if (index >= 0) {
inputParamNames.add(input.substring(index + 1, i));
index = -1;
} else {
| // Path: src/main/java/org/seasar/struts/enums/SaveType.java
// public enum SaveType {
//
// /**
// * リクエストです。
// */
// REQUEST,
// /**
// * セッションです。
// */
// SESSION
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalInputPatternRuntimeException.java
// public class IllegalInputPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String inputPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param inputPattern
// * inputパターン
// */
// public IllegalInputPatternRuntimeException(String inputPattern) {
// super("ESAS0010", new Object[] { inputPattern });
// this.inputPattern = inputPattern;
// }
//
// /**
// * inputパターンを返します。
// *
// * @return inputパターン
// */
// public String getInputPattern() {
// return inputPattern;
// }
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalUrlPatternRuntimeException.java
// public class IllegalUrlPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String urlPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param urlPattern
// * URLパターン
// */
// public IllegalUrlPatternRuntimeException(String urlPattern) {
// super("ESAS0007", new Object[] { urlPattern });
// this.urlPattern = urlPattern;
// }
//
// /**
// * URLパターンを返します。
// *
// * @return URLパターン
// */
// public String getUrlPattern() {
// return urlPattern;
// }
// }
// Path: src/main/java/org/seasar/struts/config/S2ExecuteConfig.java
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.seasar.framework.util.StringUtil;
import org.seasar.struts.enums.SaveType;
import org.seasar.struts.exception.IllegalInputPatternRuntimeException;
import org.seasar.struts.exception.IllegalUrlPatternRuntimeException;
import org.seasar.struts.util.URLEncoderUtil;
* 検証エラー時の遷移先を返します。
*
* @return 検証エラー時の遷移先
*/
public String getInput() {
return input;
}
/**
* 検証エラー時の遷移先を設定します。
*
* @param input
* 検証エラー時の遷移先
*/
public void setInput(String input) {
this.input = input;
if (StringUtil.isEmpty(input)) {
return;
}
char[] chars = input.toCharArray();
int length = chars.length;
int index = -1;
for (int i = 0; i < length; i++) {
if (chars[i] == '{') {
index = i;
} else if (chars[i] == '}') {
if (index >= 0) {
inputParamNames.add(input.substring(index + 1, i));
index = -1;
} else {
| throw new IllegalInputPatternRuntimeException(input);
|
seasarorg/sa-struts | src/main/java/org/seasar/struts/config/S2ExecuteConfig.java | // Path: src/main/java/org/seasar/struts/enums/SaveType.java
// public enum SaveType {
//
// /**
// * リクエストです。
// */
// REQUEST,
// /**
// * セッションです。
// */
// SESSION
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalInputPatternRuntimeException.java
// public class IllegalInputPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String inputPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param inputPattern
// * inputパターン
// */
// public IllegalInputPatternRuntimeException(String inputPattern) {
// super("ESAS0010", new Object[] { inputPattern });
// this.inputPattern = inputPattern;
// }
//
// /**
// * inputパターンを返します。
// *
// * @return inputパターン
// */
// public String getInputPattern() {
// return inputPattern;
// }
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalUrlPatternRuntimeException.java
// public class IllegalUrlPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String urlPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param urlPattern
// * URLパターン
// */
// public IllegalUrlPatternRuntimeException(String urlPattern) {
// super("ESAS0007", new Object[] { urlPattern });
// this.urlPattern = urlPattern;
// }
//
// /**
// * URLパターンを返します。
// *
// * @return URLパターン
// */
// public String getUrlPattern() {
// return urlPattern;
// }
// }
| import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.seasar.framework.util.StringUtil;
import org.seasar.struts.enums.SaveType;
import org.seasar.struts.exception.IllegalInputPatternRuntimeException;
import org.seasar.struts.exception.IllegalUrlPatternRuntimeException;
import org.seasar.struts.util.URLEncoderUtil;
| * @return URLのパターン
*/
public String getUrlPattern() {
return urlPattern;
}
/**
* URLのパターンを設定します。
*
* @param urlPattern
* URLのパターン
*/
public void setUrlPattern(String urlPattern) {
if (StringUtil.isEmpty(urlPattern)) {
return;
}
this.urlPattern = urlPattern;
StringBuilder sb = new StringBuilder(50);
char[] chars = urlPattern.toCharArray();
int length = chars.length;
int index = -1;
for (int i = 0; i < length; i++) {
if (chars[i] == '{') {
index = i;
} else if (chars[i] == '}') {
if (index >= 0) {
sb.append("([^/]+)");
urlParamNames.add(urlPattern.substring(index + 1, i));
index = -1;
} else {
| // Path: src/main/java/org/seasar/struts/enums/SaveType.java
// public enum SaveType {
//
// /**
// * リクエストです。
// */
// REQUEST,
// /**
// * セッションです。
// */
// SESSION
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalInputPatternRuntimeException.java
// public class IllegalInputPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String inputPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param inputPattern
// * inputパターン
// */
// public IllegalInputPatternRuntimeException(String inputPattern) {
// super("ESAS0010", new Object[] { inputPattern });
// this.inputPattern = inputPattern;
// }
//
// /**
// * inputパターンを返します。
// *
// * @return inputパターン
// */
// public String getInputPattern() {
// return inputPattern;
// }
// }
//
// Path: src/main/java/org/seasar/struts/exception/IllegalUrlPatternRuntimeException.java
// public class IllegalUrlPatternRuntimeException extends SRuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private String urlPattern;
//
// /**
// * インスタンスを構築します。
// *
// * @param urlPattern
// * URLパターン
// */
// public IllegalUrlPatternRuntimeException(String urlPattern) {
// super("ESAS0007", new Object[] { urlPattern });
// this.urlPattern = urlPattern;
// }
//
// /**
// * URLパターンを返します。
// *
// * @return URLパターン
// */
// public String getUrlPattern() {
// return urlPattern;
// }
// }
// Path: src/main/java/org/seasar/struts/config/S2ExecuteConfig.java
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.seasar.framework.util.StringUtil;
import org.seasar.struts.enums.SaveType;
import org.seasar.struts.exception.IllegalInputPatternRuntimeException;
import org.seasar.struts.exception.IllegalUrlPatternRuntimeException;
import org.seasar.struts.util.URLEncoderUtil;
* @return URLのパターン
*/
public String getUrlPattern() {
return urlPattern;
}
/**
* URLのパターンを設定します。
*
* @param urlPattern
* URLのパターン
*/
public void setUrlPattern(String urlPattern) {
if (StringUtil.isEmpty(urlPattern)) {
return;
}
this.urlPattern = urlPattern;
StringBuilder sb = new StringBuilder(50);
char[] chars = urlPattern.toCharArray();
int length = chars.length;
int index = -1;
for (int i = 0; i < length; i++) {
if (chars[i] == '{') {
index = i;
} else if (chars[i] == '}') {
if (index >= 0) {
sb.append("([^/]+)");
urlParamNames.add(urlPattern.substring(index + 1, i));
index = -1;
} else {
| throw new IllegalUrlPatternRuntimeException(urlPattern);
|
seasarorg/sa-struts | src/test/java/org/seasar/struts/util/ValidatorResourcesUtilTest.java | // Path: src/main/java/org/seasar/struts/validator/S2ValidatorResources.java
// public class S2ValidatorResources extends ValidatorResources implements
// Disposable {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * DTDがどこに登録されているかです。
// */
// protected static final String REGISTRATIONS[] = {
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN",
// "/org/apache/commons/validator/resources/validator_1_0.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0.1//EN",
// "/org/apache/commons/validator/resources/validator_1_0_1.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN",
// "/org/apache/commons/validator/resources/validator_1_1.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN",
// "/org/apache/commons/validator/resources/validator_1_1_3.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.2.0//EN",
// "/org/apache/commons/validator/resources/validator_1_2_0.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN",
// "/org/apache/commons/validator/resources/validator_1_3_0.dtd" };
//
// /**
// * 初期化されたかどうかです。
// */
// protected volatile boolean initialized = false;
//
// /**
// * フォームのマップです。
// */
// protected Map<String, Form> forms = new HashMap<String, Form>();
//
// /**
// * インスタンスを構築します。
// */
// public S2ValidatorResources() {
// }
//
// /**
// * インスタンスを構築します。
// *
// * @param streams
// * 入力ストリームの配列
// * @throws IOException
// * IO例外が発生した場合。
// * @throws SAXException
// * SAX例外が発生した場合。
// */
// public S2ValidatorResources(InputStream[] streams) throws IOException,
// SAXException {
// URL rulesUrl = ValidatorResources.class
// .getResource("digester-rules.xml");
// Digester digester = DigesterLoader.createDigester(rulesUrl);
// digester.setNamespaceAware(true);
// digester.setValidating(true);
// digester.setUseContextClassLoader(true);
// for (int i = 0; i < REGISTRATIONS.length; i += 2) {
// URL url = ValidatorResources.class
// .getResource(REGISTRATIONS[i + 1]);
// if (url != null) {
// digester.register(REGISTRATIONS[i], url.toString());
// }
// }
// for (int i = 0; i < streams.length; i++) {
// digester.push(this);
// digester.parse(streams[i]);
// }
// initialize();
// }
//
// /**
// * 初期化します。
// */
// public void initialize() {
// DisposableUtil.add(this);
// initialized = true;
// }
//
// public void dispose() {
// forms.clear();
// initialized = false;
// }
//
// @Override
// public Form getForm(Locale locale, String formKey) {
// if (!initialized) {
// initialize();
// }
// Form form = forms.get(formKey);
// if (form == null) {
// if (HotdeployUtil.isHotdeploy() && formKey.endsWith("Form")) {
// SingletonS2ContainerFactory.getContainer().getComponentDef(
// formKey.substring(0, formKey.length() - 4));
// form = forms.get(formKey);
// }
// }
// return form;
// }
//
// /**
// * フォームを追加します。
// *
// * @param form
// * フォーム
// */
// public void addForm(Form form) {
// forms.put(form.getName(), form);
// }
//
// /**
// * 定数を返します。
// *
// * @param name
// * @return 定数
// */
// @SuppressWarnings("deprecation")
// public String getConstant(String name) {
// return (String) hConstants.get(name);
// }
// }
| import org.apache.struts.validator.ValidatorPlugIn;
import org.seasar.extension.unit.S2TestCase;
import org.seasar.struts.validator.S2ValidatorResources;
| /*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.util;
/**
* @author higa
*
*/
public class ValidatorResourcesUtilTest extends S2TestCase {
/**
* @throws Exception
*/
public void testGetModuleConfig() throws Exception {
getServletContext().setAttribute(ValidatorPlugIn.VALIDATOR_KEY,
| // Path: src/main/java/org/seasar/struts/validator/S2ValidatorResources.java
// public class S2ValidatorResources extends ValidatorResources implements
// Disposable {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * DTDがどこに登録されているかです。
// */
// protected static final String REGISTRATIONS[] = {
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN",
// "/org/apache/commons/validator/resources/validator_1_0.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0.1//EN",
// "/org/apache/commons/validator/resources/validator_1_0_1.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN",
// "/org/apache/commons/validator/resources/validator_1_1.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN",
// "/org/apache/commons/validator/resources/validator_1_1_3.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.2.0//EN",
// "/org/apache/commons/validator/resources/validator_1_2_0.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN",
// "/org/apache/commons/validator/resources/validator_1_3_0.dtd" };
//
// /**
// * 初期化されたかどうかです。
// */
// protected volatile boolean initialized = false;
//
// /**
// * フォームのマップです。
// */
// protected Map<String, Form> forms = new HashMap<String, Form>();
//
// /**
// * インスタンスを構築します。
// */
// public S2ValidatorResources() {
// }
//
// /**
// * インスタンスを構築します。
// *
// * @param streams
// * 入力ストリームの配列
// * @throws IOException
// * IO例外が発生した場合。
// * @throws SAXException
// * SAX例外が発生した場合。
// */
// public S2ValidatorResources(InputStream[] streams) throws IOException,
// SAXException {
// URL rulesUrl = ValidatorResources.class
// .getResource("digester-rules.xml");
// Digester digester = DigesterLoader.createDigester(rulesUrl);
// digester.setNamespaceAware(true);
// digester.setValidating(true);
// digester.setUseContextClassLoader(true);
// for (int i = 0; i < REGISTRATIONS.length; i += 2) {
// URL url = ValidatorResources.class
// .getResource(REGISTRATIONS[i + 1]);
// if (url != null) {
// digester.register(REGISTRATIONS[i], url.toString());
// }
// }
// for (int i = 0; i < streams.length; i++) {
// digester.push(this);
// digester.parse(streams[i]);
// }
// initialize();
// }
//
// /**
// * 初期化します。
// */
// public void initialize() {
// DisposableUtil.add(this);
// initialized = true;
// }
//
// public void dispose() {
// forms.clear();
// initialized = false;
// }
//
// @Override
// public Form getForm(Locale locale, String formKey) {
// if (!initialized) {
// initialize();
// }
// Form form = forms.get(formKey);
// if (form == null) {
// if (HotdeployUtil.isHotdeploy() && formKey.endsWith("Form")) {
// SingletonS2ContainerFactory.getContainer().getComponentDef(
// formKey.substring(0, formKey.length() - 4));
// form = forms.get(formKey);
// }
// }
// return form;
// }
//
// /**
// * フォームを追加します。
// *
// * @param form
// * フォーム
// */
// public void addForm(Form form) {
// forms.put(form.getName(), form);
// }
//
// /**
// * 定数を返します。
// *
// * @param name
// * @return 定数
// */
// @SuppressWarnings("deprecation")
// public String getConstant(String name) {
// return (String) hConstants.get(name);
// }
// }
// Path: src/test/java/org/seasar/struts/util/ValidatorResourcesUtilTest.java
import org.apache.struts.validator.ValidatorPlugIn;
import org.seasar.extension.unit.S2TestCase;
import org.seasar.struts.validator.S2ValidatorResources;
/*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.util;
/**
* @author higa
*
*/
public class ValidatorResourcesUtilTest extends S2TestCase {
/**
* @throws Exception
*/
public void testGetModuleConfig() throws Exception {
getServletContext().setAttribute(ValidatorPlugIn.VALIDATOR_KEY,
| new S2ValidatorResources());
|
seasarorg/sa-struts | src/main/java/org/seasar/struts/util/ValidatorResourcesUtil.java | // Path: src/main/java/org/seasar/struts/validator/S2ValidatorResources.java
// public class S2ValidatorResources extends ValidatorResources implements
// Disposable {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * DTDがどこに登録されているかです。
// */
// protected static final String REGISTRATIONS[] = {
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN",
// "/org/apache/commons/validator/resources/validator_1_0.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0.1//EN",
// "/org/apache/commons/validator/resources/validator_1_0_1.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN",
// "/org/apache/commons/validator/resources/validator_1_1.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN",
// "/org/apache/commons/validator/resources/validator_1_1_3.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.2.0//EN",
// "/org/apache/commons/validator/resources/validator_1_2_0.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN",
// "/org/apache/commons/validator/resources/validator_1_3_0.dtd" };
//
// /**
// * 初期化されたかどうかです。
// */
// protected volatile boolean initialized = false;
//
// /**
// * フォームのマップです。
// */
// protected Map<String, Form> forms = new HashMap<String, Form>();
//
// /**
// * インスタンスを構築します。
// */
// public S2ValidatorResources() {
// }
//
// /**
// * インスタンスを構築します。
// *
// * @param streams
// * 入力ストリームの配列
// * @throws IOException
// * IO例外が発生した場合。
// * @throws SAXException
// * SAX例外が発生した場合。
// */
// public S2ValidatorResources(InputStream[] streams) throws IOException,
// SAXException {
// URL rulesUrl = ValidatorResources.class
// .getResource("digester-rules.xml");
// Digester digester = DigesterLoader.createDigester(rulesUrl);
// digester.setNamespaceAware(true);
// digester.setValidating(true);
// digester.setUseContextClassLoader(true);
// for (int i = 0; i < REGISTRATIONS.length; i += 2) {
// URL url = ValidatorResources.class
// .getResource(REGISTRATIONS[i + 1]);
// if (url != null) {
// digester.register(REGISTRATIONS[i], url.toString());
// }
// }
// for (int i = 0; i < streams.length; i++) {
// digester.push(this);
// digester.parse(streams[i]);
// }
// initialize();
// }
//
// /**
// * 初期化します。
// */
// public void initialize() {
// DisposableUtil.add(this);
// initialized = true;
// }
//
// public void dispose() {
// forms.clear();
// initialized = false;
// }
//
// @Override
// public Form getForm(Locale locale, String formKey) {
// if (!initialized) {
// initialize();
// }
// Form form = forms.get(formKey);
// if (form == null) {
// if (HotdeployUtil.isHotdeploy() && formKey.endsWith("Form")) {
// SingletonS2ContainerFactory.getContainer().getComponentDef(
// formKey.substring(0, formKey.length() - 4));
// form = forms.get(formKey);
// }
// }
// return form;
// }
//
// /**
// * フォームを追加します。
// *
// * @param form
// * フォーム
// */
// public void addForm(Form form) {
// forms.put(form.getName(), form);
// }
//
// /**
// * 定数を返します。
// *
// * @param name
// * @return 定数
// */
// @SuppressWarnings("deprecation")
// public String getConstant(String name) {
// return (String) hConstants.get(name);
// }
// }
| import org.apache.struts.validator.ValidatorPlugIn;
import org.seasar.struts.validator.S2ValidatorResources;
| /*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.util;
/**
* 検証リソースに関するユーティリティです。
*
* @author higa
*
*/
public final class ValidatorResourcesUtil {
private ValidatorResourcesUtil() {
}
/**
* 検証リソースを返します。
*
* @return 検証リソース
*/
| // Path: src/main/java/org/seasar/struts/validator/S2ValidatorResources.java
// public class S2ValidatorResources extends ValidatorResources implements
// Disposable {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * DTDがどこに登録されているかです。
// */
// protected static final String REGISTRATIONS[] = {
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN",
// "/org/apache/commons/validator/resources/validator_1_0.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0.1//EN",
// "/org/apache/commons/validator/resources/validator_1_0_1.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN",
// "/org/apache/commons/validator/resources/validator_1_1.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN",
// "/org/apache/commons/validator/resources/validator_1_1_3.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.2.0//EN",
// "/org/apache/commons/validator/resources/validator_1_2_0.dtd",
// "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN",
// "/org/apache/commons/validator/resources/validator_1_3_0.dtd" };
//
// /**
// * 初期化されたかどうかです。
// */
// protected volatile boolean initialized = false;
//
// /**
// * フォームのマップです。
// */
// protected Map<String, Form> forms = new HashMap<String, Form>();
//
// /**
// * インスタンスを構築します。
// */
// public S2ValidatorResources() {
// }
//
// /**
// * インスタンスを構築します。
// *
// * @param streams
// * 入力ストリームの配列
// * @throws IOException
// * IO例外が発生した場合。
// * @throws SAXException
// * SAX例外が発生した場合。
// */
// public S2ValidatorResources(InputStream[] streams) throws IOException,
// SAXException {
// URL rulesUrl = ValidatorResources.class
// .getResource("digester-rules.xml");
// Digester digester = DigesterLoader.createDigester(rulesUrl);
// digester.setNamespaceAware(true);
// digester.setValidating(true);
// digester.setUseContextClassLoader(true);
// for (int i = 0; i < REGISTRATIONS.length; i += 2) {
// URL url = ValidatorResources.class
// .getResource(REGISTRATIONS[i + 1]);
// if (url != null) {
// digester.register(REGISTRATIONS[i], url.toString());
// }
// }
// for (int i = 0; i < streams.length; i++) {
// digester.push(this);
// digester.parse(streams[i]);
// }
// initialize();
// }
//
// /**
// * 初期化します。
// */
// public void initialize() {
// DisposableUtil.add(this);
// initialized = true;
// }
//
// public void dispose() {
// forms.clear();
// initialized = false;
// }
//
// @Override
// public Form getForm(Locale locale, String formKey) {
// if (!initialized) {
// initialize();
// }
// Form form = forms.get(formKey);
// if (form == null) {
// if (HotdeployUtil.isHotdeploy() && formKey.endsWith("Form")) {
// SingletonS2ContainerFactory.getContainer().getComponentDef(
// formKey.substring(0, formKey.length() - 4));
// form = forms.get(formKey);
// }
// }
// return form;
// }
//
// /**
// * フォームを追加します。
// *
// * @param form
// * フォーム
// */
// public void addForm(Form form) {
// forms.put(form.getName(), form);
// }
//
// /**
// * 定数を返します。
// *
// * @param name
// * @return 定数
// */
// @SuppressWarnings("deprecation")
// public String getConstant(String name) {
// return (String) hConstants.get(name);
// }
// }
// Path: src/main/java/org/seasar/struts/util/ValidatorResourcesUtil.java
import org.apache.struts.validator.ValidatorPlugIn;
import org.seasar.struts.validator.S2ValidatorResources;
/*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.util;
/**
* 検証リソースに関するユーティリティです。
*
* @author higa
*
*/
public final class ValidatorResourcesUtil {
private ValidatorResourcesUtil() {
}
/**
* 検証リソースを返します。
*
* @return 検証リソース
*/
| public static S2ValidatorResources getValidatorResources() {
|
seasarorg/sa-struts | src/main/java/org/seasar/struts/exception/ActionMessagesException.java | // Path: src/main/java/org/seasar/struts/enums/SaveType.java
// public enum SaveType {
//
// /**
// * リクエストです。
// */
// REQUEST,
// /**
// * セッションです。
// */
// SESSION
// }
| import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.seasar.struts.enums.SaveType;
| /*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.exception;
/**
* アクションメッセージ用の例外です。
*
* @author higa
*
*/
public class ActionMessagesException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* アクションメッセージの集合です。
*/
protected ActionMessages messages = new ActionMessages();
/**
* エラーメッセージをどこに保存するかです。
*/
| // Path: src/main/java/org/seasar/struts/enums/SaveType.java
// public enum SaveType {
//
// /**
// * リクエストです。
// */
// REQUEST,
// /**
// * セッションです。
// */
// SESSION
// }
// Path: src/main/java/org/seasar/struts/exception/ActionMessagesException.java
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.seasar.struts.enums.SaveType;
/*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.struts.exception;
/**
* アクションメッセージ用の例外です。
*
* @author higa
*
*/
public class ActionMessagesException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* アクションメッセージの集合です。
*/
protected ActionMessages messages = new ActionMessages();
/**
* エラーメッセージをどこに保存するかです。
*/
| protected SaveType saveErrors = SaveType.REQUEST;
|
Nilhcem/frcndict-android | src/com/nilhcem/frcndict/database/StarredDbHelper.java | // Path: src/com/nilhcem/frcndict/settings/SettingsActivity.java
// public final class SettingsActivity extends PreferenceActivity {
//
// // Shared preferences
// public static final String PREFS_NAME = "SharedPrefs";
// public static final String KEY_DB_PATH_OLD = "dbPath";
// public static final String KEY_INSTALLED = "installed";
//
// public static final String KEY_CHINESE_CHARS = "chineseChars";
// public static final String VAL_CHINESE_CHARS_SIMP = "1";
// public static final String VAL_CHINESE_CHARS_TRAD = "2";
// public static final String VAL_CHINESE_CHARS_BOTH_ST = "3";
// public static final String VAL_CHINESE_CHARS_BOTH_TS = "4";
//
// public static final String KEY_PINYIN = "pinyin";
// public static final String VAL_PINYIN_NONE = "1";
// public static final String VAL_PINYIN_TONES = "2";
// public static final String VAL_PINYIN_NUMBER = "3";
// public static final String VAL_PINYIN_ZHUYIN = "4";
//
// public static final String KEY_COLOR_HANZI = "hanziColoring";
// public static final String KEY_DARK_THEME = "darkTheme";
//
// public static final String KEY_TEXT_SIZE = "textSize";
// private static final String VAL_TEXT_SIZE_SMALL = "1";
// private static final String VAL_TEXT_SIZE_MEDIUM = "2";
// private static final String VAL_TEXT_SIZE_BIG = "3";
//
// // Other preferences
// public static final int NB_ENTRIES_PER_LIST = 20;
//
// private static final String KEY_ADVANCED = "advanced";
// private static final String KEY_INSTALL_TTS = "installTTS";
// private static final String KEY_IMPORT_EXPORT = "importExport";
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// AbstractDictActivity.checkForNightModeTheme(this, prefs);
//
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.xml.preferences);
// prefs.registerOnSharedPreferenceChangeListener(((ApplicationController) getApplication())
// .getOnPreferencesChangedListener());
// removeImportExportIfNoSdCard();
// removeInstallTtsIfNoFreeSpaceOnExternalStoreOrAlreadyInstalled();
// }
//
// // returns the array index depending on the user's prefs font sizes (small: 0, medium: 1, big: 2)
// public static int getArrayIdxFontSizes(SharedPreferences prefs) {
// int index;
//
// String sizePref = prefs.getString(SettingsActivity.KEY_TEXT_SIZE, SettingsActivity.VAL_TEXT_SIZE_MEDIUM);
// if (sizePref.equals(SettingsActivity.VAL_TEXT_SIZE_SMALL)) {
// index = 0;
// } else if (sizePref.equals(SettingsActivity.VAL_TEXT_SIZE_MEDIUM)) {
// index = 1;
// } else { // VAL_TEXT_SIZE_BIG
// index = 2;
// }
// return index;
// }
//
// private void removeImportExportIfNoSdCard() {
// PreferenceCategory advanced = (PreferenceCategory) findPreference(SettingsActivity.KEY_ADVANCED);
// Preference importExport = findPreference(SettingsActivity.KEY_IMPORT_EXPORT);
// if (advanced != null && importExport != null && !FileHandler.isSdCardMounted()) {
// advanced.removePreference(importExport);
// }
// }
//
// /**
// * Remove option if voices are already installed or if available space on external storage < 100MB.
// */
// private void removeInstallTtsIfNoFreeSpaceOnExternalStoreOrAlreadyInstalled() {
// PreferenceCategory advanced = (PreferenceCategory) findPreference(SettingsActivity.KEY_ADVANCED);
// Preference installTts = findPreference(SettingsActivity.KEY_INSTALL_TTS);
//
// if (advanced != null && installTts != null
// && (FileHandler.getFreeSpaceInExternalStorage() < 100
// || FileHandler.areVoicesInstalled())) {
// advanced.removePreference(installTts);
// }
// }
// }
| import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.nilhcem.frcndict.settings.SettingsActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement; | package com.nilhcem.frcndict.database;
public final class StarredDbHelper extends SQLiteOpenHelper {
public static final String STARRED_TABLE_NAME = "starred";
public static final String STARRED_KEY_SIMPLIFIED = "simplified";
public static final String STARRED_KEY_DATE = "date";
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
private static final String DATABASE_NAME = "starred.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE `"
+ STARRED_TABLE_NAME + "` (`" + STARRED_KEY_SIMPLIFIED
+ "` text not null, `" + STARRED_KEY_DATE + "` text);";
public StarredDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public List<String> getAllStarred(Integer curPage) {
List<String> starred = new ArrayList<String>();
StringBuilder query = new StringBuilder("SELECT `")
.append(StarredDbHelper.STARRED_KEY_SIMPLIFIED)
.append("` FROM `").append(StarredDbHelper.STARRED_TABLE_NAME)
.append("` ORDER BY `")
.append(StarredDbHelper.STARRED_KEY_DATE)
.append("` DESC LIMIT ") | // Path: src/com/nilhcem/frcndict/settings/SettingsActivity.java
// public final class SettingsActivity extends PreferenceActivity {
//
// // Shared preferences
// public static final String PREFS_NAME = "SharedPrefs";
// public static final String KEY_DB_PATH_OLD = "dbPath";
// public static final String KEY_INSTALLED = "installed";
//
// public static final String KEY_CHINESE_CHARS = "chineseChars";
// public static final String VAL_CHINESE_CHARS_SIMP = "1";
// public static final String VAL_CHINESE_CHARS_TRAD = "2";
// public static final String VAL_CHINESE_CHARS_BOTH_ST = "3";
// public static final String VAL_CHINESE_CHARS_BOTH_TS = "4";
//
// public static final String KEY_PINYIN = "pinyin";
// public static final String VAL_PINYIN_NONE = "1";
// public static final String VAL_PINYIN_TONES = "2";
// public static final String VAL_PINYIN_NUMBER = "3";
// public static final String VAL_PINYIN_ZHUYIN = "4";
//
// public static final String KEY_COLOR_HANZI = "hanziColoring";
// public static final String KEY_DARK_THEME = "darkTheme";
//
// public static final String KEY_TEXT_SIZE = "textSize";
// private static final String VAL_TEXT_SIZE_SMALL = "1";
// private static final String VAL_TEXT_SIZE_MEDIUM = "2";
// private static final String VAL_TEXT_SIZE_BIG = "3";
//
// // Other preferences
// public static final int NB_ENTRIES_PER_LIST = 20;
//
// private static final String KEY_ADVANCED = "advanced";
// private static final String KEY_INSTALL_TTS = "installTTS";
// private static final String KEY_IMPORT_EXPORT = "importExport";
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// AbstractDictActivity.checkForNightModeTheme(this, prefs);
//
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.xml.preferences);
// prefs.registerOnSharedPreferenceChangeListener(((ApplicationController) getApplication())
// .getOnPreferencesChangedListener());
// removeImportExportIfNoSdCard();
// removeInstallTtsIfNoFreeSpaceOnExternalStoreOrAlreadyInstalled();
// }
//
// // returns the array index depending on the user's prefs font sizes (small: 0, medium: 1, big: 2)
// public static int getArrayIdxFontSizes(SharedPreferences prefs) {
// int index;
//
// String sizePref = prefs.getString(SettingsActivity.KEY_TEXT_SIZE, SettingsActivity.VAL_TEXT_SIZE_MEDIUM);
// if (sizePref.equals(SettingsActivity.VAL_TEXT_SIZE_SMALL)) {
// index = 0;
// } else if (sizePref.equals(SettingsActivity.VAL_TEXT_SIZE_MEDIUM)) {
// index = 1;
// } else { // VAL_TEXT_SIZE_BIG
// index = 2;
// }
// return index;
// }
//
// private void removeImportExportIfNoSdCard() {
// PreferenceCategory advanced = (PreferenceCategory) findPreference(SettingsActivity.KEY_ADVANCED);
// Preference importExport = findPreference(SettingsActivity.KEY_IMPORT_EXPORT);
// if (advanced != null && importExport != null && !FileHandler.isSdCardMounted()) {
// advanced.removePreference(importExport);
// }
// }
//
// /**
// * Remove option if voices are already installed or if available space on external storage < 100MB.
// */
// private void removeInstallTtsIfNoFreeSpaceOnExternalStoreOrAlreadyInstalled() {
// PreferenceCategory advanced = (PreferenceCategory) findPreference(SettingsActivity.KEY_ADVANCED);
// Preference installTts = findPreference(SettingsActivity.KEY_INSTALL_TTS);
//
// if (advanced != null && installTts != null
// && (FileHandler.getFreeSpaceInExternalStorage() < 100
// || FileHandler.areVoicesInstalled())) {
// advanced.removePreference(installTts);
// }
// }
// }
// Path: src/com/nilhcem/frcndict/database/StarredDbHelper.java
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.nilhcem.frcndict.settings.SettingsActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
package com.nilhcem.frcndict.database;
public final class StarredDbHelper extends SQLiteOpenHelper {
public static final String STARRED_TABLE_NAME = "starred";
public static final String STARRED_KEY_SIMPLIFIED = "simplified";
public static final String STARRED_KEY_DATE = "date";
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
private static final String DATABASE_NAME = "starred.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE `"
+ STARRED_TABLE_NAME + "` (`" + STARRED_KEY_SIMPLIFIED
+ "` text not null, `" + STARRED_KEY_DATE + "` text);";
public StarredDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public List<String> getAllStarred(Integer curPage) {
List<String> starred = new ArrayList<String>();
StringBuilder query = new StringBuilder("SELECT `")
.append(StarredDbHelper.STARRED_KEY_SIMPLIFIED)
.append("` FROM `").append(StarredDbHelper.STARRED_TABLE_NAME)
.append("` ORDER BY `")
.append(StarredDbHelper.STARRED_KEY_DATE)
.append("` DESC LIMIT ") | .append(SettingsActivity.NB_ENTRIES_PER_LIST * curPage) |
Nilhcem/frcndict-android | src/com/nilhcem/frcndict/core/list/EndlessScrollListener.java | // Path: src/com/nilhcem/frcndict/core/Log.java
// public final class Log {
//
// private static final boolean LOG_ERROR = Config.LOGLEVEL > 0;
// private static final boolean LOG_WARN = Config.LOGLEVEL > 1;
// private static final boolean LOG_INFO = Config.LOGLEVEL > 2;
// private static final boolean LOG_DEBUG = Config.LOGLEVEL > 3;
//
// private Log() {
// throw new UnsupportedOperationException();
// }
//
// public static void d(String tag, String msgFormat, Object... args) {
// if (LOG_DEBUG) {
// try {
// android.util.Log.d(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.d(tag, msgFormat);
// }
// }
// }
//
// public static void w(String tag, String msgFormat, Object... args) {
// if (LOG_WARN) {
// try {
// android.util.Log.w(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.w(tag, msgFormat);
// }
// }
// }
//
// public static void i(String tag, String msgFormat, Object... args) {
// if (LOG_INFO) {
// try {
// android.util.Log.i(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.i(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t) {
// if (LOG_ERROR) {
// android.util.Log.e(tag, "", t);
// }
// }
//
// public static void e(String tag, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args), t);
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat, t);
// }
// }
// }
// }
| import java.util.Observable;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import com.nilhcem.frcndict.core.Log; | package com.nilhcem.frcndict.core.list;
public final class EndlessScrollListener extends Observable implements OnScrollListener {
private int mCurrentPage; // Current loaded "page" of data
private int mPreviousTotal; // Total nb of items in the dataset.
private boolean mLoading; // True if we are still waiting for the last set of data to load.
public EndlessScrollListener() {
super();
reset();
}
// called every time the list is scrolled to check if the latest element of the list is visible, to run a special operation
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (mLoading && (totalItemCount > mPreviousTotal)) {
// If the dataset count has changed, it has finished loading
mLoading = false;
mPreviousTotal = totalItemCount;
mCurrentPage++;
}
// If it isn't currently loading, we check to see if we need to reload more data.
if (!mLoading && totalItemCount > 0 && ((firstVisibleItem + visibleItemCount) == totalItemCount)) { | // Path: src/com/nilhcem/frcndict/core/Log.java
// public final class Log {
//
// private static final boolean LOG_ERROR = Config.LOGLEVEL > 0;
// private static final boolean LOG_WARN = Config.LOGLEVEL > 1;
// private static final boolean LOG_INFO = Config.LOGLEVEL > 2;
// private static final boolean LOG_DEBUG = Config.LOGLEVEL > 3;
//
// private Log() {
// throw new UnsupportedOperationException();
// }
//
// public static void d(String tag, String msgFormat, Object... args) {
// if (LOG_DEBUG) {
// try {
// android.util.Log.d(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.d(tag, msgFormat);
// }
// }
// }
//
// public static void w(String tag, String msgFormat, Object... args) {
// if (LOG_WARN) {
// try {
// android.util.Log.w(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.w(tag, msgFormat);
// }
// }
// }
//
// public static void i(String tag, String msgFormat, Object... args) {
// if (LOG_INFO) {
// try {
// android.util.Log.i(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.i(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t) {
// if (LOG_ERROR) {
// android.util.Log.e(tag, "", t);
// }
// }
//
// public static void e(String tag, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args), t);
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat, t);
// }
// }
// }
// }
// Path: src/com/nilhcem/frcndict/core/list/EndlessScrollListener.java
import java.util.Observable;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import com.nilhcem.frcndict.core.Log;
package com.nilhcem.frcndict.core.list;
public final class EndlessScrollListener extends Observable implements OnScrollListener {
private int mCurrentPage; // Current loaded "page" of data
private int mPreviousTotal; // Total nb of items in the dataset.
private boolean mLoading; // True if we are still waiting for the last set of data to load.
public EndlessScrollListener() {
super();
reset();
}
// called every time the list is scrolled to check if the latest element of the list is visible, to run a special operation
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (mLoading && (totalItemCount > mPreviousTotal)) {
// If the dataset count has changed, it has finished loading
mLoading = false;
mPreviousTotal = totalItemCount;
mCurrentPage++;
}
// If it isn't currently loading, we check to see if we need to reload more data.
if (!mLoading && totalItemCount > 0 && ((firstVisibleItem + visibleItemCount) == totalItemCount)) { | Log.d(EndlessScrollListener.class.getSimpleName(), "[End of scroll] Load more data"); |
Nilhcem/frcndict-android | src/com/nilhcem/frcndict/core/layout/StarButton.java | // Path: src/com/nilhcem/frcndict/database/StarredDbHelper.java
// public final class StarredDbHelper extends SQLiteOpenHelper {
//
// public static final String STARRED_TABLE_NAME = "starred";
// public static final String STARRED_KEY_SIMPLIFIED = "simplified";
// public static final String STARRED_KEY_DATE = "date";
//
// public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
//
// private static final String DATABASE_NAME = "starred.db";
// private static final int DATABASE_VERSION = 1;
//
// private static final String DATABASE_CREATE = "CREATE TABLE `"
// + STARRED_TABLE_NAME + "` (`" + STARRED_KEY_SIMPLIFIED
// + "` text not null, `" + STARRED_KEY_DATE + "` text);";
//
// public StarredDbHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(DATABASE_CREATE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// }
//
// public List<String> getAllStarred(Integer curPage) {
// List<String> starred = new ArrayList<String>();
//
// StringBuilder query = new StringBuilder("SELECT `")
// .append(StarredDbHelper.STARRED_KEY_SIMPLIFIED)
// .append("` FROM `").append(StarredDbHelper.STARRED_TABLE_NAME)
// .append("` ORDER BY `")
// .append(StarredDbHelper.STARRED_KEY_DATE)
// .append("` DESC LIMIT ")
// .append(SettingsActivity.NB_ENTRIES_PER_LIST * curPage)
// .append(", ").append(SettingsActivity.NB_ENTRIES_PER_LIST + 1);
//
// SQLiteDatabase db = getReadableDatabase();
// Cursor c = db.rawQuery(query.toString(), null);
// if (c != null) {
// while (c.moveToNext()) {
// starred.add(c.getString(0));
// }
// c.close();
// }
// return starred;
// }
//
// public String getStarredDate(String simplified) {
// String starredDate = null;
//
// SQLiteDatabase db = getReadableDatabase();
// Cursor c = db.query(StarredDbHelper.STARRED_TABLE_NAME,
// new String[] { StarredDbHelper.STARRED_KEY_DATE },
// String.format(Locale.US, "%s=?", StarredDbHelper.STARRED_KEY_SIMPLIFIED),
// new String[] { simplified }, null, null, null, "1");
//
// if (c != null) {
// if (c.moveToFirst()) {
// starredDate = c.getString(c
// .getColumnIndex(StarredDbHelper.STARRED_KEY_DATE));
// }
// c.close();
// }
//
// return starredDate;
// }
//
// public void setStarredDate(String simplified, Date starredDate) {
// String dateStr = null;
//
// if (starredDate != null) {
// dateStr = DATE_FORMAT.format(starredDate);
// }
// setStarredDate(simplified, dateStr);
// }
//
// public void setStarredDate(String simplified, String starredDate) {
// SQLiteDatabase db = getReadableDatabase();
//
// // Delete
// db.delete(StarredDbHelper.STARRED_TABLE_NAME,
// String.format(Locale.US, "%s=?", StarredDbHelper.STARRED_KEY_SIMPLIFIED),
// new String[] { simplified });
//
// // Insert
// if (starredDate != null) {
// ContentValues values = new ContentValues();
// values.put(StarredDbHelper.STARRED_KEY_SIMPLIFIED, simplified);
// values.put(StarredDbHelper.STARRED_KEY_DATE, starredDate);
// db.insert(STARRED_TABLE_NAME, null, values);
// }
// }
//
// public long getNbStarred() {
// StringBuilder query = new StringBuilder("SELECT count(`")
// .append(StarredDbHelper.STARRED_KEY_SIMPLIFIED)
// .append("`) FROM `").append(StarredDbHelper.STARRED_TABLE_NAME)
// .append("`");
//
// SQLiteDatabase db = getReadableDatabase();
// SQLiteStatement statement = db.compileStatement(query.toString());
// return statement.simpleQueryForLong();
// }
//
// public Cursor getAllStarredCursor() {
// SQLiteDatabase db = getReadableDatabase();
// return db.query(StarredDbHelper.STARRED_TABLE_NAME, new String[] {
// StarredDbHelper.STARRED_KEY_SIMPLIFIED,
// StarredDbHelper.STARRED_KEY_DATE }, null, null, null, null,
// null);
// }
// }
| import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.nilhcem.frcndict.R;
import com.nilhcem.frcndict.database.StarredDbHelper; | package com.nilhcem.frcndict.core.layout;
public final class StarButton extends RelativeLayout {
private Context mParent;
private String mSimplified; | // Path: src/com/nilhcem/frcndict/database/StarredDbHelper.java
// public final class StarredDbHelper extends SQLiteOpenHelper {
//
// public static final String STARRED_TABLE_NAME = "starred";
// public static final String STARRED_KEY_SIMPLIFIED = "simplified";
// public static final String STARRED_KEY_DATE = "date";
//
// public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
//
// private static final String DATABASE_NAME = "starred.db";
// private static final int DATABASE_VERSION = 1;
//
// private static final String DATABASE_CREATE = "CREATE TABLE `"
// + STARRED_TABLE_NAME + "` (`" + STARRED_KEY_SIMPLIFIED
// + "` text not null, `" + STARRED_KEY_DATE + "` text);";
//
// public StarredDbHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(DATABASE_CREATE);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// }
//
// public List<String> getAllStarred(Integer curPage) {
// List<String> starred = new ArrayList<String>();
//
// StringBuilder query = new StringBuilder("SELECT `")
// .append(StarredDbHelper.STARRED_KEY_SIMPLIFIED)
// .append("` FROM `").append(StarredDbHelper.STARRED_TABLE_NAME)
// .append("` ORDER BY `")
// .append(StarredDbHelper.STARRED_KEY_DATE)
// .append("` DESC LIMIT ")
// .append(SettingsActivity.NB_ENTRIES_PER_LIST * curPage)
// .append(", ").append(SettingsActivity.NB_ENTRIES_PER_LIST + 1);
//
// SQLiteDatabase db = getReadableDatabase();
// Cursor c = db.rawQuery(query.toString(), null);
// if (c != null) {
// while (c.moveToNext()) {
// starred.add(c.getString(0));
// }
// c.close();
// }
// return starred;
// }
//
// public String getStarredDate(String simplified) {
// String starredDate = null;
//
// SQLiteDatabase db = getReadableDatabase();
// Cursor c = db.query(StarredDbHelper.STARRED_TABLE_NAME,
// new String[] { StarredDbHelper.STARRED_KEY_DATE },
// String.format(Locale.US, "%s=?", StarredDbHelper.STARRED_KEY_SIMPLIFIED),
// new String[] { simplified }, null, null, null, "1");
//
// if (c != null) {
// if (c.moveToFirst()) {
// starredDate = c.getString(c
// .getColumnIndex(StarredDbHelper.STARRED_KEY_DATE));
// }
// c.close();
// }
//
// return starredDate;
// }
//
// public void setStarredDate(String simplified, Date starredDate) {
// String dateStr = null;
//
// if (starredDate != null) {
// dateStr = DATE_FORMAT.format(starredDate);
// }
// setStarredDate(simplified, dateStr);
// }
//
// public void setStarredDate(String simplified, String starredDate) {
// SQLiteDatabase db = getReadableDatabase();
//
// // Delete
// db.delete(StarredDbHelper.STARRED_TABLE_NAME,
// String.format(Locale.US, "%s=?", StarredDbHelper.STARRED_KEY_SIMPLIFIED),
// new String[] { simplified });
//
// // Insert
// if (starredDate != null) {
// ContentValues values = new ContentValues();
// values.put(StarredDbHelper.STARRED_KEY_SIMPLIFIED, simplified);
// values.put(StarredDbHelper.STARRED_KEY_DATE, starredDate);
// db.insert(STARRED_TABLE_NAME, null, values);
// }
// }
//
// public long getNbStarred() {
// StringBuilder query = new StringBuilder("SELECT count(`")
// .append(StarredDbHelper.STARRED_KEY_SIMPLIFIED)
// .append("`) FROM `").append(StarredDbHelper.STARRED_TABLE_NAME)
// .append("`");
//
// SQLiteDatabase db = getReadableDatabase();
// SQLiteStatement statement = db.compileStatement(query.toString());
// return statement.simpleQueryForLong();
// }
//
// public Cursor getAllStarredCursor() {
// SQLiteDatabase db = getReadableDatabase();
// return db.query(StarredDbHelper.STARRED_TABLE_NAME, new String[] {
// StarredDbHelper.STARRED_KEY_SIMPLIFIED,
// StarredDbHelper.STARRED_KEY_DATE }, null, null, null, null,
// null);
// }
// }
// Path: src/com/nilhcem/frcndict/core/layout/StarButton.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.nilhcem.frcndict.R;
import com.nilhcem.frcndict.database.StarredDbHelper;
package com.nilhcem.frcndict.core.layout;
public final class StarButton extends RelativeLayout {
private Context mParent;
private String mSimplified; | private StarredDbHelper mDb; |
Nilhcem/frcndict-android | src/com/nilhcem/frcndict/meaning/StrokesOrderDisplayer.java | // Path: src/com/nilhcem/frcndict/utils/FileHandler.java
// public final class FileHandler {
//
// public static final String SD_BACKUP_RESTORE_FILE = "cfdict.xml";
// private static final String SD_PATH = "/Android/data/";
// private static final String INTERNAL_PATH = "/data/";
// private static final String VOICES_DIR = "/chinese-tts-data";
// private static final String STROKES_DIR = "/chinese-stroke-data";
// private static final String STROKES_EXT = ".gif";
// private static final int BYTES_IN_A_MB = 1048576; // 1048576 = Nb of bytes in a MB: 1 * 1024 (kb) * 1024 (mb)
//
// private FileHandler() {
// throw new UnsupportedOperationException();
// }
//
// public static String getDbStorageDirectory(Context context) {
// File external = FileHandler.getAppRootDir(context.getApplicationContext(), true);
// if (external != null && external.exists() && external.canRead() && external.canWrite()) {
// return external.getAbsolutePath();
// } else {
// external = FileHandler.getAppRootDir(context.getApplicationContext(), false);
// if (external != null && external.exists() && external.canRead() && external.canWrite()) {
// return external.getAbsolutePath();
// }
// }
// return null;
// }
//
// private static File getAppRootDir(Context appContext, boolean sdcard) {
// File rootDir = null;
//
// if (sdcard) {
// File externalDir = Environment.getExternalStorageDirectory();
// if (externalDir == null) {
// sdcard = false;
// } else {
// rootDir = new File(externalDir.getAbsolutePath()
// + FileHandler.SD_PATH + appContext.getClass().getPackage().getName());
// }
// }
// if (!sdcard) {
// rootDir = new File(Environment.getDataDirectory().getAbsolutePath()
// + FileHandler.INTERNAL_PATH + appContext.getClass().getPackage().getName());
// }
//
// if (!rootDir.exists()) {
// rootDir.mkdirs();
// }
// return rootDir;
// }
//
// public static boolean isSdCardMounted() {
// return android.os.Environment.getExternalStorageState().equals(
// android.os.Environment.MEDIA_MOUNTED);
// }
//
// public static File getBackupRestoreFile() {
// return new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + "/" + FileHandler.SD_BACKUP_RESTORE_FILE);
// }
//
// public static File getVoicesDir() {
// File file = null;
//
// if (isSdCardMounted()) {
// file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + FileHandler.VOICES_DIR);
// }
// return file;
// }
//
// /**
// * @return free space in external storage (in MB).
// */
// public static double getFreeSpaceInExternalStorage() {
// double freeSpace = 0;
//
// if (isSdCardMounted()) {
// StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
// double sdAvailSize = (double)stat.getAvailableBlocks() * (double)stat.getBlockSize();
// freeSpace = sdAvailSize / FileHandler.BYTES_IN_A_MB;
// }
// return freeSpace;
// }
//
// public static File getStrokesDir() {
// File file = null;
//
// if (isSdCardMounted()) {
// file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + FileHandler.STROKES_DIR);
// }
// return file;
// }
//
// public static File getStrokesFile(String hanzi) {
// File strokeFile = null;
//
// File strokeDir = FileHandler.getStrokesDir();
// if (strokeDir != null) {
// strokeFile = new File(strokeDir, String.format(Locale.US, "%s%s", hanzi, FileHandler.STROKES_EXT));
// }
// return strokeFile;
// }
//
// public static boolean areVoicesInstalled() {
// boolean installed = false;
//
// File voices = FileHandler.getVoicesDir();
// if (voices != null) {
// // Check if it contains some data
// File mp3 = new File(voices, "zhang1.mp3");
// if (mp3.isFile()) {
// installed = true;
// }
// }
// return installed;
// }
// }
| import java.io.File;
import com.nilhcem.frcndict.utils.FileHandler;
import android.app.AlertDialog;
import android.content.Context;
import android.view.Gravity;
import android.webkit.WebView;
import android.widget.LinearLayout; | package com.nilhcem.frcndict.meaning;
public final class StrokesOrderDisplayer {
private static final int WEBVIEW_DP_SIZE = 256;
private static final String WEBVIEW_MIME = "text/html";
private static final String WEBVIEW_ENCODING = "UTF-8";
private static final String STROKES_DIR_PATH;
static { | // Path: src/com/nilhcem/frcndict/utils/FileHandler.java
// public final class FileHandler {
//
// public static final String SD_BACKUP_RESTORE_FILE = "cfdict.xml";
// private static final String SD_PATH = "/Android/data/";
// private static final String INTERNAL_PATH = "/data/";
// private static final String VOICES_DIR = "/chinese-tts-data";
// private static final String STROKES_DIR = "/chinese-stroke-data";
// private static final String STROKES_EXT = ".gif";
// private static final int BYTES_IN_A_MB = 1048576; // 1048576 = Nb of bytes in a MB: 1 * 1024 (kb) * 1024 (mb)
//
// private FileHandler() {
// throw new UnsupportedOperationException();
// }
//
// public static String getDbStorageDirectory(Context context) {
// File external = FileHandler.getAppRootDir(context.getApplicationContext(), true);
// if (external != null && external.exists() && external.canRead() && external.canWrite()) {
// return external.getAbsolutePath();
// } else {
// external = FileHandler.getAppRootDir(context.getApplicationContext(), false);
// if (external != null && external.exists() && external.canRead() && external.canWrite()) {
// return external.getAbsolutePath();
// }
// }
// return null;
// }
//
// private static File getAppRootDir(Context appContext, boolean sdcard) {
// File rootDir = null;
//
// if (sdcard) {
// File externalDir = Environment.getExternalStorageDirectory();
// if (externalDir == null) {
// sdcard = false;
// } else {
// rootDir = new File(externalDir.getAbsolutePath()
// + FileHandler.SD_PATH + appContext.getClass().getPackage().getName());
// }
// }
// if (!sdcard) {
// rootDir = new File(Environment.getDataDirectory().getAbsolutePath()
// + FileHandler.INTERNAL_PATH + appContext.getClass().getPackage().getName());
// }
//
// if (!rootDir.exists()) {
// rootDir.mkdirs();
// }
// return rootDir;
// }
//
// public static boolean isSdCardMounted() {
// return android.os.Environment.getExternalStorageState().equals(
// android.os.Environment.MEDIA_MOUNTED);
// }
//
// public static File getBackupRestoreFile() {
// return new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + "/" + FileHandler.SD_BACKUP_RESTORE_FILE);
// }
//
// public static File getVoicesDir() {
// File file = null;
//
// if (isSdCardMounted()) {
// file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + FileHandler.VOICES_DIR);
// }
// return file;
// }
//
// /**
// * @return free space in external storage (in MB).
// */
// public static double getFreeSpaceInExternalStorage() {
// double freeSpace = 0;
//
// if (isSdCardMounted()) {
// StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
// double sdAvailSize = (double)stat.getAvailableBlocks() * (double)stat.getBlockSize();
// freeSpace = sdAvailSize / FileHandler.BYTES_IN_A_MB;
// }
// return freeSpace;
// }
//
// public static File getStrokesDir() {
// File file = null;
//
// if (isSdCardMounted()) {
// file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + FileHandler.STROKES_DIR);
// }
// return file;
// }
//
// public static File getStrokesFile(String hanzi) {
// File strokeFile = null;
//
// File strokeDir = FileHandler.getStrokesDir();
// if (strokeDir != null) {
// strokeFile = new File(strokeDir, String.format(Locale.US, "%s%s", hanzi, FileHandler.STROKES_EXT));
// }
// return strokeFile;
// }
//
// public static boolean areVoicesInstalled() {
// boolean installed = false;
//
// File voices = FileHandler.getVoicesDir();
// if (voices != null) {
// // Check if it contains some data
// File mp3 = new File(voices, "zhang1.mp3");
// if (mp3.isFile()) {
// installed = true;
// }
// }
// return installed;
// }
// }
// Path: src/com/nilhcem/frcndict/meaning/StrokesOrderDisplayer.java
import java.io.File;
import com.nilhcem.frcndict.utils.FileHandler;
import android.app.AlertDialog;
import android.content.Context;
import android.view.Gravity;
import android.webkit.WebView;
import android.widget.LinearLayout;
package com.nilhcem.frcndict.meaning;
public final class StrokesOrderDisplayer {
private static final int WEBVIEW_DP_SIZE = 256;
private static final String WEBVIEW_MIME = "text/html";
private static final String WEBVIEW_ENCODING = "UTF-8";
private static final String STROKES_DIR_PATH;
static { | File strokeDir = FileHandler.getStrokesDir(); |
Nilhcem/frcndict-android | src/com/nilhcem/frcndict/settings/OnPreferencesChangedListener.java | // Path: src/com/nilhcem/frcndict/core/Log.java
// public final class Log {
//
// private static final boolean LOG_ERROR = Config.LOGLEVEL > 0;
// private static final boolean LOG_WARN = Config.LOGLEVEL > 1;
// private static final boolean LOG_INFO = Config.LOGLEVEL > 2;
// private static final boolean LOG_DEBUG = Config.LOGLEVEL > 3;
//
// private Log() {
// throw new UnsupportedOperationException();
// }
//
// public static void d(String tag, String msgFormat, Object... args) {
// if (LOG_DEBUG) {
// try {
// android.util.Log.d(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.d(tag, msgFormat);
// }
// }
// }
//
// public static void w(String tag, String msgFormat, Object... args) {
// if (LOG_WARN) {
// try {
// android.util.Log.w(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.w(tag, msgFormat);
// }
// }
// }
//
// public static void i(String tag, String msgFormat, Object... args) {
// if (LOG_INFO) {
// try {
// android.util.Log.i(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.i(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t) {
// if (LOG_ERROR) {
// android.util.Log.e(tag, "", t);
// }
// }
//
// public static void e(String tag, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args), t);
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat, t);
// }
// }
// }
// }
| import android.content.SharedPreferences;
import com.nilhcem.frcndict.core.Log; | package com.nilhcem.frcndict.settings;
public final class OnPreferencesChangedListener implements SharedPreferences.OnSharedPreferenceChangeListener {
private boolean mThemeHasChanged;
private boolean mResultListShouldBeUpdated;
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(SettingsActivity.KEY_DARK_THEME)) { | // Path: src/com/nilhcem/frcndict/core/Log.java
// public final class Log {
//
// private static final boolean LOG_ERROR = Config.LOGLEVEL > 0;
// private static final boolean LOG_WARN = Config.LOGLEVEL > 1;
// private static final boolean LOG_INFO = Config.LOGLEVEL > 2;
// private static final boolean LOG_DEBUG = Config.LOGLEVEL > 3;
//
// private Log() {
// throw new UnsupportedOperationException();
// }
//
// public static void d(String tag, String msgFormat, Object... args) {
// if (LOG_DEBUG) {
// try {
// android.util.Log.d(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.d(tag, msgFormat);
// }
// }
// }
//
// public static void w(String tag, String msgFormat, Object... args) {
// if (LOG_WARN) {
// try {
// android.util.Log.w(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.w(tag, msgFormat);
// }
// }
// }
//
// public static void i(String tag, String msgFormat, Object... args) {
// if (LOG_INFO) {
// try {
// android.util.Log.i(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.i(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t) {
// if (LOG_ERROR) {
// android.util.Log.e(tag, "", t);
// }
// }
//
// public static void e(String tag, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args), t);
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat, t);
// }
// }
// }
// }
// Path: src/com/nilhcem/frcndict/settings/OnPreferencesChangedListener.java
import android.content.SharedPreferences;
import com.nilhcem.frcndict.core.Log;
package com.nilhcem.frcndict.settings;
public final class OnPreferencesChangedListener implements SharedPreferences.OnSharedPreferenceChangeListener {
private boolean mThemeHasChanged;
private boolean mResultListShouldBeUpdated;
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(SettingsActivity.KEY_DARK_THEME)) { | Log.d(OnPreferencesChangedListener.class.getSimpleName(), "[Has changed] Theme"); |
Nilhcem/frcndict-android | src/com/nilhcem/frcndict/about/AboutDialog.java | // Path: src/com/nilhcem/frcndict/core/Log.java
// public final class Log {
//
// private static final boolean LOG_ERROR = Config.LOGLEVEL > 0;
// private static final boolean LOG_WARN = Config.LOGLEVEL > 1;
// private static final boolean LOG_INFO = Config.LOGLEVEL > 2;
// private static final boolean LOG_DEBUG = Config.LOGLEVEL > 3;
//
// private Log() {
// throw new UnsupportedOperationException();
// }
//
// public static void d(String tag, String msgFormat, Object... args) {
// if (LOG_DEBUG) {
// try {
// android.util.Log.d(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.d(tag, msgFormat);
// }
// }
// }
//
// public static void w(String tag, String msgFormat, Object... args) {
// if (LOG_WARN) {
// try {
// android.util.Log.w(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.w(tag, msgFormat);
// }
// }
// }
//
// public static void i(String tag, String msgFormat, Object... args) {
// if (LOG_INFO) {
// try {
// android.util.Log.i(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.i(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t) {
// if (LOG_ERROR) {
// android.util.Log.e(tag, "", t);
// }
// }
//
// public static void e(String tag, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args), t);
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat, t);
// }
// }
// }
// }
| import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.webkit.WebView;
import com.nilhcem.frcndict.R;
import com.nilhcem.frcndict.core.Log; |
// Get webview and enable JS
WebView webView = (WebView) findViewById(R.id.aboutWebView);
webView.getSettings().setJavaScriptEnabled(true);
// Add interface
webView.addJavascriptInterface(jsInterface, "android"); // "android" is the keyword that will be exposed in js
// Load file
webView.loadUrl(getLocaleUrl());
}
private String getLocaleUrl() {
boolean found = false;
String localeUrl = null;
try {
Locale locale = Locale.getDefault();
List<String> assets = Arrays.asList(mParentContext.getResources().getAssets().list(AboutDialog.ABOUT_ASSET_DIR));
localeUrl = String.format(Locale.US, "%s%s%s%s", AboutDialog.ABOUT_ASSET_FILE,
AboutDialog.ABOUT_ASSET_FILE_SEPARATOR, locale.getLanguage(),
AboutDialog.ABOUT_URL_EXTENSION);
if (assets.contains(localeUrl)) {
found = true;
}
if (locale.getCountry().equals("CN")) {
localeUrl = localeUrl.replace("zh", "zh-simplified");
}
} catch (IOException e) { | // Path: src/com/nilhcem/frcndict/core/Log.java
// public final class Log {
//
// private static final boolean LOG_ERROR = Config.LOGLEVEL > 0;
// private static final boolean LOG_WARN = Config.LOGLEVEL > 1;
// private static final boolean LOG_INFO = Config.LOGLEVEL > 2;
// private static final boolean LOG_DEBUG = Config.LOGLEVEL > 3;
//
// private Log() {
// throw new UnsupportedOperationException();
// }
//
// public static void d(String tag, String msgFormat, Object... args) {
// if (LOG_DEBUG) {
// try {
// android.util.Log.d(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.d(tag, msgFormat);
// }
// }
// }
//
// public static void w(String tag, String msgFormat, Object... args) {
// if (LOG_WARN) {
// try {
// android.util.Log.w(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.w(tag, msgFormat);
// }
// }
// }
//
// public static void i(String tag, String msgFormat, Object... args) {
// if (LOG_INFO) {
// try {
// android.util.Log.i(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.i(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t) {
// if (LOG_ERROR) {
// android.util.Log.e(tag, "", t);
// }
// }
//
// public static void e(String tag, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args));
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat);
// }
// }
// }
//
// public static void e(String tag, Throwable t, String msgFormat, Object... args) {
// if (LOG_ERROR) {
// try {
// android.util.Log.e(tag, String.format(Locale.US, msgFormat, args), t);
// } catch (NullPointerException e) {
// // Do nothing
// } catch (IllegalFormatException e) {
// android.util.Log.e(tag, msgFormat, t);
// }
// }
// }
// }
// Path: src/com/nilhcem/frcndict/about/AboutDialog.java
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.webkit.WebView;
import com.nilhcem.frcndict.R;
import com.nilhcem.frcndict.core.Log;
// Get webview and enable JS
WebView webView = (WebView) findViewById(R.id.aboutWebView);
webView.getSettings().setJavaScriptEnabled(true);
// Add interface
webView.addJavascriptInterface(jsInterface, "android"); // "android" is the keyword that will be exposed in js
// Load file
webView.loadUrl(getLocaleUrl());
}
private String getLocaleUrl() {
boolean found = false;
String localeUrl = null;
try {
Locale locale = Locale.getDefault();
List<String> assets = Arrays.asList(mParentContext.getResources().getAssets().list(AboutDialog.ABOUT_ASSET_DIR));
localeUrl = String.format(Locale.US, "%s%s%s%s", AboutDialog.ABOUT_ASSET_FILE,
AboutDialog.ABOUT_ASSET_FILE_SEPARATOR, locale.getLanguage(),
AboutDialog.ABOUT_URL_EXTENSION);
if (assets.contains(localeUrl)) {
found = true;
}
if (locale.getCountry().equals("CN")) {
localeUrl = localeUrl.replace("zh", "zh-simplified");
}
} catch (IOException e) { | Log.e(AboutDialog.class.getSimpleName(), e, "Can't find about asset"); |
spinnaker/scheduled-actions | scheduled-actions-cassandra/src/main/java/com/netflix/scheduledactions/persistence/cassandra/ThriftCassandraDao.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/Codec.java
// public interface Codec {
//
// /**
// * Compress the provided bytes array
// * @throws IOException
// */
// byte[] compress(byte[] bytes) throws IOException;
//
// /**
// * Un-compress the provided bytes array
// * @throws IOException
// */
// byte[] decompress(byte[] bytes) throws IOException;
// }
//
// Path: scheduled-actions-cassandra/src/main/java/com/netflix/scheduledactions/persistence/SnappyCodec.java
// public class SnappyCodec implements Codec {
//
// @Override
// public byte[] compress(byte[] bytes) throws IOException {
// return Snappy.compress(bytes);
// }
//
// @Override
// public byte[] decompress(byte[] bytes) throws IOException {
// return Snappy.uncompress(bytes);
// }
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.NotFoundException;
import com.netflix.astyanax.ddl.ColumnFamilyDefinition;
import com.netflix.astyanax.model.*;
import com.netflix.astyanax.query.RowQuery;
import com.netflix.astyanax.query.RowSliceQuery;
import com.netflix.astyanax.serializers.ByteBufferSerializer;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.astyanax.util.RangeBuilder;
import com.netflix.scheduledactions.persistence.Codec;
import com.netflix.scheduledactions.persistence.SnappyCodec; | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.persistence.cassandra;
public class ThriftCassandraDao<T> implements CassandraDao<T> {
public static final String ALL = "all";
private final Class<T> parameterClass;
private final Keyspace keyspace; | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/Codec.java
// public interface Codec {
//
// /**
// * Compress the provided bytes array
// * @throws IOException
// */
// byte[] compress(byte[] bytes) throws IOException;
//
// /**
// * Un-compress the provided bytes array
// * @throws IOException
// */
// byte[] decompress(byte[] bytes) throws IOException;
// }
//
// Path: scheduled-actions-cassandra/src/main/java/com/netflix/scheduledactions/persistence/SnappyCodec.java
// public class SnappyCodec implements Codec {
//
// @Override
// public byte[] compress(byte[] bytes) throws IOException {
// return Snappy.compress(bytes);
// }
//
// @Override
// public byte[] decompress(byte[] bytes) throws IOException {
// return Snappy.uncompress(bytes);
// }
// }
// Path: scheduled-actions-cassandra/src/main/java/com/netflix/scheduledactions/persistence/cassandra/ThriftCassandraDao.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.NotFoundException;
import com.netflix.astyanax.ddl.ColumnFamilyDefinition;
import com.netflix.astyanax.model.*;
import com.netflix.astyanax.query.RowQuery;
import com.netflix.astyanax.query.RowSliceQuery;
import com.netflix.astyanax.serializers.ByteBufferSerializer;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.astyanax.util.RangeBuilder;
import com.netflix.scheduledactions.persistence.Codec;
import com.netflix.scheduledactions.persistence.SnappyCodec;
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.persistence.cassandra;
public class ThriftCassandraDao<T> implements CassandraDao<T> {
public static final String ALL = "all";
private final Class<T> parameterClass;
private final Keyspace keyspace; | private final Codec codec; |
spinnaker/scheduled-actions | scheduled-actions-cassandra/src/main/java/com/netflix/scheduledactions/persistence/cassandra/ThriftCassandraDao.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/Codec.java
// public interface Codec {
//
// /**
// * Compress the provided bytes array
// * @throws IOException
// */
// byte[] compress(byte[] bytes) throws IOException;
//
// /**
// * Un-compress the provided bytes array
// * @throws IOException
// */
// byte[] decompress(byte[] bytes) throws IOException;
// }
//
// Path: scheduled-actions-cassandra/src/main/java/com/netflix/scheduledactions/persistence/SnappyCodec.java
// public class SnappyCodec implements Codec {
//
// @Override
// public byte[] compress(byte[] bytes) throws IOException {
// return Snappy.compress(bytes);
// }
//
// @Override
// public byte[] decompress(byte[] bytes) throws IOException {
// return Snappy.uncompress(bytes);
// }
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.NotFoundException;
import com.netflix.astyanax.ddl.ColumnFamilyDefinition;
import com.netflix.astyanax.model.*;
import com.netflix.astyanax.query.RowQuery;
import com.netflix.astyanax.query.RowSliceQuery;
import com.netflix.astyanax.serializers.ByteBufferSerializer;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.astyanax.util.RangeBuilder;
import com.netflix.scheduledactions.persistence.Codec;
import com.netflix.scheduledactions.persistence.SnappyCodec; | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.persistence.cassandra;
public class ThriftCassandraDao<T> implements CassandraDao<T> {
public static final String ALL = "all";
private final Class<T> parameterClass;
private final Keyspace keyspace;
private final Codec codec;
private final ObjectMapper objectMapper;
private final ColumnFamily<String, String> columnFamily;
public ThriftCassandraDao(Class<T> parameterClass, Keyspace keyspace, ObjectMapper objectMapper) { | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/Codec.java
// public interface Codec {
//
// /**
// * Compress the provided bytes array
// * @throws IOException
// */
// byte[] compress(byte[] bytes) throws IOException;
//
// /**
// * Un-compress the provided bytes array
// * @throws IOException
// */
// byte[] decompress(byte[] bytes) throws IOException;
// }
//
// Path: scheduled-actions-cassandra/src/main/java/com/netflix/scheduledactions/persistence/SnappyCodec.java
// public class SnappyCodec implements Codec {
//
// @Override
// public byte[] compress(byte[] bytes) throws IOException {
// return Snappy.compress(bytes);
// }
//
// @Override
// public byte[] decompress(byte[] bytes) throws IOException {
// return Snappy.uncompress(bytes);
// }
// }
// Path: scheduled-actions-cassandra/src/main/java/com/netflix/scheduledactions/persistence/cassandra/ThriftCassandraDao.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.NotFoundException;
import com.netflix.astyanax.ddl.ColumnFamilyDefinition;
import com.netflix.astyanax.model.*;
import com.netflix.astyanax.query.RowQuery;
import com.netflix.astyanax.query.RowSliceQuery;
import com.netflix.astyanax.serializers.ByteBufferSerializer;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.astyanax.util.RangeBuilder;
import com.netflix.scheduledactions.persistence.Codec;
import com.netflix.scheduledactions.persistence.SnappyCodec;
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.persistence.cassandra;
public class ThriftCassandraDao<T> implements CassandraDao<T> {
public static final String ALL = "all";
private final Class<T> parameterClass;
private final Keyspace keyspace;
private final Codec codec;
private final ObjectMapper objectMapper;
private final ColumnFamily<String, String> columnFamily;
public ThriftCassandraDao(Class<T> parameterClass, Keyspace keyspace, ObjectMapper objectMapper) { | this(parameterClass, keyspace, objectMapper, new SnappyCodec(), toTitleCase(parameterClass.getSimpleName())); |
spinnaker/scheduled-actions | scheduled-actions-clustered/src/main/java/com/netflix/scheduledactions/clustered/notifications/ExecutionMessage.java | // Path: scheduled-actions-clustered/src/main/java/com/netflix/scheduledactions/clustered/Status.java
// public enum Status {
// CREATED, UPDATED, DISABLED, ENABLED, DELETED, CANCELED
// }
| import com.netflix.scheduledactions.clustered.Status; | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.clustered.notifications;
public class ExecutionMessage {
private final String executionId;
private final String actionInstanceId; | // Path: scheduled-actions-clustered/src/main/java/com/netflix/scheduledactions/clustered/Status.java
// public enum Status {
// CREATED, UPDATED, DISABLED, ENABLED, DELETED, CANCELED
// }
// Path: scheduled-actions-clustered/src/main/java/com/netflix/scheduledactions/clustered/notifications/ExecutionMessage.java
import com.netflix.scheduledactions.clustered.Status;
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.clustered.notifications;
public class ExecutionMessage {
private final String executionId;
private final String actionInstanceId; | private final Status status; |
spinnaker/scheduled-actions | scheduled-actions-core/src/main/java/com/netflix/scheduledactions/DaoConfigurer.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
| import com.netflix.fenzo.triggers.persistence.TriggerDao;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao; | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions;
public class DaoConfigurer {
private final ActionInstanceDao actionInstanceDao;
private final TriggerDao triggerDao; | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/DaoConfigurer.java
import com.netflix.fenzo.triggers.persistence.TriggerDao;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao;
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions;
public class DaoConfigurer {
private final ActionInstanceDao actionInstanceDao;
private final TriggerDao triggerDao; | private final ExecutionDao executionDao; |
spinnaker/scheduled-actions | scheduled-actions-core/src/main/java/com/netflix/scheduledactions/ActionInstance.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/triggers/Trigger.java
// @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
// public interface Trigger {
// public void validate() throws IllegalArgumentException;
// public com.netflix.fenzo.triggers.Trigger<Context> createFenzoTrigger(Context context,
// Class<? extends Action1<Context>> action);
// }
| import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.netflix.scheduledactions.triggers.Trigger;
import java.util.*; | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions;
@JsonDeserialize(builder = ActionInstance.ActionInstanceBuilder.class)
public class ActionInstance implements Comparable<ActionInstance> {
public static final String DEFAULT_GROUP = "DEFAULT_GROUP";
public static final Class<? extends ExecutionListener> DEFAULT_EXECUTION_LISTENER_CLASS = NoOpExecutionListener.class;
public static final long DEFAULT_EXECUTION_TIMEOUT = -1L;
public static final ConcurrentExecutionStrategy DEFAULT_EXECUTION_STRATEGY = ConcurrentExecutionStrategy.REJECT;
private long creationTime;
private String id;
private String name;
private String group;
private Class<? extends Action> action;
private Class<? extends ExecutionListener> executionListener;
private Map<String, String> parameters; | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/triggers/Trigger.java
// @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
// public interface Trigger {
// public void validate() throws IllegalArgumentException;
// public com.netflix.fenzo.triggers.Trigger<Context> createFenzoTrigger(Context context,
// Class<? extends Action1<Context>> action);
// }
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/ActionInstance.java
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.netflix.scheduledactions.triggers.Trigger;
import java.util.*;
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions;
@JsonDeserialize(builder = ActionInstance.ActionInstanceBuilder.class)
public class ActionInstance implements Comparable<ActionInstance> {
public static final String DEFAULT_GROUP = "DEFAULT_GROUP";
public static final Class<? extends ExecutionListener> DEFAULT_EXECUTION_LISTENER_CLASS = NoOpExecutionListener.class;
public static final long DEFAULT_EXECUTION_TIMEOUT = -1L;
public static final ConcurrentExecutionStrategy DEFAULT_EXECUTION_STRATEGY = ConcurrentExecutionStrategy.REJECT;
private long creationTime;
private String id;
private String name;
private String group;
private Class<? extends Action> action;
private Class<? extends ExecutionListener> executionListener;
private Map<String, String> parameters; | private Trigger trigger; |
spinnaker/scheduled-actions | scheduled-actions-core/src/main/java/com/netflix/scheduledactions/ActionsOperator.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/exceptions/ActionInstanceNotFoundException.java
// public class ActionInstanceNotFoundException extends Exception {
//
// public ActionInstanceNotFoundException(String message) {
// super(message);
// }
//
// public ActionInstanceNotFoundException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
| import com.netflix.fenzo.triggers.TriggerOperator;
import com.netflix.fenzo.triggers.exceptions.SchedulerException;
import com.netflix.scheduledactions.exceptions.ActionInstanceNotFoundException;
import com.netflix.scheduledactions.exceptions.ExecutionNotFoundException;
import com.netflix.scheduledactions.executors.LocalThreadPoolBlockingExecutor;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean; | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions;
/**
* Primary class that operates on {@code ActionInstance}. This class should be initialized
* as a singleton in the application that is using this library.
*/
public class ActionsOperator {
public static final String DEFAULT_INITIATOR = "Unknown";
private final ActionInstanceDao actionInstanceDao; | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/exceptions/ActionInstanceNotFoundException.java
// public class ActionInstanceNotFoundException extends Exception {
//
// public ActionInstanceNotFoundException(String message) {
// super(message);
// }
//
// public ActionInstanceNotFoundException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/ActionsOperator.java
import com.netflix.fenzo.triggers.TriggerOperator;
import com.netflix.fenzo.triggers.exceptions.SchedulerException;
import com.netflix.scheduledactions.exceptions.ActionInstanceNotFoundException;
import com.netflix.scheduledactions.exceptions.ExecutionNotFoundException;
import com.netflix.scheduledactions.executors.LocalThreadPoolBlockingExecutor;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions;
/**
* Primary class that operates on {@code ActionInstance}. This class should be initialized
* as a singleton in the application that is using this library.
*/
public class ActionsOperator {
public static final String DEFAULT_INITIATOR = "Unknown";
private final ActionInstanceDao actionInstanceDao; | private final ExecutionDao executionDao; |
spinnaker/scheduled-actions | scheduled-actions-core/src/main/java/com/netflix/scheduledactions/ActionsOperator.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/exceptions/ActionInstanceNotFoundException.java
// public class ActionInstanceNotFoundException extends Exception {
//
// public ActionInstanceNotFoundException(String message) {
// super(message);
// }
//
// public ActionInstanceNotFoundException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
| import com.netflix.fenzo.triggers.TriggerOperator;
import com.netflix.fenzo.triggers.exceptions.SchedulerException;
import com.netflix.scheduledactions.exceptions.ActionInstanceNotFoundException;
import com.netflix.scheduledactions.exceptions.ExecutionNotFoundException;
import com.netflix.scheduledactions.executors.LocalThreadPoolBlockingExecutor;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean; | }
/**
* Returns a list of {@code Execution}s for a given actionInstance
*/
public List<Execution> getExecutions(String actionInstanceId) {
List<Execution> executions = executionDao.getExecutions(actionInstanceId);
if (executions != null) {
Collections.sort(executions);
}
return executions;
}
public Execution getExecution(String executionId) {
return executionDao.getExecution(executionId);
}
/**
* Registers a {@code ActionInstance} with actionInstance service
*/
public String registerActionInstance(ActionInstance actionInstance) {
checkInitialized();
return actionOperationsDelegate.register(actionInstance);
}
/**
* Disables the {@code ActionInstance}. If the {@code ActionInstance} is disabled it will NOT execute
* @throws ActionInstanceNotFoundException
* @throws com.netflix.scheduledactions.exceptions.ActionOperationException
*/ | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/exceptions/ActionInstanceNotFoundException.java
// public class ActionInstanceNotFoundException extends Exception {
//
// public ActionInstanceNotFoundException(String message) {
// super(message);
// }
//
// public ActionInstanceNotFoundException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/ActionsOperator.java
import com.netflix.fenzo.triggers.TriggerOperator;
import com.netflix.fenzo.triggers.exceptions.SchedulerException;
import com.netflix.scheduledactions.exceptions.ActionInstanceNotFoundException;
import com.netflix.scheduledactions.exceptions.ExecutionNotFoundException;
import com.netflix.scheduledactions.executors.LocalThreadPoolBlockingExecutor;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
}
/**
* Returns a list of {@code Execution}s for a given actionInstance
*/
public List<Execution> getExecutions(String actionInstanceId) {
List<Execution> executions = executionDao.getExecutions(actionInstanceId);
if (executions != null) {
Collections.sort(executions);
}
return executions;
}
public Execution getExecution(String executionId) {
return executionDao.getExecution(executionId);
}
/**
* Registers a {@code ActionInstance} with actionInstance service
*/
public String registerActionInstance(ActionInstance actionInstance) {
checkInitialized();
return actionOperationsDelegate.register(actionInstance);
}
/**
* Disables the {@code ActionInstance}. If the {@code ActionInstance} is disabled it will NOT execute
* @throws ActionInstanceNotFoundException
* @throws com.netflix.scheduledactions.exceptions.ActionOperationException
*/ | public ActionInstance disableActionInstance(String actionInstanceId) throws ActionInstanceNotFoundException { |
spinnaker/scheduled-actions | scheduled-actions-core/src/main/java/com/netflix/scheduledactions/triggers/IntervalTrigger.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/Context.java
// public class Context {
// private String actionInstanceId;
// private final String name;
// private final String group;
// private final Map<String, String> parameters;
//
// @JsonCreator
// public Context(@JsonProperty("actionInstanceId") String actionInstanceId,
// @JsonProperty("name") String name,
// @JsonProperty("group") String group,
// @JsonProperty("parameters") Map<String, String> parameters) {
// this.actionInstanceId = actionInstanceId;
// this.name = name;
// this.group = group;
// this.parameters = parameters;
// }
//
// public void setActionInstanceId(String actionInstanceId) {
// this.actionInstanceId = actionInstanceId;
// }
//
// public String getActionInstanceId() {
// return actionInstanceId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getGroup() {
// return group;
// }
//
// public Map<String, String> getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// return String.format(
// "Context: (actionInstance: %s, name: %s, group: %s, parameters: %s)", actionInstanceId, name, group, parameters
// );
// }
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.netflix.fenzo.triggers.TriggerUtils;
import com.netflix.scheduledactions.Context;
import rx.functions.Action1;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date; | /**
* Creates an interval trigger that starts immediately and repeats indefinitely
*/
public IntervalTrigger(int interval, TimeUnit intervalUnit) {
this(interval, intervalUnit, -1, null);
}
/**
* Creates an interval trigger based on the given parameters
*/
public IntervalTrigger(int interval, TimeUnit intervalUnit, int repeatCount, Date startAt) {
if (interval <= 0) {
throw new IllegalArgumentException(String.format("Invalid interval %s specified for the IntervalTrigger", interval));
}
if (startAt == null) {
startAt = new Date();
}
DateFormat dateFormat = new SimpleDateFormat(ISO_8601_DATE_FORMAT);
this.iso8601Interval = String.format(
"%s/%s%s%s", dateFormat.format(startAt), ISO_8601_TIME_PREFIX, interval, intervalUnit.getTimeUnitSuffix()
);
this.repeatCount = repeatCount;
}
@Override
public void validate() throws IllegalArgumentException {
TriggerUtils.validateISO8601Interval(iso8601Interval);
}
@Override | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/Context.java
// public class Context {
// private String actionInstanceId;
// private final String name;
// private final String group;
// private final Map<String, String> parameters;
//
// @JsonCreator
// public Context(@JsonProperty("actionInstanceId") String actionInstanceId,
// @JsonProperty("name") String name,
// @JsonProperty("group") String group,
// @JsonProperty("parameters") Map<String, String> parameters) {
// this.actionInstanceId = actionInstanceId;
// this.name = name;
// this.group = group;
// this.parameters = parameters;
// }
//
// public void setActionInstanceId(String actionInstanceId) {
// this.actionInstanceId = actionInstanceId;
// }
//
// public String getActionInstanceId() {
// return actionInstanceId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getGroup() {
// return group;
// }
//
// public Map<String, String> getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// return String.format(
// "Context: (actionInstance: %s, name: %s, group: %s, parameters: %s)", actionInstanceId, name, group, parameters
// );
// }
// }
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/triggers/IntervalTrigger.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.netflix.fenzo.triggers.TriggerUtils;
import com.netflix.scheduledactions.Context;
import rx.functions.Action1;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Creates an interval trigger that starts immediately and repeats indefinitely
*/
public IntervalTrigger(int interval, TimeUnit intervalUnit) {
this(interval, intervalUnit, -1, null);
}
/**
* Creates an interval trigger based on the given parameters
*/
public IntervalTrigger(int interval, TimeUnit intervalUnit, int repeatCount, Date startAt) {
if (interval <= 0) {
throw new IllegalArgumentException(String.format("Invalid interval %s specified for the IntervalTrigger", interval));
}
if (startAt == null) {
startAt = new Date();
}
DateFormat dateFormat = new SimpleDateFormat(ISO_8601_DATE_FORMAT);
this.iso8601Interval = String.format(
"%s/%s%s%s", dateFormat.format(startAt), ISO_8601_TIME_PREFIX, interval, intervalUnit.getTimeUnitSuffix()
);
this.repeatCount = repeatCount;
}
@Override
public void validate() throws IllegalArgumentException {
TriggerUtils.validateISO8601Interval(iso8601Interval);
}
@Override | public com.netflix.fenzo.triggers.Trigger<Context> createFenzoTrigger(Context context, |
spinnaker/scheduled-actions | scheduled-actions-core/src/main/java/com/netflix/scheduledactions/AbstractActionOperationsDelegate.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/exceptions/ActionInstanceNotFoundException.java
// public class ActionInstanceNotFoundException extends Exception {
//
// public ActionInstanceNotFoundException(String message) {
// super(message);
// }
//
// public ActionInstanceNotFoundException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/executors/Executor.java
// public interface Executor {
// public void execute(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// public void cancel(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
| import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.netflix.fenzo.triggers.TriggerOperator;
import com.netflix.fenzo.triggers.exceptions.SchedulerException;
import com.netflix.scheduledactions.exceptions.ActionInstanceNotFoundException;
import com.netflix.scheduledactions.exceptions.ActionOperationException;
import com.netflix.scheduledactions.exceptions.ExecutionException;
import com.netflix.scheduledactions.exceptions.ExecutionNotFoundException;
import com.netflix.scheduledactions.executors.Executor;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Action1;
import java.util.ArrayList; | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions;
public class AbstractActionOperationsDelegate implements ActionOperationsDelegate {
private static final Logger logger = LoggerFactory.getLogger(DefaultActionOperationsDelegate.class);
protected final TriggerOperator triggerOperator;
protected final ActionInstanceDao actionInstanceDao; | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/exceptions/ActionInstanceNotFoundException.java
// public class ActionInstanceNotFoundException extends Exception {
//
// public ActionInstanceNotFoundException(String message) {
// super(message);
// }
//
// public ActionInstanceNotFoundException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/executors/Executor.java
// public interface Executor {
// public void execute(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// public void cancel(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/AbstractActionOperationsDelegate.java
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.netflix.fenzo.triggers.TriggerOperator;
import com.netflix.fenzo.triggers.exceptions.SchedulerException;
import com.netflix.scheduledactions.exceptions.ActionInstanceNotFoundException;
import com.netflix.scheduledactions.exceptions.ActionOperationException;
import com.netflix.scheduledactions.exceptions.ExecutionException;
import com.netflix.scheduledactions.exceptions.ExecutionNotFoundException;
import com.netflix.scheduledactions.executors.Executor;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Action1;
import java.util.ArrayList;
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions;
public class AbstractActionOperationsDelegate implements ActionOperationsDelegate {
private static final Logger logger = LoggerFactory.getLogger(DefaultActionOperationsDelegate.class);
protected final TriggerOperator triggerOperator;
protected final ActionInstanceDao actionInstanceDao; | protected final ExecutionDao executionDao; |
spinnaker/scheduled-actions | scheduled-actions-core/src/main/java/com/netflix/scheduledactions/AbstractActionOperationsDelegate.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/exceptions/ActionInstanceNotFoundException.java
// public class ActionInstanceNotFoundException extends Exception {
//
// public ActionInstanceNotFoundException(String message) {
// super(message);
// }
//
// public ActionInstanceNotFoundException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/executors/Executor.java
// public interface Executor {
// public void execute(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// public void cancel(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
| import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.netflix.fenzo.triggers.TriggerOperator;
import com.netflix.fenzo.triggers.exceptions.SchedulerException;
import com.netflix.scheduledactions.exceptions.ActionInstanceNotFoundException;
import com.netflix.scheduledactions.exceptions.ActionOperationException;
import com.netflix.scheduledactions.exceptions.ExecutionException;
import com.netflix.scheduledactions.exceptions.ExecutionNotFoundException;
import com.netflix.scheduledactions.executors.Executor;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Action1;
import java.util.ArrayList; | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions;
public class AbstractActionOperationsDelegate implements ActionOperationsDelegate {
private static final Logger logger = LoggerFactory.getLogger(DefaultActionOperationsDelegate.class);
protected final TriggerOperator triggerOperator;
protected final ActionInstanceDao actionInstanceDao;
protected final ExecutionDao executionDao; | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/exceptions/ActionInstanceNotFoundException.java
// public class ActionInstanceNotFoundException extends Exception {
//
// public ActionInstanceNotFoundException(String message) {
// super(message);
// }
//
// public ActionInstanceNotFoundException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/executors/Executor.java
// public interface Executor {
// public void execute(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// public void cancel(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/AbstractActionOperationsDelegate.java
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.netflix.fenzo.triggers.TriggerOperator;
import com.netflix.fenzo.triggers.exceptions.SchedulerException;
import com.netflix.scheduledactions.exceptions.ActionInstanceNotFoundException;
import com.netflix.scheduledactions.exceptions.ActionOperationException;
import com.netflix.scheduledactions.exceptions.ExecutionException;
import com.netflix.scheduledactions.exceptions.ExecutionNotFoundException;
import com.netflix.scheduledactions.executors.Executor;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Action1;
import java.util.ArrayList;
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions;
public class AbstractActionOperationsDelegate implements ActionOperationsDelegate {
private static final Logger logger = LoggerFactory.getLogger(DefaultActionOperationsDelegate.class);
protected final TriggerOperator triggerOperator;
protected final ActionInstanceDao actionInstanceDao;
protected final ExecutionDao executionDao; | protected final Executor executor; |
spinnaker/scheduled-actions | scheduled-actions-core/src/main/java/com/netflix/scheduledactions/AbstractActionOperationsDelegate.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/exceptions/ActionInstanceNotFoundException.java
// public class ActionInstanceNotFoundException extends Exception {
//
// public ActionInstanceNotFoundException(String message) {
// super(message);
// }
//
// public ActionInstanceNotFoundException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/executors/Executor.java
// public interface Executor {
// public void execute(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// public void cancel(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
| import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.netflix.fenzo.triggers.TriggerOperator;
import com.netflix.fenzo.triggers.exceptions.SchedulerException;
import com.netflix.scheduledactions.exceptions.ActionInstanceNotFoundException;
import com.netflix.scheduledactions.exceptions.ActionOperationException;
import com.netflix.scheduledactions.exceptions.ExecutionException;
import com.netflix.scheduledactions.exceptions.ExecutionNotFoundException;
import com.netflix.scheduledactions.executors.Executor;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Action1;
import java.util.ArrayList; | * @param actionInstance
*/
@Override
public String register(ActionInstance actionInstance) {
validate(actionInstance);
actionInstanceDao.createActionInstance(actionInstance.getGroup(), actionInstance);
if (actionInstance.getTrigger() != null) {
actionInstance.setFenzoTrigger(actionInstance.getTrigger().createFenzoTrigger(actionInstance.getContext(),
InternalAction.class));
try {
triggerOperator.registerTrigger(actionInstance.getGroup(), actionInstance.getFenzoTrigger());
} catch (SchedulerException e) {
throw new ActionOperationException(String.format(
"Exception occurred while registering actionInstance %s", actionInstance), e);
}
}
actionInstanceDao.updateActionInstance(actionInstance);
logger.info("Successfully registered the actionInstance {}", actionInstance);
return actionInstance.getId();
}
public static class InternalAction implements Action1<Context> {
@Override
public void call(Context context) {
String actionInstanceId = context.getActionInstanceId();
try {
logger.info("[{}] InternalAction: Calling execute() on delegate with context: {}", actionInstanceId, context);
actionOperationsDelegate.execute(actionInstanceId, "ScheduledTrigger"); // TODO: Pass trigger info from context | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/exceptions/ActionInstanceNotFoundException.java
// public class ActionInstanceNotFoundException extends Exception {
//
// public ActionInstanceNotFoundException(String message) {
// super(message);
// }
//
// public ActionInstanceNotFoundException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/executors/Executor.java
// public interface Executor {
// public void execute(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// public void cancel(Action action, ActionInstance actionInstance, Execution execution) throws ExecutionException;
// }
//
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/persistence/ExecutionDao.java
// public interface ExecutionDao {
//
// public String createExecution(String actionInstanceId, Execution execution);
// public void updateExecution(Execution execution);
// public Execution getExecution(String executionId);
// public void deleteExecution(String actionInstanceId, Execution execution);
// public List<Execution> getExecutions(String actionInstanceId, int count);
// public List<Execution> getExecutions(String actionInstanceId);
//
// }
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/AbstractActionOperationsDelegate.java
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.netflix.fenzo.triggers.TriggerOperator;
import com.netflix.fenzo.triggers.exceptions.SchedulerException;
import com.netflix.scheduledactions.exceptions.ActionInstanceNotFoundException;
import com.netflix.scheduledactions.exceptions.ActionOperationException;
import com.netflix.scheduledactions.exceptions.ExecutionException;
import com.netflix.scheduledactions.exceptions.ExecutionNotFoundException;
import com.netflix.scheduledactions.executors.Executor;
import com.netflix.scheduledactions.persistence.ActionInstanceDao;
import com.netflix.scheduledactions.persistence.ExecutionDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Action1;
import java.util.ArrayList;
* @param actionInstance
*/
@Override
public String register(ActionInstance actionInstance) {
validate(actionInstance);
actionInstanceDao.createActionInstance(actionInstance.getGroup(), actionInstance);
if (actionInstance.getTrigger() != null) {
actionInstance.setFenzoTrigger(actionInstance.getTrigger().createFenzoTrigger(actionInstance.getContext(),
InternalAction.class));
try {
triggerOperator.registerTrigger(actionInstance.getGroup(), actionInstance.getFenzoTrigger());
} catch (SchedulerException e) {
throw new ActionOperationException(String.format(
"Exception occurred while registering actionInstance %s", actionInstance), e);
}
}
actionInstanceDao.updateActionInstance(actionInstance);
logger.info("Successfully registered the actionInstance {}", actionInstance);
return actionInstance.getId();
}
public static class InternalAction implements Action1<Context> {
@Override
public void call(Context context) {
String actionInstanceId = context.getActionInstanceId();
try {
logger.info("[{}] InternalAction: Calling execute() on delegate with context: {}", actionInstanceId, context);
actionOperationsDelegate.execute(actionInstanceId, "ScheduledTrigger"); // TODO: Pass trigger info from context | } catch (ActionInstanceNotFoundException e) {} |
spinnaker/scheduled-actions | scheduled-actions-core/src/main/java/com/netflix/scheduledactions/triggers/CronTrigger.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/Context.java
// public class Context {
// private String actionInstanceId;
// private final String name;
// private final String group;
// private final Map<String, String> parameters;
//
// @JsonCreator
// public Context(@JsonProperty("actionInstanceId") String actionInstanceId,
// @JsonProperty("name") String name,
// @JsonProperty("group") String group,
// @JsonProperty("parameters") Map<String, String> parameters) {
// this.actionInstanceId = actionInstanceId;
// this.name = name;
// this.group = group;
// this.parameters = parameters;
// }
//
// public void setActionInstanceId(String actionInstanceId) {
// this.actionInstanceId = actionInstanceId;
// }
//
// public String getActionInstanceId() {
// return actionInstanceId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getGroup() {
// return group;
// }
//
// public Map<String, String> getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// return String.format(
// "Context: (actionInstance: %s, name: %s, group: %s, parameters: %s)", actionInstanceId, name, group, parameters
// );
// }
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.netflix.scheduledactions.Context;
import rx.functions.Action1;
import java.util.Date; | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.triggers;
public class CronTrigger implements Trigger {
private final String cronExpression;
private final Date startAt;
private final String timeZoneId;
public CronTrigger(String cronExpression) {
this(cronExpression, "America/Los_Angeles", new Date());
}
@JsonCreator
public CronTrigger(@JsonProperty("cronExpression") String cronExpression,
@JsonProperty("timeZoneId") String timeZoneId,
@JsonProperty("startAt") Date startAt) {
this.cronExpression = cronExpression;
this.timeZoneId = timeZoneId;
this.startAt = startAt;
}
@Override
public void validate() throws IllegalArgumentException {
CronExpressionFuzzer.validate(cronExpression);
}
@Override | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/Context.java
// public class Context {
// private String actionInstanceId;
// private final String name;
// private final String group;
// private final Map<String, String> parameters;
//
// @JsonCreator
// public Context(@JsonProperty("actionInstanceId") String actionInstanceId,
// @JsonProperty("name") String name,
// @JsonProperty("group") String group,
// @JsonProperty("parameters") Map<String, String> parameters) {
// this.actionInstanceId = actionInstanceId;
// this.name = name;
// this.group = group;
// this.parameters = parameters;
// }
//
// public void setActionInstanceId(String actionInstanceId) {
// this.actionInstanceId = actionInstanceId;
// }
//
// public String getActionInstanceId() {
// return actionInstanceId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getGroup() {
// return group;
// }
//
// public Map<String, String> getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// return String.format(
// "Context: (actionInstance: %s, name: %s, group: %s, parameters: %s)", actionInstanceId, name, group, parameters
// );
// }
// }
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/triggers/CronTrigger.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.netflix.scheduledactions.Context;
import rx.functions.Action1;
import java.util.Date;
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.triggers;
public class CronTrigger implements Trigger {
private final String cronExpression;
private final Date startAt;
private final String timeZoneId;
public CronTrigger(String cronExpression) {
this(cronExpression, "America/Los_Angeles", new Date());
}
@JsonCreator
public CronTrigger(@JsonProperty("cronExpression") String cronExpression,
@JsonProperty("timeZoneId") String timeZoneId,
@JsonProperty("startAt") Date startAt) {
this.cronExpression = cronExpression;
this.timeZoneId = timeZoneId;
this.startAt = startAt;
}
@Override
public void validate() throws IllegalArgumentException {
CronExpressionFuzzer.validate(cronExpression);
}
@Override | public com.netflix.fenzo.triggers.Trigger<Context> createFenzoTrigger(Context context, |
spinnaker/scheduled-actions | scheduled-actions-core/src/main/java/com/netflix/scheduledactions/triggers/Trigger.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/Context.java
// public class Context {
// private String actionInstanceId;
// private final String name;
// private final String group;
// private final Map<String, String> parameters;
//
// @JsonCreator
// public Context(@JsonProperty("actionInstanceId") String actionInstanceId,
// @JsonProperty("name") String name,
// @JsonProperty("group") String group,
// @JsonProperty("parameters") Map<String, String> parameters) {
// this.actionInstanceId = actionInstanceId;
// this.name = name;
// this.group = group;
// this.parameters = parameters;
// }
//
// public void setActionInstanceId(String actionInstanceId) {
// this.actionInstanceId = actionInstanceId;
// }
//
// public String getActionInstanceId() {
// return actionInstanceId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getGroup() {
// return group;
// }
//
// public Map<String, String> getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// return String.format(
// "Context: (actionInstance: %s, name: %s, group: %s, parameters: %s)", actionInstanceId, name, group, parameters
// );
// }
// }
| import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.netflix.scheduledactions.Context;
import rx.functions.Action1; | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.triggers;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public interface Trigger {
public void validate() throws IllegalArgumentException; | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/Context.java
// public class Context {
// private String actionInstanceId;
// private final String name;
// private final String group;
// private final Map<String, String> parameters;
//
// @JsonCreator
// public Context(@JsonProperty("actionInstanceId") String actionInstanceId,
// @JsonProperty("name") String name,
// @JsonProperty("group") String group,
// @JsonProperty("parameters") Map<String, String> parameters) {
// this.actionInstanceId = actionInstanceId;
// this.name = name;
// this.group = group;
// this.parameters = parameters;
// }
//
// public void setActionInstanceId(String actionInstanceId) {
// this.actionInstanceId = actionInstanceId;
// }
//
// public String getActionInstanceId() {
// return actionInstanceId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getGroup() {
// return group;
// }
//
// public Map<String, String> getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// return String.format(
// "Context: (actionInstance: %s, name: %s, group: %s, parameters: %s)", actionInstanceId, name, group, parameters
// );
// }
// }
// Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/triggers/Trigger.java
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.netflix.scheduledactions.Context;
import rx.functions.Action1;
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.triggers;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public interface Trigger {
public void validate() throws IllegalArgumentException; | public com.netflix.fenzo.triggers.Trigger<Context> createFenzoTrigger(Context context, |
spinnaker/scheduled-actions | scheduled-actions-web/src/main/java/com/netflix/scheduledactions/web/controllers/ValidationController.java | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/triggers/CronExpressionFuzzer.java
// public class CronExpressionFuzzer {
//
// private static final String TOKEN = "H";
//
// public static String fuzz(String id, String expression) {
// if (!hasFuzzyExpression(expression)) {
// return expression;
// }
// return Tokens.tokenize(expression).toFuzzedExpression(id);
// }
//
// public static void validate(String expression) {
// TriggerUtils.validateCronExpression(fuzz("temp", expression));
// }
//
// public static boolean hasFuzzyExpression(String expression) {
// return expression.contains(TOKEN);
// }
//
// private static class Tokens {
// private String seconds;
// private String minutes;
// private String hours;
// private String dayOfMonth;
// private String month;
// private String dayOfWeek;
// private String year;
//
// private Tokens(String seconds,
// String minutes,
// String hours,
// String dayOfMonth,
// String month,
// String dayOfWeek,
// String year) {
// this.seconds = seconds;
// this.minutes = minutes;
// this.hours = hours;
// this.dayOfMonth = dayOfMonth;
// this.month = month;
// this.dayOfWeek = dayOfWeek;
// this.year = year;
// }
//
// static Tokens tokenize(String expression) {
// String[] t = expression.trim().split(" ");
// return new Tokens(t[0], t[1], t[2], t[3], t[4], t[5], (t.length == 7) ? t[6] : null);
// }
//
// String toFuzzedExpression(String id) {
// if (seconds.contains(TOKEN)) {
// seconds = seconds.replace(TOKEN, hash(id, 59));
// }
// if (minutes.contains(TOKEN)) {
// minutes = minutes.replace(TOKEN, hash(id, 59));
// }
// if (hours.contains(TOKEN)) {
// hours = hours.replace(TOKEN, hash(id, 23));
// }
//
// return (year == null)
// ? format("%s %s %s %s %s %s", seconds, minutes, hours, dayOfMonth, month, dayOfWeek)
// : format("%s %s %s %s %s %s %s", seconds, minutes, hours, dayOfMonth, month, dayOfWeek, year);
// }
//
// private String hash(String id, Integer maxRange) {
// return Integer.toString(Math.abs(id.hashCode() % maxRange));
// }
// }
// }
| import com.google.common.collect.ImmutableMap;
import com.netflix.fenzo.triggers.TriggerUtils;
import com.netflix.scheduledactions.triggers.CronExpressionFuzzer;
import net.redhogs.cronparser.CronExpressionDescriptor;
import net.redhogs.cronparser.Options;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Map; | /*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.web.controllers;
@RestController
public class ValidationController {
@RequestMapping(value = "/validateCronExpression", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
public Map<String,Object> validateCronExpression(@RequestParam String cronExpression) {
ImmutableMap.Builder<String,Object> mapBuilder = ImmutableMap.builder();
try { | // Path: scheduled-actions-core/src/main/java/com/netflix/scheduledactions/triggers/CronExpressionFuzzer.java
// public class CronExpressionFuzzer {
//
// private static final String TOKEN = "H";
//
// public static String fuzz(String id, String expression) {
// if (!hasFuzzyExpression(expression)) {
// return expression;
// }
// return Tokens.tokenize(expression).toFuzzedExpression(id);
// }
//
// public static void validate(String expression) {
// TriggerUtils.validateCronExpression(fuzz("temp", expression));
// }
//
// public static boolean hasFuzzyExpression(String expression) {
// return expression.contains(TOKEN);
// }
//
// private static class Tokens {
// private String seconds;
// private String minutes;
// private String hours;
// private String dayOfMonth;
// private String month;
// private String dayOfWeek;
// private String year;
//
// private Tokens(String seconds,
// String minutes,
// String hours,
// String dayOfMonth,
// String month,
// String dayOfWeek,
// String year) {
// this.seconds = seconds;
// this.minutes = minutes;
// this.hours = hours;
// this.dayOfMonth = dayOfMonth;
// this.month = month;
// this.dayOfWeek = dayOfWeek;
// this.year = year;
// }
//
// static Tokens tokenize(String expression) {
// String[] t = expression.trim().split(" ");
// return new Tokens(t[0], t[1], t[2], t[3], t[4], t[5], (t.length == 7) ? t[6] : null);
// }
//
// String toFuzzedExpression(String id) {
// if (seconds.contains(TOKEN)) {
// seconds = seconds.replace(TOKEN, hash(id, 59));
// }
// if (minutes.contains(TOKEN)) {
// minutes = minutes.replace(TOKEN, hash(id, 59));
// }
// if (hours.contains(TOKEN)) {
// hours = hours.replace(TOKEN, hash(id, 23));
// }
//
// return (year == null)
// ? format("%s %s %s %s %s %s", seconds, minutes, hours, dayOfMonth, month, dayOfWeek)
// : format("%s %s %s %s %s %s %s", seconds, minutes, hours, dayOfMonth, month, dayOfWeek, year);
// }
//
// private String hash(String id, Integer maxRange) {
// return Integer.toString(Math.abs(id.hashCode() % maxRange));
// }
// }
// }
// Path: scheduled-actions-web/src/main/java/com/netflix/scheduledactions/web/controllers/ValidationController.java
import com.google.common.collect.ImmutableMap;
import com.netflix.fenzo.triggers.TriggerUtils;
import com.netflix.scheduledactions.triggers.CronExpressionFuzzer;
import net.redhogs.cronparser.CronExpressionDescriptor;
import net.redhogs.cronparser.Options;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Map;
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.scheduledactions.web.controllers;
@RestController
public class ValidationController {
@RequestMapping(value = "/validateCronExpression", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
public Map<String,Object> validateCronExpression(@RequestParam String cronExpression) {
ImmutableMap.Builder<String,Object> mapBuilder = ImmutableMap.builder();
try { | CronExpressionFuzzer.validate(cronExpression); |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-client/src/test/java/com/orange/ngsi2/client/Ngsi2ClientTest.java | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/Ngsi2Exception.java
// public class Ngsi2Exception extends RuntimeException {
//
// private Error error = new Error();
//
// /**
// * Return specialized exception based on the HTTP status code and error
// * @param statusCode the response code
// * @param error the error
// * @return the corresponding Ngsi2Exception
// */
// public static Ngsi2Exception fromError(int statusCode, Error error) {
// switch (statusCode) {
// case 409: return new ConflictingEntitiesException(error);
// case 400: return new InvalidatedSyntaxException(error);
// default: return new Ngsi2Exception(error);
// }
// }
//
// public Ngsi2Exception(Error error) {
// this(error.getError(), error.getDescription().orElse(""), error.getAffectedItems().orElse(Collections.emptyList()));
// }
//
// public Ngsi2Exception(String error, String description, Collection<String> affectedItems) {
// this.error.setError(error);
// if (description != null) {
// this.error.setDescription(Optional.of(description));
// } else {
// this.error.setDescription(Optional.empty());
// }
// if (affectedItems != null) {
// this.error.setAffectedItems(Optional.of(affectedItems));
// } else {
// this.error.setAffectedItems(Optional.empty());
// }
// }
//
// public Error getError() {
// return error;
// }
//
// public String getMessage() {
// return error.toString();
// }
// }
| import java.net.URL;
import java.time.Instant;
import java.util.*;
import static org.junit.Assert.*;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;
import com.orange.ngsi2.Utils;
import com.orange.ngsi2.exception.Ngsi2Exception;
import com.orange.ngsi2.model.*;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.AsyncRestTemplate; | /*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.client;
/**
* Tests for Ngsi2Client
*/
public class Ngsi2ClientTest {
private final static String baseURL = "http://localhost:8080";
private MockRestServiceServer mockServer;
private Ngsi2Client ngsiClient;
@Rule
public ExpectedException thrown = ExpectedException.none();
public Ngsi2ClientTest() {
AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
//asyncRestTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter(Utils.objectMapper)));
ngsiClient = new Ngsi2Client(asyncRestTemplate, baseURL);
mockServer = MockRestServiceServer.createServer(asyncRestTemplate);
}
@Test
public void testGetV2_ServerError() throws Exception { | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/Ngsi2Exception.java
// public class Ngsi2Exception extends RuntimeException {
//
// private Error error = new Error();
//
// /**
// * Return specialized exception based on the HTTP status code and error
// * @param statusCode the response code
// * @param error the error
// * @return the corresponding Ngsi2Exception
// */
// public static Ngsi2Exception fromError(int statusCode, Error error) {
// switch (statusCode) {
// case 409: return new ConflictingEntitiesException(error);
// case 400: return new InvalidatedSyntaxException(error);
// default: return new Ngsi2Exception(error);
// }
// }
//
// public Ngsi2Exception(Error error) {
// this(error.getError(), error.getDescription().orElse(""), error.getAffectedItems().orElse(Collections.emptyList()));
// }
//
// public Ngsi2Exception(String error, String description, Collection<String> affectedItems) {
// this.error.setError(error);
// if (description != null) {
// this.error.setDescription(Optional.of(description));
// } else {
// this.error.setDescription(Optional.empty());
// }
// if (affectedItems != null) {
// this.error.setAffectedItems(Optional.of(affectedItems));
// } else {
// this.error.setAffectedItems(Optional.empty());
// }
// }
//
// public Error getError() {
// return error;
// }
//
// public String getMessage() {
// return error.toString();
// }
// }
// Path: ngsi2-client/src/test/java/com/orange/ngsi2/client/Ngsi2ClientTest.java
import java.net.URL;
import java.time.Instant;
import java.util.*;
import static org.junit.Assert.*;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;
import com.orange.ngsi2.Utils;
import com.orange.ngsi2.exception.Ngsi2Exception;
import com.orange.ngsi2.model.*;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.AsyncRestTemplate;
/*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.client;
/**
* Tests for Ngsi2Client
*/
public class Ngsi2ClientTest {
private final static String baseURL = "http://localhost:8080";
private MockRestServiceServer mockServer;
private Ngsi2Client ngsiClient;
@Rule
public ExpectedException thrown = ExpectedException.none();
public Ngsi2ClientTest() {
AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
//asyncRestTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter(Utils.objectMapper)));
ngsiClient = new Ngsi2Client(asyncRestTemplate, baseURL);
mockServer = MockRestServiceServer.createServer(asyncRestTemplate);
}
@Test
public void testGetV2_ServerError() throws Exception { | thrown.expect(Ngsi2Exception.class); |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-client/src/test/java/com/orange/ngsi2/client/Ngsi2ClientTest.java | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/Ngsi2Exception.java
// public class Ngsi2Exception extends RuntimeException {
//
// private Error error = new Error();
//
// /**
// * Return specialized exception based on the HTTP status code and error
// * @param statusCode the response code
// * @param error the error
// * @return the corresponding Ngsi2Exception
// */
// public static Ngsi2Exception fromError(int statusCode, Error error) {
// switch (statusCode) {
// case 409: return new ConflictingEntitiesException(error);
// case 400: return new InvalidatedSyntaxException(error);
// default: return new Ngsi2Exception(error);
// }
// }
//
// public Ngsi2Exception(Error error) {
// this(error.getError(), error.getDescription().orElse(""), error.getAffectedItems().orElse(Collections.emptyList()));
// }
//
// public Ngsi2Exception(String error, String description, Collection<String> affectedItems) {
// this.error.setError(error);
// if (description != null) {
// this.error.setDescription(Optional.of(description));
// } else {
// this.error.setDescription(Optional.empty());
// }
// if (affectedItems != null) {
// this.error.setAffectedItems(Optional.of(affectedItems));
// } else {
// this.error.setAffectedItems(Optional.empty());
// }
// }
//
// public Error getError() {
// return error;
// }
//
// public String getMessage() {
// return error.toString();
// }
// }
| import java.net.URL;
import java.time.Instant;
import java.util.*;
import static org.junit.Assert.*;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;
import com.orange.ngsi2.Utils;
import com.orange.ngsi2.exception.Ngsi2Exception;
import com.orange.ngsi2.model.*;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.AsyncRestTemplate; | /*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.client;
/**
* Tests for Ngsi2Client
*/
public class Ngsi2ClientTest {
private final static String baseURL = "http://localhost:8080";
private MockRestServiceServer mockServer;
private Ngsi2Client ngsiClient;
@Rule
public ExpectedException thrown = ExpectedException.none();
public Ngsi2ClientTest() {
AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
//asyncRestTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter(Utils.objectMapper)));
ngsiClient = new Ngsi2Client(asyncRestTemplate, baseURL);
mockServer = MockRestServiceServer.createServer(asyncRestTemplate);
}
@Test
public void testGetV2_ServerError() throws Exception {
thrown.expect(Ngsi2Exception.class);
thrown.expectMessage("error: 500 | description: Internal Server Error | affectedItems: [item1, item2, item3]");
mockServer.expect(requestTo(baseURL + "/v2"))
.andExpect(method(HttpMethod.GET)) | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/Ngsi2Exception.java
// public class Ngsi2Exception extends RuntimeException {
//
// private Error error = new Error();
//
// /**
// * Return specialized exception based on the HTTP status code and error
// * @param statusCode the response code
// * @param error the error
// * @return the corresponding Ngsi2Exception
// */
// public static Ngsi2Exception fromError(int statusCode, Error error) {
// switch (statusCode) {
// case 409: return new ConflictingEntitiesException(error);
// case 400: return new InvalidatedSyntaxException(error);
// default: return new Ngsi2Exception(error);
// }
// }
//
// public Ngsi2Exception(Error error) {
// this(error.getError(), error.getDescription().orElse(""), error.getAffectedItems().orElse(Collections.emptyList()));
// }
//
// public Ngsi2Exception(String error, String description, Collection<String> affectedItems) {
// this.error.setError(error);
// if (description != null) {
// this.error.setDescription(Optional.of(description));
// } else {
// this.error.setDescription(Optional.empty());
// }
// if (affectedItems != null) {
// this.error.setAffectedItems(Optional.of(affectedItems));
// } else {
// this.error.setAffectedItems(Optional.empty());
// }
// }
//
// public Error getError() {
// return error;
// }
//
// public String getMessage() {
// return error.toString();
// }
// }
// Path: ngsi2-client/src/test/java/com/orange/ngsi2/client/Ngsi2ClientTest.java
import java.net.URL;
import java.time.Instant;
import java.util.*;
import static org.junit.Assert.*;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;
import com.orange.ngsi2.Utils;
import com.orange.ngsi2.exception.Ngsi2Exception;
import com.orange.ngsi2.model.*;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.AsyncRestTemplate;
/*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.client;
/**
* Tests for Ngsi2Client
*/
public class Ngsi2ClientTest {
private final static String baseURL = "http://localhost:8080";
private MockRestServiceServer mockServer;
private Ngsi2Client ngsiClient;
@Rule
public ExpectedException thrown = ExpectedException.none();
public Ngsi2ClientTest() {
AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
//asyncRestTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter(Utils.objectMapper)));
ngsiClient = new Ngsi2Client(asyncRestTemplate, baseURL);
mockServer = MockRestServiceServer.createServer(asyncRestTemplate);
}
@Test
public void testGetV2_ServerError() throws Exception {
thrown.expect(Ngsi2Exception.class);
thrown.expectMessage("error: 500 | description: Internal Server Error | affectedItems: [item1, item2, item3]");
mockServer.expect(requestTo(baseURL + "/v2"))
.andExpect(method(HttpMethod.GET)) | .andRespond(withServerError().body(Utils.loadResource("json/error500Response.json"))); |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-client/src/test/java/com/orange/ngsi2/model/RegistrationTest.java | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.orange.ngsi2.Utils;
import org.junit.Test;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Optional; | /*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.model;
/**
* Tests for the Registration
*/
public class RegistrationTest {
String jsonString = "{\n" +
" \"id\": \"abcdefg\",\n" +
" \"subject\": {\n" +
" \"entities\": [\n" +
" {\n" +
" \"id\": \"Bcn_Welt\",\n" +
" \"type\": \"Room\"\n" +
" }\n" +
" ],\n" +
" \"attributes\": [\n" +
" \"temperature\"\n" +
" ]\n" +
" },\n" +
" \"callback\": \"http://weather.example.com/ngsi\",\n" +
" \"metadata\": {\n" +
" \"providingService\": {\n" +
" \"value\": \"weather.example.com\",\n" +
" \"type\": \"none\"\n" +
" },\n" +
" \"providingAuthority\": {\n" +
" \"value\": \"AEMET - Spain\",\n" +
" \"type\": \"none\"\n" +
" }\n" +
" },\n" +
" \"duration\": \"PT1M\"\n" +
" }";
@Test
public void serializationRegistrationTest() throws JsonProcessingException, MalformedURLException { | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
// Path: ngsi2-client/src/test/java/com/orange/ngsi2/model/RegistrationTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.orange.ngsi2.Utils;
import org.junit.Test;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Optional;
/*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.model;
/**
* Tests for the Registration
*/
public class RegistrationTest {
String jsonString = "{\n" +
" \"id\": \"abcdefg\",\n" +
" \"subject\": {\n" +
" \"entities\": [\n" +
" {\n" +
" \"id\": \"Bcn_Welt\",\n" +
" \"type\": \"Room\"\n" +
" }\n" +
" ],\n" +
" \"attributes\": [\n" +
" \"temperature\"\n" +
" ]\n" +
" },\n" +
" \"callback\": \"http://weather.example.com/ngsi\",\n" +
" \"metadata\": {\n" +
" \"providingService\": {\n" +
" \"value\": \"weather.example.com\",\n" +
" \"type\": \"none\"\n" +
" },\n" +
" \"providingAuthority\": {\n" +
" \"value\": \"AEMET - Spain\",\n" +
" \"type\": \"none\"\n" +
" }\n" +
" },\n" +
" \"duration\": \"PT1M\"\n" +
" }";
@Test
public void serializationRegistrationTest() throws JsonProcessingException, MalformedURLException { | ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter()); |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-client/src/test/java/com/orange/ngsi2/model/AttributeTest.java | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.orange.ngsi2.Utils;
import org.junit.Test;
import java.util.HashMap;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | /*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.model;
/**
* Tests for the Attribute
*/
public class AttributeTest {
@Test
public void serializationAttributeWithNullMetadataTest() throws JsonProcessingException {
Attribute attribute = new Attribute(23.5);
attribute.setType(Optional.of("float")); | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
// Path: ngsi2-client/src/test/java/com/orange/ngsi2/model/AttributeTest.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.orange.ngsi2.Utils;
import org.junit.Test;
import java.util.HashMap;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.model;
/**
* Tests for the Attribute
*/
public class AttributeTest {
@Test
public void serializationAttributeWithNullMetadataTest() throws JsonProcessingException {
Attribute attribute = new Attribute(23.5);
attribute.setType(Optional.of("float")); | String json = Utils.objectMapper.writeValueAsString(attribute); |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Error.java
// public class Error {
//
// private String error;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<String> description;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<Collection<String>> affectedItems;
//
// public Error() {
// }
//
// public Error(String error) {
// this.error = error;
// }
//
// public Error(String error, Optional<String> description, Optional<Collection<String>> affectedItems) {
// this.error = error;
// this.description = description;
// this.affectedItems = affectedItems;
// }
//
// public String getError() {
// return error;
// }
//
// public void setError(String error) {
// this.error = error;
// }
//
// public Optional<String> getDescription() {
// return description;
// }
//
// public void setDescription(Optional<String> description) {
// this.description = description;
// }
//
// public Optional<Collection<String>> getAffectedItems() {
// return affectedItems;
// }
//
// public void setAffectedItems(Optional<Collection<String>> affectedItems) {
// this.affectedItems = affectedItems;
// }
//
// @Override
// public String toString() {
// return String.format("error: %s | description: %s | affectedItems: %s", error, description.orElse(""), affectedItems.orElse(Collections.emptyList()));
// }
// }
| import com.orange.ngsi2.model.Error; | /*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.exception;
/**
* 400 Invalid syntax
*/
public class InvalidatedSyntaxException extends Ngsi2Exception {
private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
| // Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Error.java
// public class Error {
//
// private String error;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<String> description;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<Collection<String>> affectedItems;
//
// public Error() {
// }
//
// public Error(String error) {
// this.error = error;
// }
//
// public Error(String error, Optional<String> description, Optional<Collection<String>> affectedItems) {
// this.error = error;
// this.description = description;
// this.affectedItems = affectedItems;
// }
//
// public String getError() {
// return error;
// }
//
// public void setError(String error) {
// this.error = error;
// }
//
// public Optional<String> getDescription() {
// return description;
// }
//
// public void setDescription(Optional<String> description) {
// this.description = description;
// }
//
// public Optional<Collection<String>> getAffectedItems() {
// return affectedItems;
// }
//
// public void setAffectedItems(Optional<Collection<String>> affectedItems) {
// this.affectedItems = affectedItems;
// }
//
// @Override
// public String toString() {
// return String.format("error: %s | description: %s | affectedItems: %s", error, description.orElse(""), affectedItems.orElse(Collections.emptyList()));
// }
// }
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
import com.orange.ngsi2.model.Error;
/*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.exception;
/**
* 400 Invalid syntax
*/
public class InvalidatedSyntaxException extends Ngsi2Exception {
private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
| public InvalidatedSyntaxException(Error error) { |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-client/src/main/java/com/orange/ngsi2/client/Ngsi2ResponseErrorHandler.java | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/Ngsi2Exception.java
// public class Ngsi2Exception extends RuntimeException {
//
// private Error error = new Error();
//
// /**
// * Return specialized exception based on the HTTP status code and error
// * @param statusCode the response code
// * @param error the error
// * @return the corresponding Ngsi2Exception
// */
// public static Ngsi2Exception fromError(int statusCode, Error error) {
// switch (statusCode) {
// case 409: return new ConflictingEntitiesException(error);
// case 400: return new InvalidatedSyntaxException(error);
// default: return new Ngsi2Exception(error);
// }
// }
//
// public Ngsi2Exception(Error error) {
// this(error.getError(), error.getDescription().orElse(""), error.getAffectedItems().orElse(Collections.emptyList()));
// }
//
// public Ngsi2Exception(String error, String description, Collection<String> affectedItems) {
// this.error.setError(error);
// if (description != null) {
// this.error.setDescription(Optional.of(description));
// } else {
// this.error.setDescription(Optional.empty());
// }
// if (affectedItems != null) {
// this.error.setAffectedItems(Optional.of(affectedItems));
// } else {
// this.error.setAffectedItems(Optional.empty());
// }
// }
//
// public Error getError() {
// return error;
// }
//
// public String getMessage() {
// return error.toString();
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Error.java
// public class Error {
//
// private String error;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<String> description;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<Collection<String>> affectedItems;
//
// public Error() {
// }
//
// public Error(String error) {
// this.error = error;
// }
//
// public Error(String error, Optional<String> description, Optional<Collection<String>> affectedItems) {
// this.error = error;
// this.description = description;
// this.affectedItems = affectedItems;
// }
//
// public String getError() {
// return error;
// }
//
// public void setError(String error) {
// this.error = error;
// }
//
// public Optional<String> getDescription() {
// return description;
// }
//
// public void setDescription(Optional<String> description) {
// this.description = description;
// }
//
// public Optional<Collection<String>> getAffectedItems() {
// return affectedItems;
// }
//
// public void setAffectedItems(Optional<Collection<String>> affectedItems) {
// this.affectedItems = affectedItems;
// }
//
// @Override
// public String toString() {
// return String.format("error: %s | description: %s | affectedItems: %s", error, description.orElse(""), affectedItems.orElse(Collections.emptyList()));
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.ngsi2.exception.Ngsi2Exception;
import com.orange.ngsi2.model.Error;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;
import java.io.IOException; | package com.orange.ngsi2.client;
/**
* Error responses should contain an Error json structure.
* Handle all errors by throwing an Ngsi2Exception containing the error.
*/
class Ngsi2ResponseErrorHandler implements ResponseErrorHandler {
private ObjectMapper objectMapper;
Ngsi2ResponseErrorHandler(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode().is4xxClientError() || response.getStatusCode().is5xxServerError();
}
@Override
public void handleError(ClientHttpResponse response) throws IOException { | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/Ngsi2Exception.java
// public class Ngsi2Exception extends RuntimeException {
//
// private Error error = new Error();
//
// /**
// * Return specialized exception based on the HTTP status code and error
// * @param statusCode the response code
// * @param error the error
// * @return the corresponding Ngsi2Exception
// */
// public static Ngsi2Exception fromError(int statusCode, Error error) {
// switch (statusCode) {
// case 409: return new ConflictingEntitiesException(error);
// case 400: return new InvalidatedSyntaxException(error);
// default: return new Ngsi2Exception(error);
// }
// }
//
// public Ngsi2Exception(Error error) {
// this(error.getError(), error.getDescription().orElse(""), error.getAffectedItems().orElse(Collections.emptyList()));
// }
//
// public Ngsi2Exception(String error, String description, Collection<String> affectedItems) {
// this.error.setError(error);
// if (description != null) {
// this.error.setDescription(Optional.of(description));
// } else {
// this.error.setDescription(Optional.empty());
// }
// if (affectedItems != null) {
// this.error.setAffectedItems(Optional.of(affectedItems));
// } else {
// this.error.setAffectedItems(Optional.empty());
// }
// }
//
// public Error getError() {
// return error;
// }
//
// public String getMessage() {
// return error.toString();
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Error.java
// public class Error {
//
// private String error;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<String> description;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<Collection<String>> affectedItems;
//
// public Error() {
// }
//
// public Error(String error) {
// this.error = error;
// }
//
// public Error(String error, Optional<String> description, Optional<Collection<String>> affectedItems) {
// this.error = error;
// this.description = description;
// this.affectedItems = affectedItems;
// }
//
// public String getError() {
// return error;
// }
//
// public void setError(String error) {
// this.error = error;
// }
//
// public Optional<String> getDescription() {
// return description;
// }
//
// public void setDescription(Optional<String> description) {
// this.description = description;
// }
//
// public Optional<Collection<String>> getAffectedItems() {
// return affectedItems;
// }
//
// public void setAffectedItems(Optional<Collection<String>> affectedItems) {
// this.affectedItems = affectedItems;
// }
//
// @Override
// public String toString() {
// return String.format("error: %s | description: %s | affectedItems: %s", error, description.orElse(""), affectedItems.orElse(Collections.emptyList()));
// }
// }
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/client/Ngsi2ResponseErrorHandler.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.ngsi2.exception.Ngsi2Exception;
import com.orange.ngsi2.model.Error;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;
import java.io.IOException;
package com.orange.ngsi2.client;
/**
* Error responses should contain an Error json structure.
* Handle all errors by throwing an Ngsi2Exception containing the error.
*/
class Ngsi2ResponseErrorHandler implements ResponseErrorHandler {
private ObjectMapper objectMapper;
Ngsi2ResponseErrorHandler(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode().is4xxClientError() || response.getStatusCode().is5xxServerError();
}
@Override
public void handleError(ClientHttpResponse response) throws IOException { | Ngsi2Exception ex; |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-client/src/main/java/com/orange/ngsi2/client/Ngsi2ResponseErrorHandler.java | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/Ngsi2Exception.java
// public class Ngsi2Exception extends RuntimeException {
//
// private Error error = new Error();
//
// /**
// * Return specialized exception based on the HTTP status code and error
// * @param statusCode the response code
// * @param error the error
// * @return the corresponding Ngsi2Exception
// */
// public static Ngsi2Exception fromError(int statusCode, Error error) {
// switch (statusCode) {
// case 409: return new ConflictingEntitiesException(error);
// case 400: return new InvalidatedSyntaxException(error);
// default: return new Ngsi2Exception(error);
// }
// }
//
// public Ngsi2Exception(Error error) {
// this(error.getError(), error.getDescription().orElse(""), error.getAffectedItems().orElse(Collections.emptyList()));
// }
//
// public Ngsi2Exception(String error, String description, Collection<String> affectedItems) {
// this.error.setError(error);
// if (description != null) {
// this.error.setDescription(Optional.of(description));
// } else {
// this.error.setDescription(Optional.empty());
// }
// if (affectedItems != null) {
// this.error.setAffectedItems(Optional.of(affectedItems));
// } else {
// this.error.setAffectedItems(Optional.empty());
// }
// }
//
// public Error getError() {
// return error;
// }
//
// public String getMessage() {
// return error.toString();
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Error.java
// public class Error {
//
// private String error;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<String> description;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<Collection<String>> affectedItems;
//
// public Error() {
// }
//
// public Error(String error) {
// this.error = error;
// }
//
// public Error(String error, Optional<String> description, Optional<Collection<String>> affectedItems) {
// this.error = error;
// this.description = description;
// this.affectedItems = affectedItems;
// }
//
// public String getError() {
// return error;
// }
//
// public void setError(String error) {
// this.error = error;
// }
//
// public Optional<String> getDescription() {
// return description;
// }
//
// public void setDescription(Optional<String> description) {
// this.description = description;
// }
//
// public Optional<Collection<String>> getAffectedItems() {
// return affectedItems;
// }
//
// public void setAffectedItems(Optional<Collection<String>> affectedItems) {
// this.affectedItems = affectedItems;
// }
//
// @Override
// public String toString() {
// return String.format("error: %s | description: %s | affectedItems: %s", error, description.orElse(""), affectedItems.orElse(Collections.emptyList()));
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.ngsi2.exception.Ngsi2Exception;
import com.orange.ngsi2.model.Error;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;
import java.io.IOException; | package com.orange.ngsi2.client;
/**
* Error responses should contain an Error json structure.
* Handle all errors by throwing an Ngsi2Exception containing the error.
*/
class Ngsi2ResponseErrorHandler implements ResponseErrorHandler {
private ObjectMapper objectMapper;
Ngsi2ResponseErrorHandler(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode().is4xxClientError() || response.getStatusCode().is5xxServerError();
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
Ngsi2Exception ex;
try { | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/Ngsi2Exception.java
// public class Ngsi2Exception extends RuntimeException {
//
// private Error error = new Error();
//
// /**
// * Return specialized exception based on the HTTP status code and error
// * @param statusCode the response code
// * @param error the error
// * @return the corresponding Ngsi2Exception
// */
// public static Ngsi2Exception fromError(int statusCode, Error error) {
// switch (statusCode) {
// case 409: return new ConflictingEntitiesException(error);
// case 400: return new InvalidatedSyntaxException(error);
// default: return new Ngsi2Exception(error);
// }
// }
//
// public Ngsi2Exception(Error error) {
// this(error.getError(), error.getDescription().orElse(""), error.getAffectedItems().orElse(Collections.emptyList()));
// }
//
// public Ngsi2Exception(String error, String description, Collection<String> affectedItems) {
// this.error.setError(error);
// if (description != null) {
// this.error.setDescription(Optional.of(description));
// } else {
// this.error.setDescription(Optional.empty());
// }
// if (affectedItems != null) {
// this.error.setAffectedItems(Optional.of(affectedItems));
// } else {
// this.error.setAffectedItems(Optional.empty());
// }
// }
//
// public Error getError() {
// return error;
// }
//
// public String getMessage() {
// return error.toString();
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Error.java
// public class Error {
//
// private String error;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<String> description;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<Collection<String>> affectedItems;
//
// public Error() {
// }
//
// public Error(String error) {
// this.error = error;
// }
//
// public Error(String error, Optional<String> description, Optional<Collection<String>> affectedItems) {
// this.error = error;
// this.description = description;
// this.affectedItems = affectedItems;
// }
//
// public String getError() {
// return error;
// }
//
// public void setError(String error) {
// this.error = error;
// }
//
// public Optional<String> getDescription() {
// return description;
// }
//
// public void setDescription(Optional<String> description) {
// this.description = description;
// }
//
// public Optional<Collection<String>> getAffectedItems() {
// return affectedItems;
// }
//
// public void setAffectedItems(Optional<Collection<String>> affectedItems) {
// this.affectedItems = affectedItems;
// }
//
// @Override
// public String toString() {
// return String.format("error: %s | description: %s | affectedItems: %s", error, description.orElse(""), affectedItems.orElse(Collections.emptyList()));
// }
// }
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/client/Ngsi2ResponseErrorHandler.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.ngsi2.exception.Ngsi2Exception;
import com.orange.ngsi2.model.Error;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;
import java.io.IOException;
package com.orange.ngsi2.client;
/**
* Error responses should contain an Error json structure.
* Handle all errors by throwing an Ngsi2Exception containing the error.
*/
class Ngsi2ResponseErrorHandler implements ResponseErrorHandler {
private ObjectMapper objectMapper;
Ngsi2ResponseErrorHandler(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode().is4xxClientError() || response.getStatusCode().is5xxServerError();
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
Ngsi2Exception ex;
try { | ex = Ngsi2Exception.fromError(response.getStatusCode().value(), objectMapper.readValue(response.getBody(), Error.class)); |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-server/src/test/java/com/orange/ngsi2/server/Ngsi2ParsingHelperTest.java | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
| import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.model.GeoQuery;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.*; | /*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.server;
/**
* Test class for Ngsi2ParsingHelper
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
@WebAppConfiguration
public class Ngsi2ParsingHelperTest {
@Test
public void testParseTextValue() {
assertEquals("hello world", Ngsi2ParsingHelper.parseTextValue("\"hello world\""));
assertEquals(true, Ngsi2ParsingHelper.parseTextValue("true"));
assertEquals(false, Ngsi2ParsingHelper.parseTextValue("false"));
assertEquals(null, Ngsi2ParsingHelper.parseTextValue("null"));
assertEquals(1, Ngsi2ParsingHelper.parseTextValue("1"));
assertEquals(1.2f, Ngsi2ParsingHelper.parseTextValue("1.2"));
}
@Test
public void testParseGeoQuery() { | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
// Path: ngsi2-server/src/test/java/com/orange/ngsi2/server/Ngsi2ParsingHelperTest.java
import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.model.GeoQuery;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.*;
/*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.server;
/**
* Test class for Ngsi2ParsingHelper
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
@WebAppConfiguration
public class Ngsi2ParsingHelperTest {
@Test
public void testParseTextValue() {
assertEquals("hello world", Ngsi2ParsingHelper.parseTextValue("\"hello world\""));
assertEquals(true, Ngsi2ParsingHelper.parseTextValue("true"));
assertEquals(false, Ngsi2ParsingHelper.parseTextValue("false"));
assertEquals(null, Ngsi2ParsingHelper.parseTextValue("null"));
assertEquals(1, Ngsi2ParsingHelper.parseTextValue("1"));
assertEquals(1.2f, Ngsi2ParsingHelper.parseTextValue("1.2"));
}
@Test
public void testParseGeoQuery() { | GeoQuery geoQuery = Ngsi2ParsingHelper.parseGeoQuery("near;minDistance:23.3", "point", "12.3,14.2"); |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-server/src/test/java/com/orange/ngsi2/server/Ngsi2ParsingHelperTest.java | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
| import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.model.GeoQuery;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.*; | assertEquals(1, Ngsi2ParsingHelper.parseTextValue("1"));
assertEquals(1.2f, Ngsi2ParsingHelper.parseTextValue("1.2"));
}
@Test
public void testParseGeoQuery() {
GeoQuery geoQuery = Ngsi2ParsingHelper.parseGeoQuery("near;minDistance:23.3", "point", "12.3,14.2");
assertEquals(GeoQuery.Relation.near, geoQuery.getRelation());
assertEquals(GeoQuery.Modifier.minDistance, geoQuery.getModifier());
assertEquals(23.3, geoQuery.getDistance(), 0.1);
assertEquals(GeoQuery.Geometry.point, geoQuery.getGeometry());
assertEquals(1, geoQuery.getCoordinates().size());
assertEquals(12.3, geoQuery.getCoordinates().get(0).getLatitude(), 0.1);
assertEquals(14.2, geoQuery.getCoordinates().get(0).getLongitude(), 0.1);
}
@Test
public void testParseGeometryRelations() {
assertEquals(GeoQuery.Relation.disjoint, Ngsi2ParsingHelper.parseGeoQuery("disjoint", "point", "12.3,14.2").getRelation());
assertEquals(GeoQuery.Relation.coveredBy, Ngsi2ParsingHelper.parseGeoQuery("coveredBy", "point", "12.3,14.2").getRelation());
assertEquals(GeoQuery.Relation.intersects, Ngsi2ParsingHelper.parseGeoQuery("intersects", "point", "12.3,14.2").getRelation());
assertEquals(GeoQuery.Relation.equals, Ngsi2ParsingHelper.parseGeoQuery("equals", "point", "12.3,14.2").getRelation());
}
@Test
public void testParseGeometryModifiers() {
assertEquals(GeoQuery.Modifier.maxDistance, Ngsi2ParsingHelper.parseGeoQuery("near;maxDistance:23.3", "point", "12.3,14.2").getModifier());
assertEquals(GeoQuery.Modifier.minDistance, Ngsi2ParsingHelper.parseGeoQuery("near;minDistance:23.3", "point", "12.3,14.2").getModifier());
}
| // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
// Path: ngsi2-server/src/test/java/com/orange/ngsi2/server/Ngsi2ParsingHelperTest.java
import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.model.GeoQuery;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.*;
assertEquals(1, Ngsi2ParsingHelper.parseTextValue("1"));
assertEquals(1.2f, Ngsi2ParsingHelper.parseTextValue("1.2"));
}
@Test
public void testParseGeoQuery() {
GeoQuery geoQuery = Ngsi2ParsingHelper.parseGeoQuery("near;minDistance:23.3", "point", "12.3,14.2");
assertEquals(GeoQuery.Relation.near, geoQuery.getRelation());
assertEquals(GeoQuery.Modifier.minDistance, geoQuery.getModifier());
assertEquals(23.3, geoQuery.getDistance(), 0.1);
assertEquals(GeoQuery.Geometry.point, geoQuery.getGeometry());
assertEquals(1, geoQuery.getCoordinates().size());
assertEquals(12.3, geoQuery.getCoordinates().get(0).getLatitude(), 0.1);
assertEquals(14.2, geoQuery.getCoordinates().get(0).getLongitude(), 0.1);
}
@Test
public void testParseGeometryRelations() {
assertEquals(GeoQuery.Relation.disjoint, Ngsi2ParsingHelper.parseGeoQuery("disjoint", "point", "12.3,14.2").getRelation());
assertEquals(GeoQuery.Relation.coveredBy, Ngsi2ParsingHelper.parseGeoQuery("coveredBy", "point", "12.3,14.2").getRelation());
assertEquals(GeoQuery.Relation.intersects, Ngsi2ParsingHelper.parseGeoQuery("intersects", "point", "12.3,14.2").getRelation());
assertEquals(GeoQuery.Relation.equals, Ngsi2ParsingHelper.parseGeoQuery("equals", "point", "12.3,14.2").getRelation());
}
@Test
public void testParseGeometryModifiers() {
assertEquals(GeoQuery.Modifier.maxDistance, Ngsi2ParsingHelper.parseGeoQuery("near;maxDistance:23.3", "point", "12.3,14.2").getModifier());
assertEquals(GeoQuery.Modifier.minDistance, Ngsi2ParsingHelper.parseGeoQuery("near;minDistance:23.3", "point", "12.3,14.2").getModifier());
}
| @Test(expected = InvalidatedSyntaxException.class) |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-server/src/main/java/com/orange/ngsi2/server/Ngsi2BaseController.java | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/UnsupportedOperationException.java
// public class UnsupportedOperationException extends Ngsi2Exception {
//
// private final static String message = "this operation '%s' is not implemented";
//
// public UnsupportedOperationException(String operationName) {
// super("501", String.format(message, operationName), null);
// }
// }
| import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.ngsi2.exception.*;
import com.orange.ngsi2.exception.UnsupportedOperationException;
import com.orange.ngsi2.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; | * @param bulkQueryRequest defines the list of entities, attributes and scopes to match registrations
* @param offset an optional offset (0 for none)
* @param limit an optional limit (0 for none)
* @param options an optional list of options separated by comma. Possible value for option: count.
* If count is present then the total number of registrations is returned in the response as a HTTP header named `X-Total-Count`.
* @return a paginated list of registration
*/
@RequestMapping(method = RequestMethod.POST, value = {"/op/discover"}, consumes = MediaType.APPLICATION_JSON_VALUE)
final public ResponseEntity<List<Registration>> bulkDiscoverEndpoint(@RequestBody BulkQueryRequest bulkQueryRequest, @RequestParam Optional<Integer> limit,
@RequestParam Optional<Integer> offset,
@RequestParam Optional<Set<String>> options) {
validateSyntax(bulkQueryRequest);
boolean count = false;
if (options.isPresent()) {
Set<String> optionsSet = options.get();
count = optionsSet.contains("count");
}
Paginated<Registration> paginatedRegistration = bulkDiscover(bulkQueryRequest, limit.orElse(0), offset.orElse(0), count);
if (count) {
return new ResponseEntity<>(paginatedRegistration.getItems(), xTotalCountHeader(paginatedRegistration.getTotal()), HttpStatus.OK);
} else {
return new ResponseEntity<>(paginatedRegistration.getItems(), HttpStatus.OK);
}
}
/*
* Exception handling
*/
| // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/UnsupportedOperationException.java
// public class UnsupportedOperationException extends Ngsi2Exception {
//
// private final static String message = "this operation '%s' is not implemented";
//
// public UnsupportedOperationException(String operationName) {
// super("501", String.format(message, operationName), null);
// }
// }
// Path: ngsi2-server/src/main/java/com/orange/ngsi2/server/Ngsi2BaseController.java
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.ngsi2.exception.*;
import com.orange.ngsi2.exception.UnsupportedOperationException;
import com.orange.ngsi2.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
* @param bulkQueryRequest defines the list of entities, attributes and scopes to match registrations
* @param offset an optional offset (0 for none)
* @param limit an optional limit (0 for none)
* @param options an optional list of options separated by comma. Possible value for option: count.
* If count is present then the total number of registrations is returned in the response as a HTTP header named `X-Total-Count`.
* @return a paginated list of registration
*/
@RequestMapping(method = RequestMethod.POST, value = {"/op/discover"}, consumes = MediaType.APPLICATION_JSON_VALUE)
final public ResponseEntity<List<Registration>> bulkDiscoverEndpoint(@RequestBody BulkQueryRequest bulkQueryRequest, @RequestParam Optional<Integer> limit,
@RequestParam Optional<Integer> offset,
@RequestParam Optional<Set<String>> options) {
validateSyntax(bulkQueryRequest);
boolean count = false;
if (options.isPresent()) {
Set<String> optionsSet = options.get();
count = optionsSet.contains("count");
}
Paginated<Registration> paginatedRegistration = bulkDiscover(bulkQueryRequest, limit.orElse(0), offset.orElse(0), count);
if (count) {
return new ResponseEntity<>(paginatedRegistration.getItems(), xTotalCountHeader(paginatedRegistration.getTotal()), HttpStatus.OK);
} else {
return new ResponseEntity<>(paginatedRegistration.getItems(), HttpStatus.OK);
}
}
/*
* Exception handling
*/
| @ExceptionHandler({UnsupportedOperationException.class}) |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-server/src/main/java/com/orange/ngsi2/server/Ngsi2ParsingHelper.java | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/NotAcceptableException.java
// public class NotAcceptableException extends Ngsi2Exception {
//
// private final static String message = "Not Acceptable: Accepted MIME types: text/plain.";
//
// public NotAcceptableException() {
// super("406", message, null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Coordinate.java
// public class Coordinate {
//
// double latitude;
//
// double longitude;
//
// public Coordinate(double latitude, double longitude) {
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public void setLatitude(double latitude) {
// this.latitude = latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public void setLongitude(double longitude) {
// this.longitude = longitude;
// }
//
// @Override
// public String toString() {
// return latitude + "," + longitude ;
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
| import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.exception.NotAcceptableException;
import com.orange.ngsi2.model.Coordinate;
import com.orange.ngsi2.model.GeoQuery;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.server;
/**
* Helper class to parse some NGSIv2 specific payload or parameters
*/
public class Ngsi2ParsingHelper {
/**
* Attempt to parse a text value as boolean, double quoted string, or number
* @param value the text value to parse
* @return the value
* @throws NotAcceptableException if text cannot be parsed
*/
public static Object parseTextValue(String value) {
if (value.equalsIgnoreCase("true")) {
return true;
} else if (value.equalsIgnoreCase("false")) {
return false;
} else if (value.equalsIgnoreCase("null")) {
return null;
} else if (value.startsWith("\"") && value.endsWith("\"") && value.length() > 1) {
return value.substring(1, value.length()-1);
}
// Attempt to parse as the simplest number format possible...
try {
return Integer.parseInt(value);
} catch (NumberFormatException ignored) {}
try {
return Long.parseLong(value);
} catch (NumberFormatException ignored) {}
try {
return Float.parseFloat(value);
} catch (NumberFormatException ignored) {}
try {
return Double.parseDouble(value);
} catch (NumberFormatException ignored) {} | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/NotAcceptableException.java
// public class NotAcceptableException extends Ngsi2Exception {
//
// private final static String message = "Not Acceptable: Accepted MIME types: text/plain.";
//
// public NotAcceptableException() {
// super("406", message, null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Coordinate.java
// public class Coordinate {
//
// double latitude;
//
// double longitude;
//
// public Coordinate(double latitude, double longitude) {
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public void setLatitude(double latitude) {
// this.latitude = latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public void setLongitude(double longitude) {
// this.longitude = longitude;
// }
//
// @Override
// public String toString() {
// return latitude + "," + longitude ;
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
// Path: ngsi2-server/src/main/java/com/orange/ngsi2/server/Ngsi2ParsingHelper.java
import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.exception.NotAcceptableException;
import com.orange.ngsi2.model.Coordinate;
import com.orange.ngsi2.model.GeoQuery;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.server;
/**
* Helper class to parse some NGSIv2 specific payload or parameters
*/
public class Ngsi2ParsingHelper {
/**
* Attempt to parse a text value as boolean, double quoted string, or number
* @param value the text value to parse
* @return the value
* @throws NotAcceptableException if text cannot be parsed
*/
public static Object parseTextValue(String value) {
if (value.equalsIgnoreCase("true")) {
return true;
} else if (value.equalsIgnoreCase("false")) {
return false;
} else if (value.equalsIgnoreCase("null")) {
return null;
} else if (value.startsWith("\"") && value.endsWith("\"") && value.length() > 1) {
return value.substring(1, value.length()-1);
}
// Attempt to parse as the simplest number format possible...
try {
return Integer.parseInt(value);
} catch (NumberFormatException ignored) {}
try {
return Long.parseLong(value);
} catch (NumberFormatException ignored) {}
try {
return Float.parseFloat(value);
} catch (NumberFormatException ignored) {}
try {
return Double.parseDouble(value);
} catch (NumberFormatException ignored) {} | throw new NotAcceptableException(); |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-server/src/main/java/com/orange/ngsi2/server/Ngsi2ParsingHelper.java | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/NotAcceptableException.java
// public class NotAcceptableException extends Ngsi2Exception {
//
// private final static String message = "Not Acceptable: Accepted MIME types: text/plain.";
//
// public NotAcceptableException() {
// super("406", message, null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Coordinate.java
// public class Coordinate {
//
// double latitude;
//
// double longitude;
//
// public Coordinate(double latitude, double longitude) {
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public void setLatitude(double latitude) {
// this.latitude = latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public void setLongitude(double longitude) {
// this.longitude = longitude;
// }
//
// @Override
// public String toString() {
// return latitude + "," + longitude ;
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
| import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.exception.NotAcceptableException;
import com.orange.ngsi2.model.Coordinate;
import com.orange.ngsi2.model.GeoQuery;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.server;
/**
* Helper class to parse some NGSIv2 specific payload or parameters
*/
public class Ngsi2ParsingHelper {
/**
* Attempt to parse a text value as boolean, double quoted string, or number
* @param value the text value to parse
* @return the value
* @throws NotAcceptableException if text cannot be parsed
*/
public static Object parseTextValue(String value) {
if (value.equalsIgnoreCase("true")) {
return true;
} else if (value.equalsIgnoreCase("false")) {
return false;
} else if (value.equalsIgnoreCase("null")) {
return null;
} else if (value.startsWith("\"") && value.endsWith("\"") && value.length() > 1) {
return value.substring(1, value.length()-1);
}
// Attempt to parse as the simplest number format possible...
try {
return Integer.parseInt(value);
} catch (NumberFormatException ignored) {}
try {
return Long.parseLong(value);
} catch (NumberFormatException ignored) {}
try {
return Float.parseFloat(value);
} catch (NumberFormatException ignored) {}
try {
return Double.parseDouble(value);
} catch (NumberFormatException ignored) {}
throw new NotAcceptableException();
}
/**
* Parse a GeoQuery request parameters
* @param georel the georel parameter
* @param geometry the geometry parameter
* @param coords the coords parameter
* @return a GeoQuery
* @throws InvalidatedSyntaxException on error
*/ | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/NotAcceptableException.java
// public class NotAcceptableException extends Ngsi2Exception {
//
// private final static String message = "Not Acceptable: Accepted MIME types: text/plain.";
//
// public NotAcceptableException() {
// super("406", message, null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Coordinate.java
// public class Coordinate {
//
// double latitude;
//
// double longitude;
//
// public Coordinate(double latitude, double longitude) {
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public void setLatitude(double latitude) {
// this.latitude = latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public void setLongitude(double longitude) {
// this.longitude = longitude;
// }
//
// @Override
// public String toString() {
// return latitude + "," + longitude ;
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
// Path: ngsi2-server/src/main/java/com/orange/ngsi2/server/Ngsi2ParsingHelper.java
import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.exception.NotAcceptableException;
import com.orange.ngsi2.model.Coordinate;
import com.orange.ngsi2.model.GeoQuery;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.server;
/**
* Helper class to parse some NGSIv2 specific payload or parameters
*/
public class Ngsi2ParsingHelper {
/**
* Attempt to parse a text value as boolean, double quoted string, or number
* @param value the text value to parse
* @return the value
* @throws NotAcceptableException if text cannot be parsed
*/
public static Object parseTextValue(String value) {
if (value.equalsIgnoreCase("true")) {
return true;
} else if (value.equalsIgnoreCase("false")) {
return false;
} else if (value.equalsIgnoreCase("null")) {
return null;
} else if (value.startsWith("\"") && value.endsWith("\"") && value.length() > 1) {
return value.substring(1, value.length()-1);
}
// Attempt to parse as the simplest number format possible...
try {
return Integer.parseInt(value);
} catch (NumberFormatException ignored) {}
try {
return Long.parseLong(value);
} catch (NumberFormatException ignored) {}
try {
return Float.parseFloat(value);
} catch (NumberFormatException ignored) {}
try {
return Double.parseDouble(value);
} catch (NumberFormatException ignored) {}
throw new NotAcceptableException();
}
/**
* Parse a GeoQuery request parameters
* @param georel the georel parameter
* @param geometry the geometry parameter
* @param coords the coords parameter
* @return a GeoQuery
* @throws InvalidatedSyntaxException on error
*/ | public static GeoQuery parseGeoQuery(String georel, String geometry, String coords) { |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-server/src/main/java/com/orange/ngsi2/server/Ngsi2ParsingHelper.java | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/NotAcceptableException.java
// public class NotAcceptableException extends Ngsi2Exception {
//
// private final static String message = "Not Acceptable: Accepted MIME types: text/plain.";
//
// public NotAcceptableException() {
// super("406", message, null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Coordinate.java
// public class Coordinate {
//
// double latitude;
//
// double longitude;
//
// public Coordinate(double latitude, double longitude) {
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public void setLatitude(double latitude) {
// this.latitude = latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public void setLongitude(double longitude) {
// this.longitude = longitude;
// }
//
// @Override
// public String toString() {
// return latitude + "," + longitude ;
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
| import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.exception.NotAcceptableException;
import com.orange.ngsi2.model.Coordinate;
import com.orange.ngsi2.model.GeoQuery;
import java.util.ArrayList;
import java.util.List; | // Attempt to parse as the simplest number format possible...
try {
return Integer.parseInt(value);
} catch (NumberFormatException ignored) {}
try {
return Long.parseLong(value);
} catch (NumberFormatException ignored) {}
try {
return Float.parseFloat(value);
} catch (NumberFormatException ignored) {}
try {
return Double.parseDouble(value);
} catch (NumberFormatException ignored) {}
throw new NotAcceptableException();
}
/**
* Parse a GeoQuery request parameters
* @param georel the georel parameter
* @param geometry the geometry parameter
* @param coords the coords parameter
* @return a GeoQuery
* @throws InvalidatedSyntaxException on error
*/
public static GeoQuery parseGeoQuery(String georel, String geometry, String coords) {
String[] georelFields = georel.split(";");
GeoQuery.Relation relation;
try {
relation = GeoQuery.Relation.valueOf(georelFields[0]);
} catch (IllegalArgumentException e) { | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/NotAcceptableException.java
// public class NotAcceptableException extends Ngsi2Exception {
//
// private final static String message = "Not Acceptable: Accepted MIME types: text/plain.";
//
// public NotAcceptableException() {
// super("406", message, null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Coordinate.java
// public class Coordinate {
//
// double latitude;
//
// double longitude;
//
// public Coordinate(double latitude, double longitude) {
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public void setLatitude(double latitude) {
// this.latitude = latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public void setLongitude(double longitude) {
// this.longitude = longitude;
// }
//
// @Override
// public String toString() {
// return latitude + "," + longitude ;
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
// Path: ngsi2-server/src/main/java/com/orange/ngsi2/server/Ngsi2ParsingHelper.java
import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.exception.NotAcceptableException;
import com.orange.ngsi2.model.Coordinate;
import com.orange.ngsi2.model.GeoQuery;
import java.util.ArrayList;
import java.util.List;
// Attempt to parse as the simplest number format possible...
try {
return Integer.parseInt(value);
} catch (NumberFormatException ignored) {}
try {
return Long.parseLong(value);
} catch (NumberFormatException ignored) {}
try {
return Float.parseFloat(value);
} catch (NumberFormatException ignored) {}
try {
return Double.parseDouble(value);
} catch (NumberFormatException ignored) {}
throw new NotAcceptableException();
}
/**
* Parse a GeoQuery request parameters
* @param georel the georel parameter
* @param geometry the geometry parameter
* @param coords the coords parameter
* @return a GeoQuery
* @throws InvalidatedSyntaxException on error
*/
public static GeoQuery parseGeoQuery(String georel, String geometry, String coords) {
String[] georelFields = georel.split(";");
GeoQuery.Relation relation;
try {
relation = GeoQuery.Relation.valueOf(georelFields[0]);
} catch (IllegalArgumentException e) { | throw new InvalidatedSyntaxException(georelFields[0]); |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-server/src/main/java/com/orange/ngsi2/server/Ngsi2ParsingHelper.java | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/NotAcceptableException.java
// public class NotAcceptableException extends Ngsi2Exception {
//
// private final static String message = "Not Acceptable: Accepted MIME types: text/plain.";
//
// public NotAcceptableException() {
// super("406", message, null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Coordinate.java
// public class Coordinate {
//
// double latitude;
//
// double longitude;
//
// public Coordinate(double latitude, double longitude) {
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public void setLatitude(double latitude) {
// this.latitude = latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public void setLongitude(double longitude) {
// this.longitude = longitude;
// }
//
// @Override
// public String toString() {
// return latitude + "," + longitude ;
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
| import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.exception.NotAcceptableException;
import com.orange.ngsi2.model.Coordinate;
import com.orange.ngsi2.model.GeoQuery;
import java.util.ArrayList;
import java.util.List; | return new GeoQuery(GeoQuery.Modifier.valueOf(modifierFields[0]), Float.parseFloat(modifierFields[1]),
parseGeometry(geometry), parseCoordinates(coords));
} catch (IllegalArgumentException e) {
throw new InvalidatedSyntaxException(georelFields[1]);
}
}
return new GeoQuery(relation, parseGeometry(geometry), parseCoordinates(coords));
}
/**
* Parse the geometry parameter
* @param geometry the geometry parameter
* @return a GeoQuery.Geometry
* @throws InvalidatedSyntaxException on error
*/
public static GeoQuery.Geometry parseGeometry(String geometry) {
try {
return GeoQuery.Geometry.valueOf(geometry);
} catch (IllegalArgumentException e) {
throw new InvalidatedSyntaxException(geometry);
}
}
/**
* Parse the coords parameter
* @param stringCoord the coord parameter
* @return a List of Coordinate
* @throws InvalidatedSyntaxException on error
*/ | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/InvalidatedSyntaxException.java
// public class InvalidatedSyntaxException extends Ngsi2Exception {
//
// private final static String message = "The incoming request is invalid in this context. %s has a bad syntax.";
//
// public InvalidatedSyntaxException(Error error) {
// super(error);
// }
//
// public InvalidatedSyntaxException(String field) {
// super("400", String.format(message, field), null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/NotAcceptableException.java
// public class NotAcceptableException extends Ngsi2Exception {
//
// private final static String message = "Not Acceptable: Accepted MIME types: text/plain.";
//
// public NotAcceptableException() {
// super("406", message, null);
// }
//
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Coordinate.java
// public class Coordinate {
//
// double latitude;
//
// double longitude;
//
// public Coordinate(double latitude, double longitude) {
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public void setLatitude(double latitude) {
// this.latitude = latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public void setLongitude(double longitude) {
// this.longitude = longitude;
// }
//
// @Override
// public String toString() {
// return latitude + "," + longitude ;
// }
// }
//
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/GeoQuery.java
// public class GeoQuery {
//
// /**
// * GeoQuery Enum model
// */
// public enum Relation {
// near, coveredBy, intersects, equals, disjoint
// }
//
// /**
// * Modifier Enum model
// */
// public enum Modifier {
// maxDistance, minDistance
// }
//
// /**
// * Geometry enum used for entities querying
// */
// public enum Geometry {
// point, line, polygon, box
// }
//
// private final Relation relation;
//
// private final Geometry geometry;
//
// private final List<Coordinate> coordinates;
//
// /**
// * Defined only for a near relation
// */
// private final Modifier modifier;
//
// /**
// * Defined only for a near relation
// */
// private final float distance;
//
// /**
// * Default constructor
// * @param relation relation to the geometry
// * @param geometry geometry to match
// * @param coordinates coordinates for the geometry
// */
// public GeoQuery(Relation relation, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = relation;
// this.geometry = geometry;
// this.coordinates = coordinates;
// this.modifier = null;
// this.distance = 0;
// }
//
// /**
// * Defines a near relation with modifier and distance
// * @param modifier
// * @param distance
// */
// public GeoQuery(Modifier modifier, float distance, Geometry geometry, List<Coordinate> coordinates) {
// this.relation = Relation.near;
// this.modifier = modifier;
// this.distance = distance;
// this.geometry = geometry;
// this.coordinates = coordinates;
// }
//
// public Relation getRelation() {
// return relation;
// }
//
// public Modifier getModifier() {
// return modifier;
// }
//
// public float getDistance() {
// return distance;
// }
//
// public Geometry getGeometry() {
// return geometry;
// }
//
// public List<Coordinate> getCoordinates() {
// return coordinates;
// }
// }
// Path: ngsi2-server/src/main/java/com/orange/ngsi2/server/Ngsi2ParsingHelper.java
import com.orange.ngsi2.exception.InvalidatedSyntaxException;
import com.orange.ngsi2.exception.NotAcceptableException;
import com.orange.ngsi2.model.Coordinate;
import com.orange.ngsi2.model.GeoQuery;
import java.util.ArrayList;
import java.util.List;
return new GeoQuery(GeoQuery.Modifier.valueOf(modifierFields[0]), Float.parseFloat(modifierFields[1]),
parseGeometry(geometry), parseCoordinates(coords));
} catch (IllegalArgumentException e) {
throw new InvalidatedSyntaxException(georelFields[1]);
}
}
return new GeoQuery(relation, parseGeometry(geometry), parseCoordinates(coords));
}
/**
* Parse the geometry parameter
* @param geometry the geometry parameter
* @return a GeoQuery.Geometry
* @throws InvalidatedSyntaxException on error
*/
public static GeoQuery.Geometry parseGeometry(String geometry) {
try {
return GeoQuery.Geometry.valueOf(geometry);
} catch (IllegalArgumentException e) {
throw new InvalidatedSyntaxException(geometry);
}
}
/**
* Parse the coords parameter
* @param stringCoord the coord parameter
* @return a List of Coordinate
* @throws InvalidatedSyntaxException on error
*/ | public static List<Coordinate> parseCoordinates(String stringCoord) { |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-client/src/test/java/com/orange/ngsi2/model/SubscriptionTest.java | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
| import static org.junit.Assert.assertTrue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.orange.ngsi2.Utils;
import org.junit.Test;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Instant;
import java.util.*;
import static org.junit.Assert.assertEquals; | " \"id\" : \"Bcn_Welt\",\n" +
" \"type\" : \"Room\"\n" +
" } ],\n" +
" \"condition\" : {\n" +
" \"attributes\" : [ \"temperature\" ],\n" +
" \"expression\" : {\n" +
" \"q\" : \"temperature>40\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"notification\" : {\n" +
" \"attributes\" : [ \"temperature\", \"humidity\" ],\n" +
" \"callback\" : \"http://localhost:1234\",\n" +
" \"headers\" : {\n" +
" \"X-MyHeader\" : \"foo\"\n" +
" },\n" +
" \"query\" : {\n" +
" \"authToken\" : \"bar\"\n" +
" },\n" +
" \"attrsFormat\" : \"keyValues\",\n" +
" \"throttling\" : 5,\n" +
" \"timesSent\" : 12,\n" +
" \"lastNotification\" : \"2015-10-05T16:00:00.100Z\"\n" +
" },\n" +
" \"expires\" : \"2016-04-05T14:00:00.200Z\",\n" +
" \"status\" : \"active\"\n" +
"}";
@Test
public void serializationSubscriptionTest() throws JsonProcessingException, MalformedURLException { | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
// Path: ngsi2-client/src/test/java/com/orange/ngsi2/model/SubscriptionTest.java
import static org.junit.Assert.assertTrue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.orange.ngsi2.Utils;
import org.junit.Test;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Instant;
import java.util.*;
import static org.junit.Assert.assertEquals;
" \"id\" : \"Bcn_Welt\",\n" +
" \"type\" : \"Room\"\n" +
" } ],\n" +
" \"condition\" : {\n" +
" \"attributes\" : [ \"temperature\" ],\n" +
" \"expression\" : {\n" +
" \"q\" : \"temperature>40\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"notification\" : {\n" +
" \"attributes\" : [ \"temperature\", \"humidity\" ],\n" +
" \"callback\" : \"http://localhost:1234\",\n" +
" \"headers\" : {\n" +
" \"X-MyHeader\" : \"foo\"\n" +
" },\n" +
" \"query\" : {\n" +
" \"authToken\" : \"bar\"\n" +
" },\n" +
" \"attrsFormat\" : \"keyValues\",\n" +
" \"throttling\" : 5,\n" +
" \"timesSent\" : 12,\n" +
" \"lastNotification\" : \"2015-10-05T16:00:00.100Z\"\n" +
" },\n" +
" \"expires\" : \"2016-04-05T14:00:00.200Z\",\n" +
" \"status\" : \"active\"\n" +
"}";
@Test
public void serializationSubscriptionTest() throws JsonProcessingException, MalformedURLException { | ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter()); |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-client/src/test/java/com/orange/ngsi2/model/EntityTest.java | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.orange.ngsi2.Utils;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import static org.junit.Assert.*; | /*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.model;
/**
* Tests for the Entity
*/
public class EntityTest {
@Test
public void serializationEntityTest() throws JsonProcessingException { | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
// Path: ngsi2-client/src/test/java/com/orange/ngsi2/model/EntityTest.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.orange.ngsi2.Utils;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import static org.junit.Assert.*;
/*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.model;
/**
* Tests for the Entity
*/
public class EntityTest {
@Test
public void serializationEntityTest() throws JsonProcessingException { | ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter()); |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-client/src/main/java/com/orange/ngsi2/exception/ConflictingEntitiesException.java | // Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Error.java
// public class Error {
//
// private String error;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<String> description;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<Collection<String>> affectedItems;
//
// public Error() {
// }
//
// public Error(String error) {
// this.error = error;
// }
//
// public Error(String error, Optional<String> description, Optional<Collection<String>> affectedItems) {
// this.error = error;
// this.description = description;
// this.affectedItems = affectedItems;
// }
//
// public String getError() {
// return error;
// }
//
// public void setError(String error) {
// this.error = error;
// }
//
// public Optional<String> getDescription() {
// return description;
// }
//
// public void setDescription(Optional<String> description) {
// this.description = description;
// }
//
// public Optional<Collection<String>> getAffectedItems() {
// return affectedItems;
// }
//
// public void setAffectedItems(Optional<Collection<String>> affectedItems) {
// this.affectedItems = affectedItems;
// }
//
// @Override
// public String toString() {
// return String.format("error: %s | description: %s | affectedItems: %s", error, description.orElse(""), affectedItems.orElse(Collections.emptyList()));
// }
// }
| import com.orange.ngsi2.model.Error;
import java.util.Collection;
import java.util.Optional; | /*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.exception;
/**
* 409 TooManyResults
*/
public class ConflictingEntitiesException extends Ngsi2Exception {
private final static String message = "Too many results. There are several results that match with the %s used in the request. Instead of, you can use %s";
| // Path: ngsi2-client/src/main/java/com/orange/ngsi2/model/Error.java
// public class Error {
//
// private String error;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<String> description;
//
// @JsonInclude(JsonInclude.Include.NON_EMPTY)
// private Optional<Collection<String>> affectedItems;
//
// public Error() {
// }
//
// public Error(String error) {
// this.error = error;
// }
//
// public Error(String error, Optional<String> description, Optional<Collection<String>> affectedItems) {
// this.error = error;
// this.description = description;
// this.affectedItems = affectedItems;
// }
//
// public String getError() {
// return error;
// }
//
// public void setError(String error) {
// this.error = error;
// }
//
// public Optional<String> getDescription() {
// return description;
// }
//
// public void setDescription(Optional<String> description) {
// this.description = description;
// }
//
// public Optional<Collection<String>> getAffectedItems() {
// return affectedItems;
// }
//
// public void setAffectedItems(Optional<Collection<String>> affectedItems) {
// this.affectedItems = affectedItems;
// }
//
// @Override
// public String toString() {
// return String.format("error: %s | description: %s | affectedItems: %s", error, description.orElse(""), affectedItems.orElse(Collections.emptyList()));
// }
// }
// Path: ngsi2-client/src/main/java/com/orange/ngsi2/exception/ConflictingEntitiesException.java
import com.orange.ngsi2.model.Error;
import java.util.Collection;
import java.util.Optional;
/*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.exception;
/**
* 409 TooManyResults
*/
public class ConflictingEntitiesException extends Ngsi2Exception {
private final static String message = "Too many results. There are several results that match with the %s used in the request. Instead of, you can use %s";
| public ConflictingEntitiesException(Error error) { |
Orange-OpenSource/fiware-ngsi2-api | ngsi2-client/src/test/java/com/orange/ngsi2/model/EntityTypeTest.java | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
| import static org.junit.Assert.assertTrue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.orange.ngsi2.Utils;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals; | /*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.model;
/**
* Tests for the Entity Type
*/
public class EntityTypeTest {
private String jsonString = "{\n" +
" \"attrs\" : {\n" +
" \"temperature\" : {\n" +
" \"type\" : \"urn:phenomenum:temperature\"\n" +
" },\n" +
" \"humidity\" : {\n" +
" \"type\" : \"percentage\"\n" +
" },\n" +
" \"pressure\" : {\n" +
" \"type\" : \"null\"\n" +
" }\n" +
" },\n" +
" \"count\" : 7\n" +
"}";
@Test
public void serializationEntityTypeTest() throws JsonProcessingException { | // Path: ngsi2-client/src/test/java/com/orange/ngsi2/Utils.java
// public class Utils {
//
// /**
// * Common object mapper used for most tests with Java 8 support for Optional
// */
// public final static ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule())
// .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//
// /**
// * Load a resource as an UTF-8 string
// * @param name name of the resource
// * @return the content of the resource
// */
// public static String loadResource(String name) {
// try {
// URL url = Utils.class.getClassLoader().getResource(name);
// if (url == null) {
// return "";
// }
// return new String(Files.readAllBytes(Paths.get(url.toURI())), "UTF-8");
// } catch (Exception e) {
// return "";
// }
// }
//
// }
// Path: ngsi2-client/src/test/java/com/orange/ngsi2/model/EntityTypeTest.java
import static org.junit.Assert.assertTrue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.orange.ngsi2.Utils;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/*
* Copyright (C) 2016 Orange
*
* 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.orange.ngsi2.model;
/**
* Tests for the Entity Type
*/
public class EntityTypeTest {
private String jsonString = "{\n" +
" \"attrs\" : {\n" +
" \"temperature\" : {\n" +
" \"type\" : \"urn:phenomenum:temperature\"\n" +
" },\n" +
" \"humidity\" : {\n" +
" \"type\" : \"percentage\"\n" +
" },\n" +
" \"pressure\" : {\n" +
" \"type\" : \"null\"\n" +
" }\n" +
" },\n" +
" \"count\" : 7\n" +
"}";
@Test
public void serializationEntityTypeTest() throws JsonProcessingException { | ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter()); |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/responses/ControlResponseHeader.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/BaseControlMessage.java
// public class BaseControlMessage {
//
// public int ProtocolVersion = 3;
// public int Code;
//
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/ControlResponseCode.java
// public class ControlResponseCode {
//
// /// <summary>
// /// API awaits connection at given endpoint.
// /// </summary>
// public static int OK = 0;
//
// /// <summary>
// /// API is not available because of undefined reason.
// /// </summary>
// public static int NotAvailable = 1;
//
// /// <summary>
// /// API is in use by another client
// /// </summary>
// public static int InUse = 2;
//
// /// <summary>
// /// Client is trying to use something that requires API client to be updated to more recent version
// /// </summary>
// public static int ClientOutdated = 3;
//
// /// <summary>
// /// VRidge needs to be updated or client is not following protocol
// /// </summary>
// public static int ServerOutdated = 4;
//
// }
| import com.riftcat.vridge.api.client.java.control.BaseControlMessage;
import com.riftcat.vridge.api.client.java.control.ControlResponseCode; | package com.riftcat.vridge.api.client.java.control.responses;
public class ControlResponseHeader extends BaseControlMessage {
// Predefined responses
public static ControlResponseHeader ResponseInUse;
public static ControlResponseHeader ResponseClientOutdated;
public static ControlResponseHeader ResponseNotAvailable;
static{
// Predefined responses
ResponseNotAvailable = new ControlResponseHeader(); | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/BaseControlMessage.java
// public class BaseControlMessage {
//
// public int ProtocolVersion = 3;
// public int Code;
//
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/ControlResponseCode.java
// public class ControlResponseCode {
//
// /// <summary>
// /// API awaits connection at given endpoint.
// /// </summary>
// public static int OK = 0;
//
// /// <summary>
// /// API is not available because of undefined reason.
// /// </summary>
// public static int NotAvailable = 1;
//
// /// <summary>
// /// API is in use by another client
// /// </summary>
// public static int InUse = 2;
//
// /// <summary>
// /// Client is trying to use something that requires API client to be updated to more recent version
// /// </summary>
// public static int ClientOutdated = 3;
//
// /// <summary>
// /// VRidge needs to be updated or client is not following protocol
// /// </summary>
// public static int ServerOutdated = 4;
//
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/responses/ControlResponseHeader.java
import com.riftcat.vridge.api.client.java.control.BaseControlMessage;
import com.riftcat.vridge.api.client.java.control.ControlResponseCode;
package com.riftcat.vridge.api.client.java.control.responses;
public class ControlResponseHeader extends BaseControlMessage {
// Predefined responses
public static ControlResponseHeader ResponseInUse;
public static ControlResponseHeader ResponseClientOutdated;
public static ControlResponseHeader ResponseNotAvailable;
static{
// Predefined responses
ResponseNotAvailable = new ControlResponseHeader(); | ResponseNotAvailable.Code = ControlResponseCode.NotAvailable; |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/HeadTrackingProxy.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingRequestCodes.java
// public class HeadTrackingRequestCodes {
//
// public static int Disconnect = 255;
//
// public static int ChangeState = 254;
// public static int Recenter = 50;
//
// public static int SendPoseMatrixRotationOnly = 0;
// public static int SendPoseMatrixFull = 6;
// public static int SendRotationMatrix = 1;
// public static int SendRadRotationAndPosition = 3;
// public static int SendQuatRotationAndPosition = 4;
// public static int SendPositionOnly = 5;
//
// public static int RequestSyncOffset = 100;
// public static int RequestReadOnlyPose = 199;
// public static int RequestReadOnlyPhonePose = 200;
//
// public static int SetYawOffset = 201;
// public static int ResetYawOffset = 21;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingResponseCodes.java
// public class HeadTrackingResponseCodes {
//
// public static int AcceptedYourData = 0;
//
// public static int SendingCurrentTrackedPose = 2;
//
// public static int PhoneDataTimeout = 253;
// public static int BadRequest = 254;
// public static int Disconnecting = 255;
//
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/TrackedDeviceStatus.java
// public class TrackedDeviceStatus {
// public static final byte Active = 0;
// public static final byte TempUnavailable = 1;
// public static final byte Disabled = 2;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/SerializationUtils.java
// public class SerializationUtils {
//
// public static ByteString byteStringFromFloats(float...args){
// return ByteString.copyFrom(byteArrayFromFloats(args));
// }
//
// public static byte[] byteArrayFromFloats(float... args){
// ByteBuffer data = ByteBuffer.allocate(args.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : args) {
// data.putFloat(arg);
// }
//
// return data.array();
// }
//
// public static ByteString byteStringFromFloatArray(float[] array){
// ByteBuffer data = ByteBuffer.allocate(array.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : array) {
// data.putFloat(arg);
// }
//
// return ByteString.copyFrom(data.array());
// }
// }
| import com.google.protobuf.ByteString;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingRequestCodes;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingResponseCodes;
import com.riftcat.vridge.api.client.java.codes.TrackedDeviceStatus;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingRequest;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingResponse;
import com.riftcat.vridge.api.client.java.proto.TrackedPose;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import com.riftcat.vridge.api.client.java.utils.SerializationUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.TimeoutException; | package com.riftcat.vridge.api.client.java.proxy;
public class HeadTrackingProxy extends ClientProxyBase {
// This is only partial implementation of API calls
public HeadTrackingProxy(String endpointAddress, boolean shouldKeepAlive){
super(endpointAddress, shouldKeepAlive);
}
/**
* Sets head position to new location.
*/
public boolean setPosition(float x, float y, float z) throws TimeoutException {
HeadTrackingRequest request = HeadTrackingRequest
.newBuilder()
.setVersion(CurrentVersion) | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingRequestCodes.java
// public class HeadTrackingRequestCodes {
//
// public static int Disconnect = 255;
//
// public static int ChangeState = 254;
// public static int Recenter = 50;
//
// public static int SendPoseMatrixRotationOnly = 0;
// public static int SendPoseMatrixFull = 6;
// public static int SendRotationMatrix = 1;
// public static int SendRadRotationAndPosition = 3;
// public static int SendQuatRotationAndPosition = 4;
// public static int SendPositionOnly = 5;
//
// public static int RequestSyncOffset = 100;
// public static int RequestReadOnlyPose = 199;
// public static int RequestReadOnlyPhonePose = 200;
//
// public static int SetYawOffset = 201;
// public static int ResetYawOffset = 21;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingResponseCodes.java
// public class HeadTrackingResponseCodes {
//
// public static int AcceptedYourData = 0;
//
// public static int SendingCurrentTrackedPose = 2;
//
// public static int PhoneDataTimeout = 253;
// public static int BadRequest = 254;
// public static int Disconnecting = 255;
//
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/TrackedDeviceStatus.java
// public class TrackedDeviceStatus {
// public static final byte Active = 0;
// public static final byte TempUnavailable = 1;
// public static final byte Disabled = 2;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/SerializationUtils.java
// public class SerializationUtils {
//
// public static ByteString byteStringFromFloats(float...args){
// return ByteString.copyFrom(byteArrayFromFloats(args));
// }
//
// public static byte[] byteArrayFromFloats(float... args){
// ByteBuffer data = ByteBuffer.allocate(args.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : args) {
// data.putFloat(arg);
// }
//
// return data.array();
// }
//
// public static ByteString byteStringFromFloatArray(float[] array){
// ByteBuffer data = ByteBuffer.allocate(array.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : array) {
// data.putFloat(arg);
// }
//
// return ByteString.copyFrom(data.array());
// }
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/HeadTrackingProxy.java
import com.google.protobuf.ByteString;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingRequestCodes;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingResponseCodes;
import com.riftcat.vridge.api.client.java.codes.TrackedDeviceStatus;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingRequest;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingResponse;
import com.riftcat.vridge.api.client.java.proto.TrackedPose;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import com.riftcat.vridge.api.client.java.utils.SerializationUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.TimeoutException;
package com.riftcat.vridge.api.client.java.proxy;
public class HeadTrackingProxy extends ClientProxyBase {
// This is only partial implementation of API calls
public HeadTrackingProxy(String endpointAddress, boolean shouldKeepAlive){
super(endpointAddress, shouldKeepAlive);
}
/**
* Sets head position to new location.
*/
public boolean setPosition(float x, float y, float z) throws TimeoutException {
HeadTrackingRequest request = HeadTrackingRequest
.newBuilder()
.setVersion(CurrentVersion) | .setTaskType(HeadTrackingRequestCodes.SendPositionOnly) |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/HeadTrackingProxy.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingRequestCodes.java
// public class HeadTrackingRequestCodes {
//
// public static int Disconnect = 255;
//
// public static int ChangeState = 254;
// public static int Recenter = 50;
//
// public static int SendPoseMatrixRotationOnly = 0;
// public static int SendPoseMatrixFull = 6;
// public static int SendRotationMatrix = 1;
// public static int SendRadRotationAndPosition = 3;
// public static int SendQuatRotationAndPosition = 4;
// public static int SendPositionOnly = 5;
//
// public static int RequestSyncOffset = 100;
// public static int RequestReadOnlyPose = 199;
// public static int RequestReadOnlyPhonePose = 200;
//
// public static int SetYawOffset = 201;
// public static int ResetYawOffset = 21;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingResponseCodes.java
// public class HeadTrackingResponseCodes {
//
// public static int AcceptedYourData = 0;
//
// public static int SendingCurrentTrackedPose = 2;
//
// public static int PhoneDataTimeout = 253;
// public static int BadRequest = 254;
// public static int Disconnecting = 255;
//
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/TrackedDeviceStatus.java
// public class TrackedDeviceStatus {
// public static final byte Active = 0;
// public static final byte TempUnavailable = 1;
// public static final byte Disabled = 2;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/SerializationUtils.java
// public class SerializationUtils {
//
// public static ByteString byteStringFromFloats(float...args){
// return ByteString.copyFrom(byteArrayFromFloats(args));
// }
//
// public static byte[] byteArrayFromFloats(float... args){
// ByteBuffer data = ByteBuffer.allocate(args.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : args) {
// data.putFloat(arg);
// }
//
// return data.array();
// }
//
// public static ByteString byteStringFromFloatArray(float[] array){
// ByteBuffer data = ByteBuffer.allocate(array.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : array) {
// data.putFloat(arg);
// }
//
// return ByteString.copyFrom(data.array());
// }
// }
| import com.google.protobuf.ByteString;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingRequestCodes;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingResponseCodes;
import com.riftcat.vridge.api.client.java.codes.TrackedDeviceStatus;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingRequest;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingResponse;
import com.riftcat.vridge.api.client.java.proto.TrackedPose;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import com.riftcat.vridge.api.client.java.utils.SerializationUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.TimeoutException; | package com.riftcat.vridge.api.client.java.proxy;
public class HeadTrackingProxy extends ClientProxyBase {
// This is only partial implementation of API calls
public HeadTrackingProxy(String endpointAddress, boolean shouldKeepAlive){
super(endpointAddress, shouldKeepAlive);
}
/**
* Sets head position to new location.
*/
public boolean setPosition(float x, float y, float z) throws TimeoutException {
HeadTrackingRequest request = HeadTrackingRequest
.newBuilder()
.setVersion(CurrentVersion)
.setTaskType(HeadTrackingRequestCodes.SendPositionOnly) | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingRequestCodes.java
// public class HeadTrackingRequestCodes {
//
// public static int Disconnect = 255;
//
// public static int ChangeState = 254;
// public static int Recenter = 50;
//
// public static int SendPoseMatrixRotationOnly = 0;
// public static int SendPoseMatrixFull = 6;
// public static int SendRotationMatrix = 1;
// public static int SendRadRotationAndPosition = 3;
// public static int SendQuatRotationAndPosition = 4;
// public static int SendPositionOnly = 5;
//
// public static int RequestSyncOffset = 100;
// public static int RequestReadOnlyPose = 199;
// public static int RequestReadOnlyPhonePose = 200;
//
// public static int SetYawOffset = 201;
// public static int ResetYawOffset = 21;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingResponseCodes.java
// public class HeadTrackingResponseCodes {
//
// public static int AcceptedYourData = 0;
//
// public static int SendingCurrentTrackedPose = 2;
//
// public static int PhoneDataTimeout = 253;
// public static int BadRequest = 254;
// public static int Disconnecting = 255;
//
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/TrackedDeviceStatus.java
// public class TrackedDeviceStatus {
// public static final byte Active = 0;
// public static final byte TempUnavailable = 1;
// public static final byte Disabled = 2;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/SerializationUtils.java
// public class SerializationUtils {
//
// public static ByteString byteStringFromFloats(float...args){
// return ByteString.copyFrom(byteArrayFromFloats(args));
// }
//
// public static byte[] byteArrayFromFloats(float... args){
// ByteBuffer data = ByteBuffer.allocate(args.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : args) {
// data.putFloat(arg);
// }
//
// return data.array();
// }
//
// public static ByteString byteStringFromFloatArray(float[] array){
// ByteBuffer data = ByteBuffer.allocate(array.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : array) {
// data.putFloat(arg);
// }
//
// return ByteString.copyFrom(data.array());
// }
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/HeadTrackingProxy.java
import com.google.protobuf.ByteString;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingRequestCodes;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingResponseCodes;
import com.riftcat.vridge.api.client.java.codes.TrackedDeviceStatus;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingRequest;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingResponse;
import com.riftcat.vridge.api.client.java.proto.TrackedPose;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import com.riftcat.vridge.api.client.java.utils.SerializationUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.TimeoutException;
package com.riftcat.vridge.api.client.java.proxy;
public class HeadTrackingProxy extends ClientProxyBase {
// This is only partial implementation of API calls
public HeadTrackingProxy(String endpointAddress, boolean shouldKeepAlive){
super(endpointAddress, shouldKeepAlive);
}
/**
* Sets head position to new location.
*/
public boolean setPosition(float x, float y, float z) throws TimeoutException {
HeadTrackingRequest request = HeadTrackingRequest
.newBuilder()
.setVersion(CurrentVersion)
.setTaskType(HeadTrackingRequestCodes.SendPositionOnly) | .setData(SerializationUtils.byteStringFromFloats(x, y, z)) |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/HeadTrackingProxy.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingRequestCodes.java
// public class HeadTrackingRequestCodes {
//
// public static int Disconnect = 255;
//
// public static int ChangeState = 254;
// public static int Recenter = 50;
//
// public static int SendPoseMatrixRotationOnly = 0;
// public static int SendPoseMatrixFull = 6;
// public static int SendRotationMatrix = 1;
// public static int SendRadRotationAndPosition = 3;
// public static int SendQuatRotationAndPosition = 4;
// public static int SendPositionOnly = 5;
//
// public static int RequestSyncOffset = 100;
// public static int RequestReadOnlyPose = 199;
// public static int RequestReadOnlyPhonePose = 200;
//
// public static int SetYawOffset = 201;
// public static int ResetYawOffset = 21;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingResponseCodes.java
// public class HeadTrackingResponseCodes {
//
// public static int AcceptedYourData = 0;
//
// public static int SendingCurrentTrackedPose = 2;
//
// public static int PhoneDataTimeout = 253;
// public static int BadRequest = 254;
// public static int Disconnecting = 255;
//
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/TrackedDeviceStatus.java
// public class TrackedDeviceStatus {
// public static final byte Active = 0;
// public static final byte TempUnavailable = 1;
// public static final byte Disabled = 2;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/SerializationUtils.java
// public class SerializationUtils {
//
// public static ByteString byteStringFromFloats(float...args){
// return ByteString.copyFrom(byteArrayFromFloats(args));
// }
//
// public static byte[] byteArrayFromFloats(float... args){
// ByteBuffer data = ByteBuffer.allocate(args.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : args) {
// data.putFloat(arg);
// }
//
// return data.array();
// }
//
// public static ByteString byteStringFromFloatArray(float[] array){
// ByteBuffer data = ByteBuffer.allocate(array.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : array) {
// data.putFloat(arg);
// }
//
// return ByteString.copyFrom(data.array());
// }
// }
| import com.google.protobuf.ByteString;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingRequestCodes;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingResponseCodes;
import com.riftcat.vridge.api.client.java.codes.TrackedDeviceStatus;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingRequest;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingResponse;
import com.riftcat.vridge.api.client.java.proto.TrackedPose;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import com.riftcat.vridge.api.client.java.utils.SerializationUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.TimeoutException; | package com.riftcat.vridge.api.client.java.proxy;
public class HeadTrackingProxy extends ClientProxyBase {
// This is only partial implementation of API calls
public HeadTrackingProxy(String endpointAddress, boolean shouldKeepAlive){
super(endpointAddress, shouldKeepAlive);
}
/**
* Sets head position to new location.
*/
public boolean setPosition(float x, float y, float z) throws TimeoutException {
HeadTrackingRequest request = HeadTrackingRequest
.newBuilder()
.setVersion(CurrentVersion)
.setTaskType(HeadTrackingRequestCodes.SendPositionOnly)
.setData(SerializationUtils.byteStringFromFloats(x, y, z))
.build();
HeadTrackingResponse reply = sendMessage(request);
| // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingRequestCodes.java
// public class HeadTrackingRequestCodes {
//
// public static int Disconnect = 255;
//
// public static int ChangeState = 254;
// public static int Recenter = 50;
//
// public static int SendPoseMatrixRotationOnly = 0;
// public static int SendPoseMatrixFull = 6;
// public static int SendRotationMatrix = 1;
// public static int SendRadRotationAndPosition = 3;
// public static int SendQuatRotationAndPosition = 4;
// public static int SendPositionOnly = 5;
//
// public static int RequestSyncOffset = 100;
// public static int RequestReadOnlyPose = 199;
// public static int RequestReadOnlyPhonePose = 200;
//
// public static int SetYawOffset = 201;
// public static int ResetYawOffset = 21;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingResponseCodes.java
// public class HeadTrackingResponseCodes {
//
// public static int AcceptedYourData = 0;
//
// public static int SendingCurrentTrackedPose = 2;
//
// public static int PhoneDataTimeout = 253;
// public static int BadRequest = 254;
// public static int Disconnecting = 255;
//
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/TrackedDeviceStatus.java
// public class TrackedDeviceStatus {
// public static final byte Active = 0;
// public static final byte TempUnavailable = 1;
// public static final byte Disabled = 2;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/SerializationUtils.java
// public class SerializationUtils {
//
// public static ByteString byteStringFromFloats(float...args){
// return ByteString.copyFrom(byteArrayFromFloats(args));
// }
//
// public static byte[] byteArrayFromFloats(float... args){
// ByteBuffer data = ByteBuffer.allocate(args.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : args) {
// data.putFloat(arg);
// }
//
// return data.array();
// }
//
// public static ByteString byteStringFromFloatArray(float[] array){
// ByteBuffer data = ByteBuffer.allocate(array.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : array) {
// data.putFloat(arg);
// }
//
// return ByteString.copyFrom(data.array());
// }
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/HeadTrackingProxy.java
import com.google.protobuf.ByteString;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingRequestCodes;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingResponseCodes;
import com.riftcat.vridge.api.client.java.codes.TrackedDeviceStatus;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingRequest;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingResponse;
import com.riftcat.vridge.api.client.java.proto.TrackedPose;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import com.riftcat.vridge.api.client.java.utils.SerializationUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.TimeoutException;
package com.riftcat.vridge.api.client.java.proxy;
public class HeadTrackingProxy extends ClientProxyBase {
// This is only partial implementation of API calls
public HeadTrackingProxy(String endpointAddress, boolean shouldKeepAlive){
super(endpointAddress, shouldKeepAlive);
}
/**
* Sets head position to new location.
*/
public boolean setPosition(float x, float y, float z) throws TimeoutException {
HeadTrackingRequest request = HeadTrackingRequest
.newBuilder()
.setVersion(CurrentVersion)
.setTaskType(HeadTrackingRequestCodes.SendPositionOnly)
.setData(SerializationUtils.byteStringFromFloats(x, y, z))
.build();
HeadTrackingResponse reply = sendMessage(request);
| return reply.getReplyCode() == HeadTrackingResponseCodes.AcceptedYourData; |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/HeadTrackingProxy.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingRequestCodes.java
// public class HeadTrackingRequestCodes {
//
// public static int Disconnect = 255;
//
// public static int ChangeState = 254;
// public static int Recenter = 50;
//
// public static int SendPoseMatrixRotationOnly = 0;
// public static int SendPoseMatrixFull = 6;
// public static int SendRotationMatrix = 1;
// public static int SendRadRotationAndPosition = 3;
// public static int SendQuatRotationAndPosition = 4;
// public static int SendPositionOnly = 5;
//
// public static int RequestSyncOffset = 100;
// public static int RequestReadOnlyPose = 199;
// public static int RequestReadOnlyPhonePose = 200;
//
// public static int SetYawOffset = 201;
// public static int ResetYawOffset = 21;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingResponseCodes.java
// public class HeadTrackingResponseCodes {
//
// public static int AcceptedYourData = 0;
//
// public static int SendingCurrentTrackedPose = 2;
//
// public static int PhoneDataTimeout = 253;
// public static int BadRequest = 254;
// public static int Disconnecting = 255;
//
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/TrackedDeviceStatus.java
// public class TrackedDeviceStatus {
// public static final byte Active = 0;
// public static final byte TempUnavailable = 1;
// public static final byte Disabled = 2;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/SerializationUtils.java
// public class SerializationUtils {
//
// public static ByteString byteStringFromFloats(float...args){
// return ByteString.copyFrom(byteArrayFromFloats(args));
// }
//
// public static byte[] byteArrayFromFloats(float... args){
// ByteBuffer data = ByteBuffer.allocate(args.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : args) {
// data.putFloat(arg);
// }
//
// return data.array();
// }
//
// public static ByteString byteStringFromFloatArray(float[] array){
// ByteBuffer data = ByteBuffer.allocate(array.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : array) {
// data.putFloat(arg);
// }
//
// return ByteString.copyFrom(data.array());
// }
// }
| import com.google.protobuf.ByteString;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingRequestCodes;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingResponseCodes;
import com.riftcat.vridge.api.client.java.codes.TrackedDeviceStatus;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingRequest;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingResponse;
import com.riftcat.vridge.api.client.java.proto.TrackedPose;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import com.riftcat.vridge.api.client.java.utils.SerializationUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.TimeoutException; |
HeadTrackingRequest request = HeadTrackingRequest
.newBuilder()
.setVersion(CurrentVersion)
.setTaskType(HeadTrackingRequestCodes.RequestReadOnlyPose)
.build();
HeadTrackingResponse reply = sendMessage(request);
if(reply.getReplyCode() == HeadTrackingResponseCodes.SendingCurrentTrackedPose){
return reply.getTrackedPose();
}
else{
return null;
}
}
public void setYawOffset(float yaw) throws TimeoutException {
HeadTrackingRequest request = HeadTrackingRequest
.newBuilder()
.setVersion(CurrentVersion)
.setTaskType(HeadTrackingRequestCodes.SetYawOffset)
.setData(SerializationUtils.byteStringFromFloats(yaw))
.build();
sendMessage(request);
}
public void changeTrackingState(boolean isInTrackingRange) throws TimeoutException {
byte[] state = new byte[1]; | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingRequestCodes.java
// public class HeadTrackingRequestCodes {
//
// public static int Disconnect = 255;
//
// public static int ChangeState = 254;
// public static int Recenter = 50;
//
// public static int SendPoseMatrixRotationOnly = 0;
// public static int SendPoseMatrixFull = 6;
// public static int SendRotationMatrix = 1;
// public static int SendRadRotationAndPosition = 3;
// public static int SendQuatRotationAndPosition = 4;
// public static int SendPositionOnly = 5;
//
// public static int RequestSyncOffset = 100;
// public static int RequestReadOnlyPose = 199;
// public static int RequestReadOnlyPhonePose = 200;
//
// public static int SetYawOffset = 201;
// public static int ResetYawOffset = 21;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/HeadTrackingResponseCodes.java
// public class HeadTrackingResponseCodes {
//
// public static int AcceptedYourData = 0;
//
// public static int SendingCurrentTrackedPose = 2;
//
// public static int PhoneDataTimeout = 253;
// public static int BadRequest = 254;
// public static int Disconnecting = 255;
//
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/TrackedDeviceStatus.java
// public class TrackedDeviceStatus {
// public static final byte Active = 0;
// public static final byte TempUnavailable = 1;
// public static final byte Disabled = 2;
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/SerializationUtils.java
// public class SerializationUtils {
//
// public static ByteString byteStringFromFloats(float...args){
// return ByteString.copyFrom(byteArrayFromFloats(args));
// }
//
// public static byte[] byteArrayFromFloats(float... args){
// ByteBuffer data = ByteBuffer.allocate(args.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : args) {
// data.putFloat(arg);
// }
//
// return data.array();
// }
//
// public static ByteString byteStringFromFloatArray(float[] array){
// ByteBuffer data = ByteBuffer.allocate(array.length * 4);
// data.order(ByteOrder.LITTLE_ENDIAN);
// for (float arg : array) {
// data.putFloat(arg);
// }
//
// return ByteString.copyFrom(data.array());
// }
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/HeadTrackingProxy.java
import com.google.protobuf.ByteString;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingRequestCodes;
import com.riftcat.vridge.api.client.java.codes.HeadTrackingResponseCodes;
import com.riftcat.vridge.api.client.java.codes.TrackedDeviceStatus;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingRequest;
import com.riftcat.vridge.api.client.java.proto.HeadTrackingResponse;
import com.riftcat.vridge.api.client.java.proto.TrackedPose;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import com.riftcat.vridge.api.client.java.utils.SerializationUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.TimeoutException;
HeadTrackingRequest request = HeadTrackingRequest
.newBuilder()
.setVersion(CurrentVersion)
.setTaskType(HeadTrackingRequestCodes.RequestReadOnlyPose)
.build();
HeadTrackingResponse reply = sendMessage(request);
if(reply.getReplyCode() == HeadTrackingResponseCodes.SendingCurrentTrackedPose){
return reply.getTrackedPose();
}
else{
return null;
}
}
public void setYawOffset(float yaw) throws TimeoutException {
HeadTrackingRequest request = HeadTrackingRequest
.newBuilder()
.setVersion(CurrentVersion)
.setTaskType(HeadTrackingRequestCodes.SetYawOffset)
.setData(SerializationUtils.byteStringFromFloats(yaw))
.build();
sendMessage(request);
}
public void changeTrackingState(boolean isInTrackingRange) throws TimeoutException {
byte[] state = new byte[1]; | state[0] = isInTrackingRange ? TrackedDeviceStatus.Active : TrackedDeviceStatus.TempUnavailable; |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/RemoteBase.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/ClientProxyBase.java
// public abstract class ClientProxyBase implements VRidgeApiProxy{
//
// private TimerTask keepAliveTimer;
// private Runnable keepAlivePing;
//
// private byte[] keepAlivePacket = { 0 };
//
// int CurrentVersion = 3;
// ZMQ.Socket socket;
//
// ClientProxyBase(String endpointAddress, boolean keepAlive){
//
// if(APIClient.ZContext == null) APIClient.ZContext = new ZContext(4);
// socket = APIClient.ZContext.createSocket(ZMQ.REQ);
// socket.setLinger(1000);
// socket.setSendTimeOut(15000);
// socket.setReceiveTimeOut(15000);
// socket.connect(endpointAddress);
// socket.setHWM(1);
//
// if (!keepAlive) return;
//
// keepAlivePing = new Runnable() {
// @Override
// public void run() {
// sendKeepAlivePing();
// }
// };
//
// ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// executor.scheduleAtFixedRate(keepAlivePing, 1, 5, TimeUnit.SECONDS);
// }
//
// void CloseSocket(){
// APIClient.ZContext.destroySocket(socket);
// }
//
// synchronized <T extends MessageLite> T SendMessage(MessageLite msg, Parser<T> parser) throws TimeoutException {
//
// APILogger.zmq("send begin");
// long timestamp = System.nanoTime();
// socket.send(msg.toByteArray());
// byte[] responseBytes = socket.recv();
// APILogger.zmq("recv end - " + (System.nanoTime() - timestamp) / 1000000.0);
//
// if (responseBytes != null){
// try {
// T response = parser.parseFrom(responseBytes);
// return response;
// } catch (InvalidProtocolBufferException e) {
// // whoops
// }
// }
//
// APILogger.zmq("timeout");
// APIClient.ZContext.destroySocket(socket);
// throw new TimeoutException();
// }
//
// public abstract void disconnect();
//
// public synchronized boolean sendKeepAlivePing(){
// boolean error = false;
// APILogger.zmq("ping begin: ");
// error = error || !socket.send(keepAlivePacket);
// error = error || socket.recv() == null;
// APILogger.zmq("ping end - error: " + error);
//
// return !error;
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/VRidgeApiProxy.java
// public interface VRidgeApiProxy {
// void disconnect();
// }
| import com.riftcat.vridge.api.client.java.proxy.ClientProxyBase;
import com.riftcat.vridge.api.client.java.proxy.VRidgeApiProxy; | package com.riftcat.vridge.api.client.java.remotes;
class RemoteBase {
private boolean isDisposed; | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/ClientProxyBase.java
// public abstract class ClientProxyBase implements VRidgeApiProxy{
//
// private TimerTask keepAliveTimer;
// private Runnable keepAlivePing;
//
// private byte[] keepAlivePacket = { 0 };
//
// int CurrentVersion = 3;
// ZMQ.Socket socket;
//
// ClientProxyBase(String endpointAddress, boolean keepAlive){
//
// if(APIClient.ZContext == null) APIClient.ZContext = new ZContext(4);
// socket = APIClient.ZContext.createSocket(ZMQ.REQ);
// socket.setLinger(1000);
// socket.setSendTimeOut(15000);
// socket.setReceiveTimeOut(15000);
// socket.connect(endpointAddress);
// socket.setHWM(1);
//
// if (!keepAlive) return;
//
// keepAlivePing = new Runnable() {
// @Override
// public void run() {
// sendKeepAlivePing();
// }
// };
//
// ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// executor.scheduleAtFixedRate(keepAlivePing, 1, 5, TimeUnit.SECONDS);
// }
//
// void CloseSocket(){
// APIClient.ZContext.destroySocket(socket);
// }
//
// synchronized <T extends MessageLite> T SendMessage(MessageLite msg, Parser<T> parser) throws TimeoutException {
//
// APILogger.zmq("send begin");
// long timestamp = System.nanoTime();
// socket.send(msg.toByteArray());
// byte[] responseBytes = socket.recv();
// APILogger.zmq("recv end - " + (System.nanoTime() - timestamp) / 1000000.0);
//
// if (responseBytes != null){
// try {
// T response = parser.parseFrom(responseBytes);
// return response;
// } catch (InvalidProtocolBufferException e) {
// // whoops
// }
// }
//
// APILogger.zmq("timeout");
// APIClient.ZContext.destroySocket(socket);
// throw new TimeoutException();
// }
//
// public abstract void disconnect();
//
// public synchronized boolean sendKeepAlivePing(){
// boolean error = false;
// APILogger.zmq("ping begin: ");
// error = error || !socket.send(keepAlivePacket);
// error = error || socket.recv() == null;
// APILogger.zmq("ping end - error: " + error);
//
// return !error;
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/VRidgeApiProxy.java
// public interface VRidgeApiProxy {
// void disconnect();
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/RemoteBase.java
import com.riftcat.vridge.api.client.java.proxy.ClientProxyBase;
import com.riftcat.vridge.api.client.java.proxy.VRidgeApiProxy;
package com.riftcat.vridge.api.client.java.remotes;
class RemoteBase {
private boolean isDisposed; | private VRidgeApiProxy proxy; |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/BroadcastProxy.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/APIClient.java
// public class APIClient {
//
// public final static int HEADTRACKING = 0;
// public final static int CONTROLLER = 1;
// public final static int BROADCASTS = 2;
//
// public static ZContext ZContext;
//
// private HashMap<Integer, VRidgeApiProxy> proxies;
// private String serverAddress = "tcp://localhost";
//
// // Connections with same app name will not result in "endpoint in use" response
// private String appName = "";
//
// public APIClient(String appName){
// ZContext = new ZContext(4);
// proxies = new HashMap<Integer, VRidgeApiProxy>();
//
// this.appName = appName;
// }
//
// public APIClient(String ip, String appName){
// this(appName);
// serverAddress = ip;
// }
//
// /// <summary>
// /// Sends control request to see what APIs are available.
// /// May return null if control connection dies (automatic reconnect will follow).
// /// </summary>
// public APIStatus GetStatus() throws Exception {
//
// ZMQ.Socket controlSocket = createControlSocket();
// if (controlSocket == null)
// {
// return null;
// }
//
// SocketHelpers.SendAsJson(controlSocket, new ControlRequestHeader(ControlRequestCode.RequestStatus));
// APIStatus status = SocketHelpers.ReceiveByJson(controlSocket, APIStatus.class);
// APIClient.ZContext.destroySocket(controlSocket);
//
// if (status != null){
// return status;
// }
//
// throw new Exception("Could not read API status.");
// }
//
// public <T extends VRidgeApiProxy> T getProxy(int proxyType) throws Exception {
//
// VRidgeApiProxy proxy = proxies.get(proxyType);
// ZMQ.Socket controlSocket = createControlSocket();
//
// if(proxy == null){
//
// String endpointName = null;
// switch (proxyType)
// {
// case HEADTRACKING:
// endpointName = EndpointNames.HeadTracking;
// break;
// case CONTROLLER:
// endpointName = EndpointNames.Controller;
// break;
// case BROADCASTS:
// endpointName = EndpointNames.Broadcast;
// break;
// }
//
// if(endpointName == null){{
// throw new IllegalArgumentException("Invalid proxy type was requested.");
// }}
//
// SocketHelpers.SendAsJson(controlSocket, new RequestEndpoint(endpointName, appName));
// EndpointCreated response = SocketHelpers.ReceiveByJson(controlSocket, EndpointCreated.class);
// APIClient.ZContext.destroySocket(controlSocket);
//
// if(response == null ){
// throw new TimeoutException("API server timeout");
// }
//
// if(response.Code == ControlResponseCode.InUse){
// throw new Exception("API endpoint in use.");
// }
//
// switch (proxyType){
// case HEADTRACKING:
// proxies.put(proxyType, new HeadTrackingProxy("tcp://" + serverAddress + ":" + response.Port, true));
// break;
// case CONTROLLER:
// proxies.put(proxyType, new ControllerProxy("tcp://" + serverAddress + ":" + response.Port));
// break;
// case BROADCASTS:
// proxies.put(proxyType, new BroadcastProxy("tcp://" + serverAddress + ":" + response.Port));
// break;
// }
// }
//
// return (T) proxies.get(proxyType);
// }
//
// public void disconnectProxy(int proxyType)
// {
// VRidgeApiProxy proxy = proxies.get(proxyType);
//
// if (proxy == null) return;
//
// proxy.disconnect();
// proxies.put(proxyType, null);
// }
//
// public void disconnectAll() {
// for(int proxyId : proxies.keySet()){
// disconnectProxy(proxyId);
// }
// }
//
// private String getEndpointAddress() {
//
// return "tcp://" + serverAddress + ":38219";
// }
//
// private ZMQ.Socket createControlSocket(){
// String ctrlAddress = getEndpointAddress();
//
// ZMQ.Socket controlSocket = ZContext.createSocket(ZMQ.REQ);
// controlSocket.connect(ctrlAddress);
// controlSocket.setSendTimeOut(1000);
// controlSocket.setReceiveTimeOut(1000);
// return controlSocket;
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
| import com.google.protobuf.InvalidProtocolBufferException;
import com.riftcat.vridge.api.client.java.APIClient;
import com.riftcat.vridge.api.client.java.proto.HapticPulse;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import org.zeromq.ZMQ;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List; | package com.riftcat.vridge.api.client.java.proxy;
public class BroadcastProxy implements VRidgeApiProxy {
private final String endpointAddr;
private ZMQ.Socket socket;
private List<IBroadcastListener> listeners = new LinkedList<IBroadcastListener>();
private Thread threadPolling;
public BroadcastProxy(String endpointAddr){
this.endpointAddr = endpointAddr;
}
public void startPolling(){
if(threadPolling != null) threadPolling.interrupt();
threadPolling = new Thread(new Runnable() {
@Override
public void run() {
| // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/APIClient.java
// public class APIClient {
//
// public final static int HEADTRACKING = 0;
// public final static int CONTROLLER = 1;
// public final static int BROADCASTS = 2;
//
// public static ZContext ZContext;
//
// private HashMap<Integer, VRidgeApiProxy> proxies;
// private String serverAddress = "tcp://localhost";
//
// // Connections with same app name will not result in "endpoint in use" response
// private String appName = "";
//
// public APIClient(String appName){
// ZContext = new ZContext(4);
// proxies = new HashMap<Integer, VRidgeApiProxy>();
//
// this.appName = appName;
// }
//
// public APIClient(String ip, String appName){
// this(appName);
// serverAddress = ip;
// }
//
// /// <summary>
// /// Sends control request to see what APIs are available.
// /// May return null if control connection dies (automatic reconnect will follow).
// /// </summary>
// public APIStatus GetStatus() throws Exception {
//
// ZMQ.Socket controlSocket = createControlSocket();
// if (controlSocket == null)
// {
// return null;
// }
//
// SocketHelpers.SendAsJson(controlSocket, new ControlRequestHeader(ControlRequestCode.RequestStatus));
// APIStatus status = SocketHelpers.ReceiveByJson(controlSocket, APIStatus.class);
// APIClient.ZContext.destroySocket(controlSocket);
//
// if (status != null){
// return status;
// }
//
// throw new Exception("Could not read API status.");
// }
//
// public <T extends VRidgeApiProxy> T getProxy(int proxyType) throws Exception {
//
// VRidgeApiProxy proxy = proxies.get(proxyType);
// ZMQ.Socket controlSocket = createControlSocket();
//
// if(proxy == null){
//
// String endpointName = null;
// switch (proxyType)
// {
// case HEADTRACKING:
// endpointName = EndpointNames.HeadTracking;
// break;
// case CONTROLLER:
// endpointName = EndpointNames.Controller;
// break;
// case BROADCASTS:
// endpointName = EndpointNames.Broadcast;
// break;
// }
//
// if(endpointName == null){{
// throw new IllegalArgumentException("Invalid proxy type was requested.");
// }}
//
// SocketHelpers.SendAsJson(controlSocket, new RequestEndpoint(endpointName, appName));
// EndpointCreated response = SocketHelpers.ReceiveByJson(controlSocket, EndpointCreated.class);
// APIClient.ZContext.destroySocket(controlSocket);
//
// if(response == null ){
// throw new TimeoutException("API server timeout");
// }
//
// if(response.Code == ControlResponseCode.InUse){
// throw new Exception("API endpoint in use.");
// }
//
// switch (proxyType){
// case HEADTRACKING:
// proxies.put(proxyType, new HeadTrackingProxy("tcp://" + serverAddress + ":" + response.Port, true));
// break;
// case CONTROLLER:
// proxies.put(proxyType, new ControllerProxy("tcp://" + serverAddress + ":" + response.Port));
// break;
// case BROADCASTS:
// proxies.put(proxyType, new BroadcastProxy("tcp://" + serverAddress + ":" + response.Port));
// break;
// }
// }
//
// return (T) proxies.get(proxyType);
// }
//
// public void disconnectProxy(int proxyType)
// {
// VRidgeApiProxy proxy = proxies.get(proxyType);
//
// if (proxy == null) return;
//
// proxy.disconnect();
// proxies.put(proxyType, null);
// }
//
// public void disconnectAll() {
// for(int proxyId : proxies.keySet()){
// disconnectProxy(proxyId);
// }
// }
//
// private String getEndpointAddress() {
//
// return "tcp://" + serverAddress + ":38219";
// }
//
// private ZMQ.Socket createControlSocket(){
// String ctrlAddress = getEndpointAddress();
//
// ZMQ.Socket controlSocket = ZContext.createSocket(ZMQ.REQ);
// controlSocket.connect(ctrlAddress);
// controlSocket.setSendTimeOut(1000);
// controlSocket.setReceiveTimeOut(1000);
// return controlSocket;
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/BroadcastProxy.java
import com.google.protobuf.InvalidProtocolBufferException;
import com.riftcat.vridge.api.client.java.APIClient;
import com.riftcat.vridge.api.client.java.proto.HapticPulse;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import org.zeromq.ZMQ;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
package com.riftcat.vridge.api.client.java.proxy;
public class BroadcastProxy implements VRidgeApiProxy {
private final String endpointAddr;
private ZMQ.Socket socket;
private List<IBroadcastListener> listeners = new LinkedList<IBroadcastListener>();
private Thread threadPolling;
public BroadcastProxy(String endpointAddr){
this.endpointAddr = endpointAddr;
}
public void startPolling(){
if(threadPolling != null) threadPolling.interrupt();
threadPolling = new Thread(new Runnable() {
@Override
public void run() {
| socket = APIClient.ZContext.createSocket(ZMQ.SUB); |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/DiscoveryClient.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/beacons/VridgeServerBeacon.java
// public class VridgeServerBeacon {
// private static long timeoutMs = 5000;
//
// private Beacon beacon;
// private InetAddress endpoint;
// private long timestmapMs;
//
// public VridgeServerBeacon(Beacon beacon, InetAddress endpoint) {
// this.beacon = beacon;
// this.endpoint = endpoint;
// timestmapMs = System.currentTimeMillis();
// }
//
// public Beacon getBeacon() {
// return beacon;
// }
//
// public InetAddress getEndpoint() {
// return endpoint;
// }
//
// public boolean isFresh(){
// return timestmapMs + timeoutMs > System.currentTimeMillis();
// }
//
// @Override
// public String toString() {
// return beacon.getRole() + "|" +
// beacon.getHumanReadableVersion() + "|" +
// beacon.getMachineName() + "|" +
// beacon.getUserName() + "@" +
// endpoint.getHostAddress();
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/beacons/VridgeServerBeaconList.java
// public class VridgeServerBeaconList {
// private HashMap<InetAddress, VridgeServerBeacon> timedList = new HashMap<InetAddress, VridgeServerBeacon>();
//
// public synchronized void add(Beacon beacon, InetAddress endpoint){
// if(timedList.containsKey(endpoint)){
// timedList.remove(endpoint);
// }
//
// timedList.put(endpoint, new VridgeServerBeacon(beacon, endpoint));
// }
//
// public synchronized List<VridgeServerBeacon> getFreshServers(){
// LinkedList<VridgeServerBeacon> beacons = new LinkedList<VridgeServerBeacon>();
// for (VridgeServerBeacon vridgeServerBeacon : timedList.values()) {
// if(vridgeServerBeacon.isFresh()){
// beacons.add(vridgeServerBeacon);
// }
// }
//
// return beacons;
// }
// }
| import com.google.protobuf.InvalidProtocolBufferException;
import com.riftcat.vridge.api.client.java.proto.Beacon;
import com.riftcat.vridge.api.client.java.proto.BeaconOrigin;
import com.riftcat.vridge.api.client.java.remotes.beacons.VridgeServerBeacon;
import com.riftcat.vridge.api.client.java.remotes.beacons.VridgeServerBeaconList;
import org.zeromq.ZBeacon;
import java.net.InetAddress;
import java.util.List; | package com.riftcat.vridge.api.client.java.remotes;
class DiscoveryClient implements Thread.UncaughtExceptionHandler {
private final byte[] identity; | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/beacons/VridgeServerBeacon.java
// public class VridgeServerBeacon {
// private static long timeoutMs = 5000;
//
// private Beacon beacon;
// private InetAddress endpoint;
// private long timestmapMs;
//
// public VridgeServerBeacon(Beacon beacon, InetAddress endpoint) {
// this.beacon = beacon;
// this.endpoint = endpoint;
// timestmapMs = System.currentTimeMillis();
// }
//
// public Beacon getBeacon() {
// return beacon;
// }
//
// public InetAddress getEndpoint() {
// return endpoint;
// }
//
// public boolean isFresh(){
// return timestmapMs + timeoutMs > System.currentTimeMillis();
// }
//
// @Override
// public String toString() {
// return beacon.getRole() + "|" +
// beacon.getHumanReadableVersion() + "|" +
// beacon.getMachineName() + "|" +
// beacon.getUserName() + "@" +
// endpoint.getHostAddress();
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/beacons/VridgeServerBeaconList.java
// public class VridgeServerBeaconList {
// private HashMap<InetAddress, VridgeServerBeacon> timedList = new HashMap<InetAddress, VridgeServerBeacon>();
//
// public synchronized void add(Beacon beacon, InetAddress endpoint){
// if(timedList.containsKey(endpoint)){
// timedList.remove(endpoint);
// }
//
// timedList.put(endpoint, new VridgeServerBeacon(beacon, endpoint));
// }
//
// public synchronized List<VridgeServerBeacon> getFreshServers(){
// LinkedList<VridgeServerBeacon> beacons = new LinkedList<VridgeServerBeacon>();
// for (VridgeServerBeacon vridgeServerBeacon : timedList.values()) {
// if(vridgeServerBeacon.isFresh()){
// beacons.add(vridgeServerBeacon);
// }
// }
//
// return beacons;
// }
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/DiscoveryClient.java
import com.google.protobuf.InvalidProtocolBufferException;
import com.riftcat.vridge.api.client.java.proto.Beacon;
import com.riftcat.vridge.api.client.java.proto.BeaconOrigin;
import com.riftcat.vridge.api.client.java.remotes.beacons.VridgeServerBeacon;
import com.riftcat.vridge.api.client.java.remotes.beacons.VridgeServerBeaconList;
import org.zeromq.ZBeacon;
import java.net.InetAddress;
import java.util.List;
package com.riftcat.vridge.api.client.java.remotes;
class DiscoveryClient implements Thread.UncaughtExceptionHandler {
private final byte[] identity; | private VridgeServerBeaconList beaconList; |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/DiscoveryClient.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/beacons/VridgeServerBeacon.java
// public class VridgeServerBeacon {
// private static long timeoutMs = 5000;
//
// private Beacon beacon;
// private InetAddress endpoint;
// private long timestmapMs;
//
// public VridgeServerBeacon(Beacon beacon, InetAddress endpoint) {
// this.beacon = beacon;
// this.endpoint = endpoint;
// timestmapMs = System.currentTimeMillis();
// }
//
// public Beacon getBeacon() {
// return beacon;
// }
//
// public InetAddress getEndpoint() {
// return endpoint;
// }
//
// public boolean isFresh(){
// return timestmapMs + timeoutMs > System.currentTimeMillis();
// }
//
// @Override
// public String toString() {
// return beacon.getRole() + "|" +
// beacon.getHumanReadableVersion() + "|" +
// beacon.getMachineName() + "|" +
// beacon.getUserName() + "@" +
// endpoint.getHostAddress();
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/beacons/VridgeServerBeaconList.java
// public class VridgeServerBeaconList {
// private HashMap<InetAddress, VridgeServerBeacon> timedList = new HashMap<InetAddress, VridgeServerBeacon>();
//
// public synchronized void add(Beacon beacon, InetAddress endpoint){
// if(timedList.containsKey(endpoint)){
// timedList.remove(endpoint);
// }
//
// timedList.put(endpoint, new VridgeServerBeacon(beacon, endpoint));
// }
//
// public synchronized List<VridgeServerBeacon> getFreshServers(){
// LinkedList<VridgeServerBeacon> beacons = new LinkedList<VridgeServerBeacon>();
// for (VridgeServerBeacon vridgeServerBeacon : timedList.values()) {
// if(vridgeServerBeacon.isFresh()){
// beacons.add(vridgeServerBeacon);
// }
// }
//
// return beacons;
// }
// }
| import com.google.protobuf.InvalidProtocolBufferException;
import com.riftcat.vridge.api.client.java.proto.Beacon;
import com.riftcat.vridge.api.client.java.proto.BeaconOrigin;
import com.riftcat.vridge.api.client.java.remotes.beacons.VridgeServerBeacon;
import com.riftcat.vridge.api.client.java.remotes.beacons.VridgeServerBeaconList;
import org.zeromq.ZBeacon;
import java.net.InetAddress;
import java.util.List; | }
public void reset(){
dispose();
beaconClient = new ZBeacon("255.255.255.255",38219, identity, true, true);
beaconClient.setBroadcastInterval(1000);
beaconClient.setListener(new ZBeacon.Listener() {
@Override
public void onBeacon(InetAddress sender, byte[] buffer) {
Beacon beacon;
try {
beacon = Beacon.parser().parseFrom(buffer);
} catch (InvalidProtocolBufferException e) {
// Ignore stray packets
return;
}
if(beacon.getRole() != BeaconOrigin.Server){
// Skip other clients
return;
}
beaconList.add(beacon, sender);
}
});
beaconClient.setUncaughtExceptionHandlers(this, this);
beaconClient.start();
}
| // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/beacons/VridgeServerBeacon.java
// public class VridgeServerBeacon {
// private static long timeoutMs = 5000;
//
// private Beacon beacon;
// private InetAddress endpoint;
// private long timestmapMs;
//
// public VridgeServerBeacon(Beacon beacon, InetAddress endpoint) {
// this.beacon = beacon;
// this.endpoint = endpoint;
// timestmapMs = System.currentTimeMillis();
// }
//
// public Beacon getBeacon() {
// return beacon;
// }
//
// public InetAddress getEndpoint() {
// return endpoint;
// }
//
// public boolean isFresh(){
// return timestmapMs + timeoutMs > System.currentTimeMillis();
// }
//
// @Override
// public String toString() {
// return beacon.getRole() + "|" +
// beacon.getHumanReadableVersion() + "|" +
// beacon.getMachineName() + "|" +
// beacon.getUserName() + "@" +
// endpoint.getHostAddress();
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/beacons/VridgeServerBeaconList.java
// public class VridgeServerBeaconList {
// private HashMap<InetAddress, VridgeServerBeacon> timedList = new HashMap<InetAddress, VridgeServerBeacon>();
//
// public synchronized void add(Beacon beacon, InetAddress endpoint){
// if(timedList.containsKey(endpoint)){
// timedList.remove(endpoint);
// }
//
// timedList.put(endpoint, new VridgeServerBeacon(beacon, endpoint));
// }
//
// public synchronized List<VridgeServerBeacon> getFreshServers(){
// LinkedList<VridgeServerBeacon> beacons = new LinkedList<VridgeServerBeacon>();
// for (VridgeServerBeacon vridgeServerBeacon : timedList.values()) {
// if(vridgeServerBeacon.isFresh()){
// beacons.add(vridgeServerBeacon);
// }
// }
//
// return beacons;
// }
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/DiscoveryClient.java
import com.google.protobuf.InvalidProtocolBufferException;
import com.riftcat.vridge.api.client.java.proto.Beacon;
import com.riftcat.vridge.api.client.java.proto.BeaconOrigin;
import com.riftcat.vridge.api.client.java.remotes.beacons.VridgeServerBeacon;
import com.riftcat.vridge.api.client.java.remotes.beacons.VridgeServerBeaconList;
import org.zeromq.ZBeacon;
import java.net.InetAddress;
import java.util.List;
}
public void reset(){
dispose();
beaconClient = new ZBeacon("255.255.255.255",38219, identity, true, true);
beaconClient.setBroadcastInterval(1000);
beaconClient.setListener(new ZBeacon.Listener() {
@Override
public void onBeacon(InetAddress sender, byte[] buffer) {
Beacon beacon;
try {
beacon = Beacon.parser().parseFrom(buffer);
} catch (InvalidProtocolBufferException e) {
// Ignore stray packets
return;
}
if(beacon.getRole() != BeaconOrigin.Server){
// Skip other clients
return;
}
beaconList.add(beacon, sender);
}
});
beaconClient.setUncaughtExceptionHandlers(this, this);
beaconClient.start();
}
| public List<VridgeServerBeacon> getFreshServers() { |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/ControllerProxy.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/ControllerStateRequestCodes.java
// public class ControllerStateRequestCodes {
// public static int Disconnect = 255;
// public static int SendFullState = 1;
// public static int RecenterHead = 2;
//
// public static int Origin_Zero = 0;
//
// }
| import com.riftcat.vridge.api.client.java.codes.ControllerStateRequestCodes;
import com.riftcat.vridge.api.client.java.proto.ControllerStateRequest;
import com.riftcat.vridge.api.client.java.proto.ControllerStateResponse;
import com.riftcat.vridge.api.client.java.proto.HandType;
import com.riftcat.vridge.api.client.java.proto.VRController;
import com.riftcat.vridge.api.client.java.proto.VRControllerAxis_t;
import com.riftcat.vridge.api.client.java.proto.VRControllerState_t;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeoutException; | package com.riftcat.vridge.api.client.java.proxy;
public class ControllerProxy extends ClientProxyBase {
private int packetNum = 0;
public ControllerProxy(String endpointAddress){
super(endpointAddress, true);
}
/// <summary>
/// Send full single VR controller state to VR.
/// </summary>
public synchronized void sendControllerState(VRController state) throws TimeoutException {
ControllerStateRequest data = ControllerStateRequest
.newBuilder() | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/codes/ControllerStateRequestCodes.java
// public class ControllerStateRequestCodes {
// public static int Disconnect = 255;
// public static int SendFullState = 1;
// public static int RecenterHead = 2;
//
// public static int Origin_Zero = 0;
//
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/ControllerProxy.java
import com.riftcat.vridge.api.client.java.codes.ControllerStateRequestCodes;
import com.riftcat.vridge.api.client.java.proto.ControllerStateRequest;
import com.riftcat.vridge.api.client.java.proto.ControllerStateResponse;
import com.riftcat.vridge.api.client.java.proto.HandType;
import com.riftcat.vridge.api.client.java.proto.VRController;
import com.riftcat.vridge.api.client.java.proto.VRControllerAxis_t;
import com.riftcat.vridge.api.client.java.proto.VRControllerState_t;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeoutException;
package com.riftcat.vridge.api.client.java.proxy;
public class ControllerProxy extends ClientProxyBase {
private int packetNum = 0;
public ControllerProxy(String endpointAddress){
super(endpointAddress, true);
}
/// <summary>
/// Send full single VR controller state to VR.
/// </summary>
public synchronized void sendControllerState(VRController state) throws TimeoutException {
ControllerStateRequest data = ControllerStateRequest
.newBuilder() | .setTaskType(ControllerStateRequestCodes.SendFullState) |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/responses/EndpointStatus.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/ControlResponseCode.java
// public class ControlResponseCode {
//
// /// <summary>
// /// API awaits connection at given endpoint.
// /// </summary>
// public static int OK = 0;
//
// /// <summary>
// /// API is not available because of undefined reason.
// /// </summary>
// public static int NotAvailable = 1;
//
// /// <summary>
// /// API is in use by another client
// /// </summary>
// public static int InUse = 2;
//
// /// <summary>
// /// Client is trying to use something that requires API client to be updated to more recent version
// /// </summary>
// public static int ClientOutdated = 3;
//
// /// <summary>
// /// VRidge needs to be updated or client is not following protocol
// /// </summary>
// public static int ServerOutdated = 4;
//
// }
| import com.riftcat.vridge.api.client.java.control.ControlResponseCode; | package com.riftcat.vridge.api.client.java.control.responses;
public class EndpointStatus extends ControlResponseHeader {
public String Name;
public String InUseBy;
public EndpointStatus(String endpointName){ | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/ControlResponseCode.java
// public class ControlResponseCode {
//
// /// <summary>
// /// API awaits connection at given endpoint.
// /// </summary>
// public static int OK = 0;
//
// /// <summary>
// /// API is not available because of undefined reason.
// /// </summary>
// public static int NotAvailable = 1;
//
// /// <summary>
// /// API is in use by another client
// /// </summary>
// public static int InUse = 2;
//
// /// <summary>
// /// Client is trying to use something that requires API client to be updated to more recent version
// /// </summary>
// public static int ClientOutdated = 3;
//
// /// <summary>
// /// VRidge needs to be updated or client is not following protocol
// /// </summary>
// public static int ServerOutdated = 4;
//
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/responses/EndpointStatus.java
import com.riftcat.vridge.api.client.java.control.ControlResponseCode;
package com.riftcat.vridge.api.client.java.control.responses;
public class EndpointStatus extends ControlResponseHeader {
public String Name;
public String InUseBy;
public EndpointStatus(String endpointName){ | this.Code = ControlResponseCode.OK; |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/ControllerRemote.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/ControllerProxy.java
// public class ControllerProxy extends ClientProxyBase {
//
// private int packetNum = 0;
//
// public ControllerProxy(String endpointAddress){
// super(endpointAddress, true);
// }
//
// /// <summary>
// /// Send full single VR controller state to VR.
// /// </summary>
// public synchronized void sendControllerState(VRController state) throws TimeoutException {
// ControllerStateRequest data = ControllerStateRequest
// .newBuilder()
// .setTaskType(ControllerStateRequestCodes.SendFullState)
// .setControllerState(state)
// .build();
//
// sendMessage(data);
// }
//
// /**
// * Send full single VR controller state to VR.
// */
// public synchronized void sendControllerState(int controllerId, long touchedMask, long pressedMask,
// List<Float> orientationMatrix,
// float triggerValue,
// float analogX, float analogY, float[] velocity,
// HandType hand) throws TimeoutException {
//
// VRControllerState_t.Builder buttonState = VRControllerState_t.newBuilder()
// .setRAxis0(VRControllerAxis_t.newBuilder()
// .setX(analogX)
// .setY(analogY))
// .setRAxis1(VRControllerAxis_t.newBuilder()
// .setX(triggerValue))
// .setUlButtonPressed(pressedMask)
// .setUlButtonTouched(touchedMask)
// .setUnPacketNum(++packetNum);
//
//
//
// VRController.Builder controllerState = VRController.newBuilder()
// .setControllerId(controllerId)
// .addAllOrientationMatrix(orientationMatrix)
// .setStatus(0)
// .setSuggestedHand(hand)
// .setButtonState(buttonState);
//
// if(velocity != null){
// controllerState
// .addVelocity(velocity[0])
// .addVelocity(velocity[1])
// .addVelocity(velocity[2]);
// }
//
// ControllerStateRequest request = ControllerStateRequest.newBuilder()
// .setTaskType(ControllerStateRequestCodes.SendFullState)
// .setControllerState(controllerState)
// .build();
//
// sendMessage(request);
// }
//
// /** Recenter head tracking. Works the same as pressing recenter hotkey as configured in VRidge settings. */
// public void recenterHead() throws TimeoutException{
// ControllerStateRequest request = ControllerStateRequest
// .newBuilder()
// .setVersion(CurrentVersion)
// .setTaskType(ControllerStateRequestCodes.RecenterHead)
// .build();
// sendMessage(request);
// }
//
// /**
// * Disconnected from controller API and frees the API for other clients.
// */
// public void disconnect(){
// ControllerStateRequest disconnectRequest = ControllerStateRequest
// .newBuilder()
// .setVersion(CurrentVersion)
// .setTaskType(ControllerStateRequestCodes.Disconnect)
// .build();
//
// try{
// sendMessage(disconnectRequest);
// }
// catch (Exception x){
// // ignored
// }
// CloseSocket();
// }
//
// private ControllerStateResponse sendMessage(ControllerStateRequest req) throws TimeoutException {
// return SendMessage(req, ControllerStateResponse.parser());
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/ButtonMask.java
// public class ButtonMask{
// private static int k_EButton_System = 0;
// private static int k_EButton_ApplicationMenu = 1;
// private static int k_EButton_Grip = 2;
// private static int k_EButton_DPad_Left = 3;
// private static int k_EButton_DPad_Up = 4;
// private static int k_EButton_DPad_Right = 5;
// private static int k_EButton_DPad_Down = 6;
// private static int k_EButton_A = 7;
//
// private static int k_EButton_ProximitySensor = 31;
//
// private static int k_EButton_Axis0 = 32;
// private static int k_EButton_Axis1 = 33;
// private static int k_EButton_Axis2 = 34;
// private static int k_EButton_Axis3 = 35;
// private static int k_EButton_Axis4 = 36;
//
// // aliases for well known controllers
// private static int k_EButton_SteamVR_Touchpad = k_EButton_Axis0;
// private static int k_EButton_SteamVR_Trigger = k_EButton_Axis1;
// private static int k_EButton_Dashboard_Back = k_EButton_Grip;
// private static int k_EButton_Max = 64;
//
// public static long System = (1L << (int)k_EButton_System);
// public static long ApplicationMenu = (1L << (int)k_EButton_ApplicationMenu);
// public static long Grip = (1L << (int)k_EButton_Grip);
// public static long Axis0 = (1L << (int)k_EButton_Axis0);
// public static long Axis1 = (1L << (int)k_EButton_Axis1);
// public static long Axis2 = (1L << (int)k_EButton_Axis2);
// public static long Axis3 = (1L << (int)k_EButton_Axis3);
// public static long Axis4 = (1L << (int)k_EButton_Axis4);
// public static long Touchpad = (1L << (int)k_EButton_SteamVR_Touchpad);
// public static long Trigger = (1L << (int)k_EButton_SteamVR_Trigger);
// }
| import com.riftcat.vridge.api.client.java.proto.HandType;
import com.riftcat.vridge.api.client.java.proto.HeadRelation;
import com.riftcat.vridge.api.client.java.proto.VRController;
import com.riftcat.vridge.api.client.java.proto.VRControllerAxis_t;
import com.riftcat.vridge.api.client.java.proto.VRControllerState_t;
import com.riftcat.vridge.api.client.java.proto.VRControllerState_tOrBuilder;
import com.riftcat.vridge.api.client.java.proxy.ControllerProxy;
import com.riftcat.vridge.api.client.java.utils.ButtonMask;
import java.util.concurrent.TimeoutException; | package com.riftcat.vridge.api.client.java.remotes;
public class ControllerRemote extends RemoteBase {
private static int packetNum = 0; | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/ControllerProxy.java
// public class ControllerProxy extends ClientProxyBase {
//
// private int packetNum = 0;
//
// public ControllerProxy(String endpointAddress){
// super(endpointAddress, true);
// }
//
// /// <summary>
// /// Send full single VR controller state to VR.
// /// </summary>
// public synchronized void sendControllerState(VRController state) throws TimeoutException {
// ControllerStateRequest data = ControllerStateRequest
// .newBuilder()
// .setTaskType(ControllerStateRequestCodes.SendFullState)
// .setControllerState(state)
// .build();
//
// sendMessage(data);
// }
//
// /**
// * Send full single VR controller state to VR.
// */
// public synchronized void sendControllerState(int controllerId, long touchedMask, long pressedMask,
// List<Float> orientationMatrix,
// float triggerValue,
// float analogX, float analogY, float[] velocity,
// HandType hand) throws TimeoutException {
//
// VRControllerState_t.Builder buttonState = VRControllerState_t.newBuilder()
// .setRAxis0(VRControllerAxis_t.newBuilder()
// .setX(analogX)
// .setY(analogY))
// .setRAxis1(VRControllerAxis_t.newBuilder()
// .setX(triggerValue))
// .setUlButtonPressed(pressedMask)
// .setUlButtonTouched(touchedMask)
// .setUnPacketNum(++packetNum);
//
//
//
// VRController.Builder controllerState = VRController.newBuilder()
// .setControllerId(controllerId)
// .addAllOrientationMatrix(orientationMatrix)
// .setStatus(0)
// .setSuggestedHand(hand)
// .setButtonState(buttonState);
//
// if(velocity != null){
// controllerState
// .addVelocity(velocity[0])
// .addVelocity(velocity[1])
// .addVelocity(velocity[2]);
// }
//
// ControllerStateRequest request = ControllerStateRequest.newBuilder()
// .setTaskType(ControllerStateRequestCodes.SendFullState)
// .setControllerState(controllerState)
// .build();
//
// sendMessage(request);
// }
//
// /** Recenter head tracking. Works the same as pressing recenter hotkey as configured in VRidge settings. */
// public void recenterHead() throws TimeoutException{
// ControllerStateRequest request = ControllerStateRequest
// .newBuilder()
// .setVersion(CurrentVersion)
// .setTaskType(ControllerStateRequestCodes.RecenterHead)
// .build();
// sendMessage(request);
// }
//
// /**
// * Disconnected from controller API and frees the API for other clients.
// */
// public void disconnect(){
// ControllerStateRequest disconnectRequest = ControllerStateRequest
// .newBuilder()
// .setVersion(CurrentVersion)
// .setTaskType(ControllerStateRequestCodes.Disconnect)
// .build();
//
// try{
// sendMessage(disconnectRequest);
// }
// catch (Exception x){
// // ignored
// }
// CloseSocket();
// }
//
// private ControllerStateResponse sendMessage(ControllerStateRequest req) throws TimeoutException {
// return SendMessage(req, ControllerStateResponse.parser());
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/ButtonMask.java
// public class ButtonMask{
// private static int k_EButton_System = 0;
// private static int k_EButton_ApplicationMenu = 1;
// private static int k_EButton_Grip = 2;
// private static int k_EButton_DPad_Left = 3;
// private static int k_EButton_DPad_Up = 4;
// private static int k_EButton_DPad_Right = 5;
// private static int k_EButton_DPad_Down = 6;
// private static int k_EButton_A = 7;
//
// private static int k_EButton_ProximitySensor = 31;
//
// private static int k_EButton_Axis0 = 32;
// private static int k_EButton_Axis1 = 33;
// private static int k_EButton_Axis2 = 34;
// private static int k_EButton_Axis3 = 35;
// private static int k_EButton_Axis4 = 36;
//
// // aliases for well known controllers
// private static int k_EButton_SteamVR_Touchpad = k_EButton_Axis0;
// private static int k_EButton_SteamVR_Trigger = k_EButton_Axis1;
// private static int k_EButton_Dashboard_Back = k_EButton_Grip;
// private static int k_EButton_Max = 64;
//
// public static long System = (1L << (int)k_EButton_System);
// public static long ApplicationMenu = (1L << (int)k_EButton_ApplicationMenu);
// public static long Grip = (1L << (int)k_EButton_Grip);
// public static long Axis0 = (1L << (int)k_EButton_Axis0);
// public static long Axis1 = (1L << (int)k_EButton_Axis1);
// public static long Axis2 = (1L << (int)k_EButton_Axis2);
// public static long Axis3 = (1L << (int)k_EButton_Axis3);
// public static long Axis4 = (1L << (int)k_EButton_Axis4);
// public static long Touchpad = (1L << (int)k_EButton_SteamVR_Touchpad);
// public static long Trigger = (1L << (int)k_EButton_SteamVR_Trigger);
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/remotes/ControllerRemote.java
import com.riftcat.vridge.api.client.java.proto.HandType;
import com.riftcat.vridge.api.client.java.proto.HeadRelation;
import com.riftcat.vridge.api.client.java.proto.VRController;
import com.riftcat.vridge.api.client.java.proto.VRControllerAxis_t;
import com.riftcat.vridge.api.client.java.proto.VRControllerState_t;
import com.riftcat.vridge.api.client.java.proto.VRControllerState_tOrBuilder;
import com.riftcat.vridge.api.client.java.proxy.ControllerProxy;
import com.riftcat.vridge.api.client.java.utils.ButtonMask;
import java.util.concurrent.TimeoutException;
package com.riftcat.vridge.api.client.java.remotes;
public class ControllerRemote extends RemoteBase {
private static int packetNum = 0; | private ControllerProxy proxy; |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/ClientProxyBase.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/APIClient.java
// public class APIClient {
//
// public final static int HEADTRACKING = 0;
// public final static int CONTROLLER = 1;
// public final static int BROADCASTS = 2;
//
// public static ZContext ZContext;
//
// private HashMap<Integer, VRidgeApiProxy> proxies;
// private String serverAddress = "tcp://localhost";
//
// // Connections with same app name will not result in "endpoint in use" response
// private String appName = "";
//
// public APIClient(String appName){
// ZContext = new ZContext(4);
// proxies = new HashMap<Integer, VRidgeApiProxy>();
//
// this.appName = appName;
// }
//
// public APIClient(String ip, String appName){
// this(appName);
// serverAddress = ip;
// }
//
// /// <summary>
// /// Sends control request to see what APIs are available.
// /// May return null if control connection dies (automatic reconnect will follow).
// /// </summary>
// public APIStatus GetStatus() throws Exception {
//
// ZMQ.Socket controlSocket = createControlSocket();
// if (controlSocket == null)
// {
// return null;
// }
//
// SocketHelpers.SendAsJson(controlSocket, new ControlRequestHeader(ControlRequestCode.RequestStatus));
// APIStatus status = SocketHelpers.ReceiveByJson(controlSocket, APIStatus.class);
// APIClient.ZContext.destroySocket(controlSocket);
//
// if (status != null){
// return status;
// }
//
// throw new Exception("Could not read API status.");
// }
//
// public <T extends VRidgeApiProxy> T getProxy(int proxyType) throws Exception {
//
// VRidgeApiProxy proxy = proxies.get(proxyType);
// ZMQ.Socket controlSocket = createControlSocket();
//
// if(proxy == null){
//
// String endpointName = null;
// switch (proxyType)
// {
// case HEADTRACKING:
// endpointName = EndpointNames.HeadTracking;
// break;
// case CONTROLLER:
// endpointName = EndpointNames.Controller;
// break;
// case BROADCASTS:
// endpointName = EndpointNames.Broadcast;
// break;
// }
//
// if(endpointName == null){{
// throw new IllegalArgumentException("Invalid proxy type was requested.");
// }}
//
// SocketHelpers.SendAsJson(controlSocket, new RequestEndpoint(endpointName, appName));
// EndpointCreated response = SocketHelpers.ReceiveByJson(controlSocket, EndpointCreated.class);
// APIClient.ZContext.destroySocket(controlSocket);
//
// if(response == null ){
// throw new TimeoutException("API server timeout");
// }
//
// if(response.Code == ControlResponseCode.InUse){
// throw new Exception("API endpoint in use.");
// }
//
// switch (proxyType){
// case HEADTRACKING:
// proxies.put(proxyType, new HeadTrackingProxy("tcp://" + serverAddress + ":" + response.Port, true));
// break;
// case CONTROLLER:
// proxies.put(proxyType, new ControllerProxy("tcp://" + serverAddress + ":" + response.Port));
// break;
// case BROADCASTS:
// proxies.put(proxyType, new BroadcastProxy("tcp://" + serverAddress + ":" + response.Port));
// break;
// }
// }
//
// return (T) proxies.get(proxyType);
// }
//
// public void disconnectProxy(int proxyType)
// {
// VRidgeApiProxy proxy = proxies.get(proxyType);
//
// if (proxy == null) return;
//
// proxy.disconnect();
// proxies.put(proxyType, null);
// }
//
// public void disconnectAll() {
// for(int proxyId : proxies.keySet()){
// disconnectProxy(proxyId);
// }
// }
//
// private String getEndpointAddress() {
//
// return "tcp://" + serverAddress + ":38219";
// }
//
// private ZMQ.Socket createControlSocket(){
// String ctrlAddress = getEndpointAddress();
//
// ZMQ.Socket controlSocket = ZContext.createSocket(ZMQ.REQ);
// controlSocket.connect(ctrlAddress);
// controlSocket.setSendTimeOut(1000);
// controlSocket.setReceiveTimeOut(1000);
// return controlSocket;
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
| import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageLite;
import com.google.protobuf.Parser;
import com.riftcat.vridge.api.client.java.APIClient;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; | package com.riftcat.vridge.api.client.java.proxy;
public abstract class ClientProxyBase implements VRidgeApiProxy{
private TimerTask keepAliveTimer;
private Runnable keepAlivePing;
private byte[] keepAlivePacket = { 0 };
int CurrentVersion = 3;
ZMQ.Socket socket;
ClientProxyBase(String endpointAddress, boolean keepAlive){
| // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/APIClient.java
// public class APIClient {
//
// public final static int HEADTRACKING = 0;
// public final static int CONTROLLER = 1;
// public final static int BROADCASTS = 2;
//
// public static ZContext ZContext;
//
// private HashMap<Integer, VRidgeApiProxy> proxies;
// private String serverAddress = "tcp://localhost";
//
// // Connections with same app name will not result in "endpoint in use" response
// private String appName = "";
//
// public APIClient(String appName){
// ZContext = new ZContext(4);
// proxies = new HashMap<Integer, VRidgeApiProxy>();
//
// this.appName = appName;
// }
//
// public APIClient(String ip, String appName){
// this(appName);
// serverAddress = ip;
// }
//
// /// <summary>
// /// Sends control request to see what APIs are available.
// /// May return null if control connection dies (automatic reconnect will follow).
// /// </summary>
// public APIStatus GetStatus() throws Exception {
//
// ZMQ.Socket controlSocket = createControlSocket();
// if (controlSocket == null)
// {
// return null;
// }
//
// SocketHelpers.SendAsJson(controlSocket, new ControlRequestHeader(ControlRequestCode.RequestStatus));
// APIStatus status = SocketHelpers.ReceiveByJson(controlSocket, APIStatus.class);
// APIClient.ZContext.destroySocket(controlSocket);
//
// if (status != null){
// return status;
// }
//
// throw new Exception("Could not read API status.");
// }
//
// public <T extends VRidgeApiProxy> T getProxy(int proxyType) throws Exception {
//
// VRidgeApiProxy proxy = proxies.get(proxyType);
// ZMQ.Socket controlSocket = createControlSocket();
//
// if(proxy == null){
//
// String endpointName = null;
// switch (proxyType)
// {
// case HEADTRACKING:
// endpointName = EndpointNames.HeadTracking;
// break;
// case CONTROLLER:
// endpointName = EndpointNames.Controller;
// break;
// case BROADCASTS:
// endpointName = EndpointNames.Broadcast;
// break;
// }
//
// if(endpointName == null){{
// throw new IllegalArgumentException("Invalid proxy type was requested.");
// }}
//
// SocketHelpers.SendAsJson(controlSocket, new RequestEndpoint(endpointName, appName));
// EndpointCreated response = SocketHelpers.ReceiveByJson(controlSocket, EndpointCreated.class);
// APIClient.ZContext.destroySocket(controlSocket);
//
// if(response == null ){
// throw new TimeoutException("API server timeout");
// }
//
// if(response.Code == ControlResponseCode.InUse){
// throw new Exception("API endpoint in use.");
// }
//
// switch (proxyType){
// case HEADTRACKING:
// proxies.put(proxyType, new HeadTrackingProxy("tcp://" + serverAddress + ":" + response.Port, true));
// break;
// case CONTROLLER:
// proxies.put(proxyType, new ControllerProxy("tcp://" + serverAddress + ":" + response.Port));
// break;
// case BROADCASTS:
// proxies.put(proxyType, new BroadcastProxy("tcp://" + serverAddress + ":" + response.Port));
// break;
// }
// }
//
// return (T) proxies.get(proxyType);
// }
//
// public void disconnectProxy(int proxyType)
// {
// VRidgeApiProxy proxy = proxies.get(proxyType);
//
// if (proxy == null) return;
//
// proxy.disconnect();
// proxies.put(proxyType, null);
// }
//
// public void disconnectAll() {
// for(int proxyId : proxies.keySet()){
// disconnectProxy(proxyId);
// }
// }
//
// private String getEndpointAddress() {
//
// return "tcp://" + serverAddress + ":38219";
// }
//
// private ZMQ.Socket createControlSocket(){
// String ctrlAddress = getEndpointAddress();
//
// ZMQ.Socket controlSocket = ZContext.createSocket(ZMQ.REQ);
// controlSocket.connect(ctrlAddress);
// controlSocket.setSendTimeOut(1000);
// controlSocket.setReceiveTimeOut(1000);
// return controlSocket;
// }
// }
//
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/utils/APILogger.java
// public class APILogger {
//
// private static LinkedList<ILog> loggers = new LinkedList<ILog>();
//
// public static void AddLogListener(ILog logger){
// loggers.add(logger);
// }
//
// public static void debug(String s){
// for (ILog log : loggers) {
// log.debug(s);
// }
// }
//
// public static void zmq(String s) {
// //debug("ZMQ: " + s);
// }
//
// public static void error(String s) {
// for (ILog log : loggers) {
// log.error(s);
// }
// }
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/proxy/ClientProxyBase.java
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageLite;
import com.google.protobuf.Parser;
import com.riftcat.vridge.api.client.java.APIClient;
import com.riftcat.vridge.api.client.java.utils.APILogger;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
package com.riftcat.vridge.api.client.java.proxy;
public abstract class ClientProxyBase implements VRidgeApiProxy{
private TimerTask keepAliveTimer;
private Runnable keepAlivePing;
private byte[] keepAlivePacket = { 0 };
int CurrentVersion = 3;
ZMQ.Socket socket;
ClientProxyBase(String endpointAddress, boolean keepAlive){
| if(APIClient.ZContext == null) APIClient.ZContext = new ZContext(4); |
RiftCat/vridge-api | src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/requests/RequestEndpoint.java | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/ControlRequestCode.java
// public class ControlRequestCode {
//
// public static int RequestEndpoint = 1;
// public static int RequestStatus = 2;
//
// }
| import com.riftcat.vridge.api.client.java.control.ControlRequestCode; | package com.riftcat.vridge.api.client.java.control.requests;
public class RequestEndpoint extends ControlRequestHeader{
public String RequestedEndpointName;
public RequestEndpoint(String name, String appName){
super(appName); | // Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/ControlRequestCode.java
// public class ControlRequestCode {
//
// public static int RequestEndpoint = 1;
// public static int RequestStatus = 2;
//
// }
// Path: src/java/VRE.Vridge.API/VRE.Vridge.API.Client/src/main/java/com/riftcat/vridge/api/client/java/control/requests/RequestEndpoint.java
import com.riftcat.vridge.api.client.java.control.ControlRequestCode;
package com.riftcat.vridge.api.client.java.control.requests;
public class RequestEndpoint extends ControlRequestHeader{
public String RequestedEndpointName;
public RequestEndpoint(String name, String appName){
super(appName); | Code = ControlRequestCode.RequestEndpoint; |
lukasniemeier/gcls | app/src/main/java/de/lukasniemeier/gamecenterlivesender/http/GetHttpTask.java | // Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/utils/Functional.java
// public class Functional {
//
// public interface Procedure {
// void execute();
// }
//
// public interface Consumer<T> {
// void accept(T t);
// }
//
// public interface BiConsumer<R, S> {
// void accept(R r, S s);
// }
//
// public interface Supplier<T> {
// T get();
// }
//
// public interface Function<T, R> {
// R apply(T t);
// }
//
// public interface Predicate<T> {
// boolean test(T t);
// }
// }
| import android.content.Context;
import org.droidparts.net.http.HTTPResponse;
import org.droidparts.net.http.RESTClient2;
import org.joda.time.DateTime;
import de.lukasniemeier.gamecenterlivesender.utils.Functional;
| package de.lukasniemeier.gamecenterlivesender.http;
public class GetHttpTask extends HttpTask {
private final DateTime modifiedSince;
private final boolean asBody;
public GetHttpTask(RESTClient2 restClient,
String url,
DateTime modifiedSince,
Context ctx,
| // Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/utils/Functional.java
// public class Functional {
//
// public interface Procedure {
// void execute();
// }
//
// public interface Consumer<T> {
// void accept(T t);
// }
//
// public interface BiConsumer<R, S> {
// void accept(R r, S s);
// }
//
// public interface Supplier<T> {
// T get();
// }
//
// public interface Function<T, R> {
// R apply(T t);
// }
//
// public interface Predicate<T> {
// boolean test(T t);
// }
// }
// Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/http/GetHttpTask.java
import android.content.Context;
import org.droidparts.net.http.HTTPResponse;
import org.droidparts.net.http.RESTClient2;
import org.joda.time.DateTime;
import de.lukasniemeier.gamecenterlivesender.utils.Functional;
package de.lukasniemeier.gamecenterlivesender.http;
public class GetHttpTask extends HttpTask {
private final DateTime modifiedSince;
private final boolean asBody;
public GetHttpTask(RESTClient2 restClient,
String url,
DateTime modifiedSince,
Context ctx,
| Functional.Consumer<HTTPResponse> successFunction,
|
lukasniemeier/gcls | app/src/main/java/de/lukasniemeier/gamecenterlivesender/http/TaskFactory.java | // Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/model/publishpoint/PublishPointResult.java
// public class PublishPointResult extends Entity {
//
// @XML(tag = "result" + XML.SUB + "path")
// public String path;
//
// public static PublishPointResult parse(String body, Context ctx) throws Exception {
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = factory.newDocumentBuilder();
// Document xml = builder.parse(new InputSource(new StringReader(body)));
//
// XMLSerializer<PublishPointResult> serializer =
// new XMLSerializer<PublishPointResult>(PublishPointResult.class, ctx);
//
// return serializer.deserialize(xml);
// }
// }
//
// Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/utils/Functional.java
// public class Functional {
//
// public interface Procedure {
// void execute();
// }
//
// public interface Consumer<T> {
// void accept(T t);
// }
//
// public interface BiConsumer<R, S> {
// void accept(R r, S s);
// }
//
// public interface Supplier<T> {
// T get();
// }
//
// public interface Function<T, R> {
// R apply(T t);
// }
//
// public interface Predicate<T> {
// boolean test(T t);
// }
// }
| import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.TextView;
import android.widget.Toast;
import org.droidparts.contract.HTTP;
import org.droidparts.net.http.HTTPException;
import org.droidparts.net.http.RESTClient2;
import java.util.HashMap;
import java.util.Map;
import de.lukasniemeier.gamecenterlivesender.R;
import de.lukasniemeier.gamecenterlivesender.model.publishpoint.PublishPointResult;
import de.lukasniemeier.gamecenterlivesender.utils.Functional;
| package de.lukasniemeier.gamecenterlivesender.http;
public class TaskFactory {
private static final String TAG = TaskFactory.class.getSimpleName();
private final Context context;
private final RESTClient2 restClient;
private final TextView statusView;
private final Animation fadeOutAnimation;
public TaskFactory(Context context, RESTClient2 restClient, TextView statusView) {
this.context = context;
this.restClient = restClient;
this.statusView = statusView;
this.fadeOutAnimation = new AlphaAnimation(1.0f, 0.0f);
fadeOutAnimation.setDuration(2000);
fadeOutAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
statusView.setVisibility(View.GONE);
}
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
});
}
| // Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/model/publishpoint/PublishPointResult.java
// public class PublishPointResult extends Entity {
//
// @XML(tag = "result" + XML.SUB + "path")
// public String path;
//
// public static PublishPointResult parse(String body, Context ctx) throws Exception {
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = factory.newDocumentBuilder();
// Document xml = builder.parse(new InputSource(new StringReader(body)));
//
// XMLSerializer<PublishPointResult> serializer =
// new XMLSerializer<PublishPointResult>(PublishPointResult.class, ctx);
//
// return serializer.deserialize(xml);
// }
// }
//
// Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/utils/Functional.java
// public class Functional {
//
// public interface Procedure {
// void execute();
// }
//
// public interface Consumer<T> {
// void accept(T t);
// }
//
// public interface BiConsumer<R, S> {
// void accept(R r, S s);
// }
//
// public interface Supplier<T> {
// T get();
// }
//
// public interface Function<T, R> {
// R apply(T t);
// }
//
// public interface Predicate<T> {
// boolean test(T t);
// }
// }
// Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/http/TaskFactory.java
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.TextView;
import android.widget.Toast;
import org.droidparts.contract.HTTP;
import org.droidparts.net.http.HTTPException;
import org.droidparts.net.http.RESTClient2;
import java.util.HashMap;
import java.util.Map;
import de.lukasniemeier.gamecenterlivesender.R;
import de.lukasniemeier.gamecenterlivesender.model.publishpoint.PublishPointResult;
import de.lukasniemeier.gamecenterlivesender.utils.Functional;
package de.lukasniemeier.gamecenterlivesender.http;
public class TaskFactory {
private static final String TAG = TaskFactory.class.getSimpleName();
private final Context context;
private final RESTClient2 restClient;
private final TextView statusView;
private final Animation fadeOutAnimation;
public TaskFactory(Context context, RESTClient2 restClient, TextView statusView) {
this.context = context;
this.restClient = restClient;
this.statusView = statusView;
this.fadeOutAnimation = new AlphaAnimation(1.0f, 0.0f);
fadeOutAnimation.setDuration(2000);
fadeOutAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
statusView.setVisibility(View.GONE);
}
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
});
}
| public HttpTask createPublishTask(String url, Functional.Consumer<String> castConsumer) {
|
lukasniemeier/gcls | app/src/main/java/de/lukasniemeier/gamecenterlivesender/http/TaskFactory.java | // Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/model/publishpoint/PublishPointResult.java
// public class PublishPointResult extends Entity {
//
// @XML(tag = "result" + XML.SUB + "path")
// public String path;
//
// public static PublishPointResult parse(String body, Context ctx) throws Exception {
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = factory.newDocumentBuilder();
// Document xml = builder.parse(new InputSource(new StringReader(body)));
//
// XMLSerializer<PublishPointResult> serializer =
// new XMLSerializer<PublishPointResult>(PublishPointResult.class, ctx);
//
// return serializer.deserialize(xml);
// }
// }
//
// Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/utils/Functional.java
// public class Functional {
//
// public interface Procedure {
// void execute();
// }
//
// public interface Consumer<T> {
// void accept(T t);
// }
//
// public interface BiConsumer<R, S> {
// void accept(R r, S s);
// }
//
// public interface Supplier<T> {
// T get();
// }
//
// public interface Function<T, R> {
// R apply(T t);
// }
//
// public interface Predicate<T> {
// boolean test(T t);
// }
// }
| import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.TextView;
import android.widget.Toast;
import org.droidparts.contract.HTTP;
import org.droidparts.net.http.HTTPException;
import org.droidparts.net.http.RESTClient2;
import java.util.HashMap;
import java.util.Map;
import de.lukasniemeier.gamecenterlivesender.R;
import de.lukasniemeier.gamecenterlivesender.model.publishpoint.PublishPointResult;
import de.lukasniemeier.gamecenterlivesender.utils.Functional;
| });
}
public HttpTask createPublishTask(String url, Functional.Consumer<String> castConsumer) {
return createPublish(url, castConsumer,
exception -> {
String message = context.getString(R.string.error_cast_generic);
if (exception instanceof HTTPException) {
HTTPException httpException = (HTTPException) exception;
if (httpException.getResponseCode() == 400) {
message = context.getString(R.string.error_missing_feed);
}
}
showErrorToast(message, exception);
});
}
public HttpTask createPublishTaskWithFallback(final Task fallbackTask, String url, Functional.Consumer<String> castConsumer) {
return createPublish(url, castConsumer, exception -> {
Log.w(TAG, "Publish task failed, falling back", exception);
fallbackTask.execute();
});
}
private HttpTask createPublish(String url, Functional.Consumer<String> castConsumer, Functional.Consumer<Exception> failureFunction) {
return new GetHttpTask(restClient, url, context,
createStatusFunc("Obtaining video feed..."),
response -> {
statusView.setText("Starting to cast...");
try {
| // Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/model/publishpoint/PublishPointResult.java
// public class PublishPointResult extends Entity {
//
// @XML(tag = "result" + XML.SUB + "path")
// public String path;
//
// public static PublishPointResult parse(String body, Context ctx) throws Exception {
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = factory.newDocumentBuilder();
// Document xml = builder.parse(new InputSource(new StringReader(body)));
//
// XMLSerializer<PublishPointResult> serializer =
// new XMLSerializer<PublishPointResult>(PublishPointResult.class, ctx);
//
// return serializer.deserialize(xml);
// }
// }
//
// Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/utils/Functional.java
// public class Functional {
//
// public interface Procedure {
// void execute();
// }
//
// public interface Consumer<T> {
// void accept(T t);
// }
//
// public interface BiConsumer<R, S> {
// void accept(R r, S s);
// }
//
// public interface Supplier<T> {
// T get();
// }
//
// public interface Function<T, R> {
// R apply(T t);
// }
//
// public interface Predicate<T> {
// boolean test(T t);
// }
// }
// Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/http/TaskFactory.java
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.TextView;
import android.widget.Toast;
import org.droidparts.contract.HTTP;
import org.droidparts.net.http.HTTPException;
import org.droidparts.net.http.RESTClient2;
import java.util.HashMap;
import java.util.Map;
import de.lukasniemeier.gamecenterlivesender.R;
import de.lukasniemeier.gamecenterlivesender.model.publishpoint.PublishPointResult;
import de.lukasniemeier.gamecenterlivesender.utils.Functional;
});
}
public HttpTask createPublishTask(String url, Functional.Consumer<String> castConsumer) {
return createPublish(url, castConsumer,
exception -> {
String message = context.getString(R.string.error_cast_generic);
if (exception instanceof HTTPException) {
HTTPException httpException = (HTTPException) exception;
if (httpException.getResponseCode() == 400) {
message = context.getString(R.string.error_missing_feed);
}
}
showErrorToast(message, exception);
});
}
public HttpTask createPublishTaskWithFallback(final Task fallbackTask, String url, Functional.Consumer<String> castConsumer) {
return createPublish(url, castConsumer, exception -> {
Log.w(TAG, "Publish task failed, falling back", exception);
fallbackTask.execute();
});
}
private HttpTask createPublish(String url, Functional.Consumer<String> castConsumer, Functional.Consumer<Exception> failureFunction) {
return new GetHttpTask(restClient, url, context,
createStatusFunc("Obtaining video feed..."),
response -> {
statusView.setText("Starting to cast...");
try {
| PublishPointResult result = PublishPointResult.parse(response.body, context);
|
lukasniemeier/gcls | app/src/main/java/de/lukasniemeier/gamecenterlivesender/http/HttpTask.java | // Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/utils/Functional.java
// public class Functional {
//
// public interface Procedure {
// void execute();
// }
//
// public interface Consumer<T> {
// void accept(T t);
// }
//
// public interface BiConsumer<R, S> {
// void accept(R r, S s);
// }
//
// public interface Supplier<T> {
// T get();
// }
//
// public interface Function<T, R> {
// R apply(T t);
// }
//
// public interface Predicate<T> {
// boolean test(T t);
// }
// }
| import android.content.Context;
import org.droidparts.concurrent.task.AsyncTaskResultListener;
import org.droidparts.concurrent.task.SimpleAsyncTask;
import org.droidparts.net.http.HTTPResponse;
import org.droidparts.net.http.RESTClient2;
import de.lukasniemeier.gamecenterlivesender.utils.Functional;
| package de.lukasniemeier.gamecenterlivesender.http;
public abstract class HttpTask extends SimpleAsyncTask<HTTPResponse> implements Task {
protected final RESTClient2 restClient;
protected final String url;
| // Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/utils/Functional.java
// public class Functional {
//
// public interface Procedure {
// void execute();
// }
//
// public interface Consumer<T> {
// void accept(T t);
// }
//
// public interface BiConsumer<R, S> {
// void accept(R r, S s);
// }
//
// public interface Supplier<T> {
// T get();
// }
//
// public interface Function<T, R> {
// R apply(T t);
// }
//
// public interface Predicate<T> {
// boolean test(T t);
// }
// }
// Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/http/HttpTask.java
import android.content.Context;
import org.droidparts.concurrent.task.AsyncTaskResultListener;
import org.droidparts.concurrent.task.SimpleAsyncTask;
import org.droidparts.net.http.HTTPResponse;
import org.droidparts.net.http.RESTClient2;
import de.lukasniemeier.gamecenterlivesender.utils.Functional;
package de.lukasniemeier.gamecenterlivesender.http;
public abstract class HttpTask extends SimpleAsyncTask<HTTPResponse> implements Task {
protected final RESTClient2 restClient;
protected final String url;
| private final Functional.Procedure preFunction;
|
lukasniemeier/gcls | app/src/main/java/de/lukasniemeier/gamecenterlivesender/http/PostHttpTask.java | // Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/utils/Functional.java
// public class Functional {
//
// public interface Procedure {
// void execute();
// }
//
// public interface Consumer<T> {
// void accept(T t);
// }
//
// public interface BiConsumer<R, S> {
// void accept(R r, S s);
// }
//
// public interface Supplier<T> {
// T get();
// }
//
// public interface Function<T, R> {
// R apply(T t);
// }
//
// public interface Predicate<T> {
// boolean test(T t);
// }
// }
| import android.content.Context;
import org.droidparts.net.http.HTTPResponse;
import org.droidparts.net.http.RESTClient2;
import java.util.Map;
import de.lukasniemeier.gamecenterlivesender.utils.Functional;
| package de.lukasniemeier.gamecenterlivesender.http;
public class PostHttpTask extends HttpTask {
private final Map<String, String> formData;
public PostHttpTask(Map<String, String> formData,
RESTClient2 restClient,
String url,
Context ctx,
| // Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/utils/Functional.java
// public class Functional {
//
// public interface Procedure {
// void execute();
// }
//
// public interface Consumer<T> {
// void accept(T t);
// }
//
// public interface BiConsumer<R, S> {
// void accept(R r, S s);
// }
//
// public interface Supplier<T> {
// T get();
// }
//
// public interface Function<T, R> {
// R apply(T t);
// }
//
// public interface Predicate<T> {
// boolean test(T t);
// }
// }
// Path: app/src/main/java/de/lukasniemeier/gamecenterlivesender/http/PostHttpTask.java
import android.content.Context;
import org.droidparts.net.http.HTTPResponse;
import org.droidparts.net.http.RESTClient2;
import java.util.Map;
import de.lukasniemeier.gamecenterlivesender.utils.Functional;
package de.lukasniemeier.gamecenterlivesender.http;
public class PostHttpTask extends HttpTask {
private final Map<String, String> formData;
public PostHttpTask(Map<String, String> formData,
RESTClient2 restClient,
String url,
Context ctx,
| Functional.Consumer<HTTPResponse> successFunction,
|
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/background/job/GeneratePageThumbnails.java | // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
| import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID; | package technology.tabula.tabula_web.background.job;
public class GeneratePageThumbnails extends Job {
private final String filePath;
private final String documentId;
private final PDDocument pdfDocument; | // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
// Path: src/main/java/technology/tabula/tabula_web/background/job/GeneratePageThumbnails.java
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;
package technology.tabula.tabula_web.background.job;
public class GeneratePageThumbnails extends Job {
private final String filePath;
private final String documentId;
private final PDDocument pdfDocument; | private WorkspaceDAO workspaceDAO; |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/background/job/GeneratePageThumbnails.java | // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
| import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID; | package technology.tabula.tabula_web.background.job;
public class GeneratePageThumbnails extends Job {
private final String filePath;
private final String documentId;
private final PDDocument pdfDocument;
private WorkspaceDAO workspaceDAO;
private static final int SIZE = 800;
final static Logger logger = LoggerFactory.getLogger(GeneratePageThumbnails.class);
public GeneratePageThumbnails(String filePath, String documentId, UUID batch, WorkspaceDAO workspaceDAO) throws Exception {
super(batch);
this.filePath = filePath;
this.documentId = documentId;
this.workspaceDAO = workspaceDAO;
| // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
// Path: src/main/java/technology/tabula/tabula_web/background/job/GeneratePageThumbnails.java
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;
package technology.tabula.tabula_web.background.job;
public class GeneratePageThumbnails extends Job {
private final String filePath;
private final String documentId;
private final PDDocument pdfDocument;
private WorkspaceDAO workspaceDAO;
private static final int SIZE = 800;
final static Logger logger = LoggerFactory.getLogger(GeneratePageThumbnails.class);
public GeneratePageThumbnails(String filePath, String documentId, UUID batch, WorkspaceDAO workspaceDAO) throws Exception {
super(batch);
this.filePath = filePath;
this.documentId = documentId;
this.workspaceDAO = workspaceDAO;
| this.pdfDocument = Utils.openPDF(this.filePath); |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/background/job/Job.java | // Path: src/main/java/technology/tabula/tabula_web/background/JobExecutor.java
// public class JobExecutor extends ThreadPoolExecutor {
//
// @SuppressWarnings("Convert2Diamond")
// private Map<String, Job> jobs = new ConcurrentHashMap<String, Job>();
// @SuppressWarnings("Convert2Diamond")
// private Map<Future<String>, Job> futureJobs = new ConcurrentHashMap<Future<String>, Job>();
// private static final Object mutex = new Object();
//
// final static Logger logger = LoggerFactory.getLogger(JobExecutor.class);
//
// private static class SingletonHolder {
// private static final JobExecutor INSTANCE = new JobExecutor();
// }
//
// public static JobExecutor getInstance() {
// synchronized (mutex) {
// return SingletonHolder.INSTANCE;
// }
// }
//
// @SuppressWarnings("Convert2Diamond")
// private JobExecutor() {
// super(3, 10, 300, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
// logger.info("Starting JobExecutor");
// }
//
// @Override
// protected void afterExecute(Runnable runnable, Throwable throwable) {
// super.afterExecute(runnable, throwable);
// FutureTask<?> ft = (FutureTask<?>) runnable;
// if (throwable == null && runnable instanceof FutureTask<?>) {
// try {
// if (ft.isDone()) ft.get();
// }
// catch (CancellationException e) {
// throwable = e.getCause();
// }
// catch (ExecutionException e) {
// throwable = e;
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// }
//
// if (throwable == null) {
// // task finished ok
// //this.futureJobs.get(key)
// }
// else {
// // TODO/ improve this
// throwable.printStackTrace(System.out);
// }
// }
// }
//
// public Future<String> submitJob(Job task) {
// jobs.put(task.getUUID(), task);
// Future<String> f = this.submit(task);
// futureJobs.put(f, task);
// return f;
// }
//
// public void submitJobs(Job... jobs) {
// for (Job j: jobs) {
// submitJob(j);
// }
// }
//
// public Job getJob(String uuid) {
// return jobs.get(uuid);
// }
//
// public List<Job> getByBatch(String uuid) {
// return jobs.values()
// .stream()
// .filter(j -> j.getBatch().equals(uuid))
// .collect(Collectors.toList());
// }
// }
| import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import technology.tabula.tabula_web.background.JobExecutor; | package technology.tabula.tabula_web.background.job;
public abstract class Job implements Callable<String> {
private UUID uuid;
private UUID batch;
private JobStatus status;
| // Path: src/main/java/technology/tabula/tabula_web/background/JobExecutor.java
// public class JobExecutor extends ThreadPoolExecutor {
//
// @SuppressWarnings("Convert2Diamond")
// private Map<String, Job> jobs = new ConcurrentHashMap<String, Job>();
// @SuppressWarnings("Convert2Diamond")
// private Map<Future<String>, Job> futureJobs = new ConcurrentHashMap<Future<String>, Job>();
// private static final Object mutex = new Object();
//
// final static Logger logger = LoggerFactory.getLogger(JobExecutor.class);
//
// private static class SingletonHolder {
// private static final JobExecutor INSTANCE = new JobExecutor();
// }
//
// public static JobExecutor getInstance() {
// synchronized (mutex) {
// return SingletonHolder.INSTANCE;
// }
// }
//
// @SuppressWarnings("Convert2Diamond")
// private JobExecutor() {
// super(3, 10, 300, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
// logger.info("Starting JobExecutor");
// }
//
// @Override
// protected void afterExecute(Runnable runnable, Throwable throwable) {
// super.afterExecute(runnable, throwable);
// FutureTask<?> ft = (FutureTask<?>) runnable;
// if (throwable == null && runnable instanceof FutureTask<?>) {
// try {
// if (ft.isDone()) ft.get();
// }
// catch (CancellationException e) {
// throwable = e.getCause();
// }
// catch (ExecutionException e) {
// throwable = e;
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// }
//
// if (throwable == null) {
// // task finished ok
// //this.futureJobs.get(key)
// }
// else {
// // TODO/ improve this
// throwable.printStackTrace(System.out);
// }
// }
// }
//
// public Future<String> submitJob(Job task) {
// jobs.put(task.getUUID(), task);
// Future<String> f = this.submit(task);
// futureJobs.put(f, task);
// return f;
// }
//
// public void submitJobs(Job... jobs) {
// for (Job j: jobs) {
// submitJob(j);
// }
// }
//
// public Job getJob(String uuid) {
// return jobs.get(uuid);
// }
//
// public List<Job> getByBatch(String uuid) {
// return jobs.values()
// .stream()
// .filter(j -> j.getBatch().equals(uuid))
// .collect(Collectors.toList());
// }
// }
// Path: src/main/java/technology/tabula/tabula_web/background/job/Job.java
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import technology.tabula.tabula_web.background.JobExecutor;
package technology.tabula.tabula_web.background.job;
public abstract class Job implements Callable<String> {
private UUID uuid;
private UUID batch;
private JobStatus status;
| final static Logger logger = LoggerFactory.getLogger(JobExecutor.class); |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/extractor/Extractor.java | // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
import technology.tabula.PageIterator;
import technology.tabula.Table;
import technology.tabula.extractors.BasicExtractionAlgorithm;
import technology.tabula.extractors.ExtractionAlgorithm;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;
import technology.tabula.tabula_web.Utils; | package technology.tabula.tabula_web.extractor;
public class Extractor {
@SuppressWarnings("Convert2Diamond")
public static List<TableWithSpecIndex> extractTables(String pdfPath, List<CoordSpec> specs) throws IOException {
Map<Integer, List<CoordSpec>> specsByPage = specs.stream().collect(Collectors.groupingBy(CoordSpec::getPage));
//noinspection Convert2Diamond
List<Integer> pages = new ArrayList<Integer>(specsByPage.keySet());
Collections.sort(pages);
| // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
// Path: src/main/java/technology/tabula/tabula_web/extractor/Extractor.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
import technology.tabula.PageIterator;
import technology.tabula.Table;
import technology.tabula.extractors.BasicExtractionAlgorithm;
import technology.tabula.extractors.ExtractionAlgorithm;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;
import technology.tabula.tabula_web.Utils;
package technology.tabula.tabula_web.extractor;
public class Extractor {
@SuppressWarnings("Convert2Diamond")
public static List<TableWithSpecIndex> extractTables(String pdfPath, List<CoordSpec> specs) throws IOException {
Map<Integer, List<CoordSpec>> specsByPage = specs.stream().collect(Collectors.groupingBy(CoordSpec::getPage));
//noinspection Convert2Diamond
List<Integer> pages = new ArrayList<Integer>(specsByPage.keySet());
Collections.sort(pages);
| PDDocument document = Utils.openPDF(pdfPath); |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/routes/PdfsRouteGroup.java | // Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
| import spark.RouteGroup;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import static spark.Spark.get;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletResponse; | package technology.tabula.tabula_web.routes;
public class PdfsRouteGroup implements RouteGroup {
private WorkspaceDAO workspaceDAO;
public PdfsRouteGroup(WorkspaceDAO workspaceDAO) {
this.workspaceDAO = workspaceDAO;
}
@Override
public void addRoutes() {
get("workspace.json", (req, rsp) -> {
rsp.type("application/json");
return this.workspaceDAO.getWorkspace(); | // Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
// Path: src/main/java/technology/tabula/tabula_web/routes/PdfsRouteGroup.java
import spark.RouteGroup;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import static spark.Spark.get;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletResponse;
package technology.tabula.tabula_web.routes;
public class PdfsRouteGroup implements RouteGroup {
private WorkspaceDAO workspaceDAO;
public PdfsRouteGroup(WorkspaceDAO workspaceDAO) {
this.workspaceDAO = workspaceDAO;
}
@Override
public void addRoutes() {
get("workspace.json", (req, rsp) -> {
rsp.type("application/json");
return this.workspaceDAO.getWorkspace(); | }, new JsonTransformer()); |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/routes/IndexRouteGroup.java | // Path: src/main/java/technology/tabula/tabula_web/App.java
// public class App {
//
// private static final String VERSION = "1.1.0";
//
// public static void main(String[] args) throws JsonIOException, JsonSyntaxException, IOException, WorkspaceException {
// staticFiles.location("/public");
// RouteOverview.enableRouteOverview();
//
// WorkspaceDAO workspaceDAO = new FileWorkspaceDAO(Settings.getDataDir());
//
// path("/", new IndexRouteGroup(workspaceDAO));
// path("/pdfs/", new PdfsRouteGroup(workspaceDAO));
// path("/pdf/", new PdfRouteGroup(workspaceDAO));
// path("/queue/", new JobProgressRouteGroup());
//
// get("/version", (req, rsp) -> {
// rsp.type("application/json");
// return String.format("{ \"api\": \"%s\" }", VERSION);
// });
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
| import java.util.Scanner;
import spark.RouteGroup;
import technology.tabula.tabula_web.App;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import static spark.Spark.*; | package technology.tabula.tabula_web.routes;
public class IndexRouteGroup implements RouteGroup {
private static final String index;
static { | // Path: src/main/java/technology/tabula/tabula_web/App.java
// public class App {
//
// private static final String VERSION = "1.1.0";
//
// public static void main(String[] args) throws JsonIOException, JsonSyntaxException, IOException, WorkspaceException {
// staticFiles.location("/public");
// RouteOverview.enableRouteOverview();
//
// WorkspaceDAO workspaceDAO = new FileWorkspaceDAO(Settings.getDataDir());
//
// path("/", new IndexRouteGroup(workspaceDAO));
// path("/pdfs/", new PdfsRouteGroup(workspaceDAO));
// path("/pdf/", new PdfRouteGroup(workspaceDAO));
// path("/queue/", new JobProgressRouteGroup());
//
// get("/version", (req, rsp) -> {
// rsp.type("application/json");
// return String.format("{ \"api\": \"%s\" }", VERSION);
// });
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
// Path: src/main/java/technology/tabula/tabula_web/routes/IndexRouteGroup.java
import java.util.Scanner;
import spark.RouteGroup;
import technology.tabula.tabula_web.App;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import static spark.Spark.*;
package technology.tabula.tabula_web.routes;
public class IndexRouteGroup implements RouteGroup {
private static final String index;
static { | index = new Scanner(App.class.getClassLoader().getResourceAsStream("public/index.html"), "UTF-8").useDelimiter("\\A").next(); |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/routes/IndexRouteGroup.java | // Path: src/main/java/technology/tabula/tabula_web/App.java
// public class App {
//
// private static final String VERSION = "1.1.0";
//
// public static void main(String[] args) throws JsonIOException, JsonSyntaxException, IOException, WorkspaceException {
// staticFiles.location("/public");
// RouteOverview.enableRouteOverview();
//
// WorkspaceDAO workspaceDAO = new FileWorkspaceDAO(Settings.getDataDir());
//
// path("/", new IndexRouteGroup(workspaceDAO));
// path("/pdfs/", new PdfsRouteGroup(workspaceDAO));
// path("/pdf/", new PdfRouteGroup(workspaceDAO));
// path("/queue/", new JobProgressRouteGroup());
//
// get("/version", (req, rsp) -> {
// rsp.type("application/json");
// return String.format("{ \"api\": \"%s\" }", VERSION);
// });
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
| import java.util.Scanner;
import spark.RouteGroup;
import technology.tabula.tabula_web.App;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import static spark.Spark.*; | package technology.tabula.tabula_web.routes;
public class IndexRouteGroup implements RouteGroup {
private static final String index;
static {
index = new Scanner(App.class.getClassLoader().getResourceAsStream("public/index.html"), "UTF-8").useDelimiter("\\A").next();
}
private static final String[] indexes = new String[]{"pdf/:file_id", "help", "about"}; | // Path: src/main/java/technology/tabula/tabula_web/App.java
// public class App {
//
// private static final String VERSION = "1.1.0";
//
// public static void main(String[] args) throws JsonIOException, JsonSyntaxException, IOException, WorkspaceException {
// staticFiles.location("/public");
// RouteOverview.enableRouteOverview();
//
// WorkspaceDAO workspaceDAO = new FileWorkspaceDAO(Settings.getDataDir());
//
// path("/", new IndexRouteGroup(workspaceDAO));
// path("/pdfs/", new PdfsRouteGroup(workspaceDAO));
// path("/pdf/", new PdfRouteGroup(workspaceDAO));
// path("/queue/", new JobProgressRouteGroup());
//
// get("/version", (req, rsp) -> {
// rsp.type("application/json");
// return String.format("{ \"api\": \"%s\" }", VERSION);
// });
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
// Path: src/main/java/technology/tabula/tabula_web/routes/IndexRouteGroup.java
import java.util.Scanner;
import spark.RouteGroup;
import technology.tabula.tabula_web.App;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import static spark.Spark.*;
package technology.tabula.tabula_web.routes;
public class IndexRouteGroup implements RouteGroup {
private static final String index;
static {
index = new Scanner(App.class.getClassLoader().getResourceAsStream("public/index.html"), "UTF-8").useDelimiter("\\A").next();
}
private static final String[] indexes = new String[]{"pdf/:file_id", "help", "about"}; | private WorkspaceDAO workspaceDAO; |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/routes/IndexRouteGroup.java | // Path: src/main/java/technology/tabula/tabula_web/App.java
// public class App {
//
// private static final String VERSION = "1.1.0";
//
// public static void main(String[] args) throws JsonIOException, JsonSyntaxException, IOException, WorkspaceException {
// staticFiles.location("/public");
// RouteOverview.enableRouteOverview();
//
// WorkspaceDAO workspaceDAO = new FileWorkspaceDAO(Settings.getDataDir());
//
// path("/", new IndexRouteGroup(workspaceDAO));
// path("/pdfs/", new PdfsRouteGroup(workspaceDAO));
// path("/pdf/", new PdfRouteGroup(workspaceDAO));
// path("/queue/", new JobProgressRouteGroup());
//
// get("/version", (req, rsp) -> {
// rsp.type("application/json");
// return String.format("{ \"api\": \"%s\" }", VERSION);
// });
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
| import java.util.Scanner;
import spark.RouteGroup;
import technology.tabula.tabula_web.App;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import static spark.Spark.*; | package technology.tabula.tabula_web.routes;
public class IndexRouteGroup implements RouteGroup {
private static final String index;
static {
index = new Scanner(App.class.getClassLoader().getResourceAsStream("public/index.html"), "UTF-8").useDelimiter("\\A").next();
}
private static final String[] indexes = new String[]{"pdf/:file_id", "help", "about"};
private WorkspaceDAO workspaceDAO;
public IndexRouteGroup(WorkspaceDAO workspaceDAO) {
this.workspaceDAO = workspaceDAO;
}
@Override
public void addRoutes() {
for (String path : indexes) {
get(path, (req, rsp) -> index);
} | // Path: src/main/java/technology/tabula/tabula_web/App.java
// public class App {
//
// private static final String VERSION = "1.1.0";
//
// public static void main(String[] args) throws JsonIOException, JsonSyntaxException, IOException, WorkspaceException {
// staticFiles.location("/public");
// RouteOverview.enableRouteOverview();
//
// WorkspaceDAO workspaceDAO = new FileWorkspaceDAO(Settings.getDataDir());
//
// path("/", new IndexRouteGroup(workspaceDAO));
// path("/pdfs/", new PdfsRouteGroup(workspaceDAO));
// path("/pdf/", new PdfRouteGroup(workspaceDAO));
// path("/queue/", new JobProgressRouteGroup());
//
// get("/version", (req, rsp) -> {
// rsp.type("application/json");
// return String.format("{ \"api\": \"%s\" }", VERSION);
// });
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
// Path: src/main/java/technology/tabula/tabula_web/routes/IndexRouteGroup.java
import java.util.Scanner;
import spark.RouteGroup;
import technology.tabula.tabula_web.App;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import static spark.Spark.*;
package technology.tabula.tabula_web.routes;
public class IndexRouteGroup implements RouteGroup {
private static final String index;
static {
index = new Scanner(App.class.getClassLoader().getResourceAsStream("public/index.html"), "UTF-8").useDelimiter("\\A").next();
}
private static final String[] indexes = new String[]{"pdf/:file_id", "help", "about"};
private WorkspaceDAO workspaceDAO;
public IndexRouteGroup(WorkspaceDAO workspaceDAO) {
this.workspaceDAO = workspaceDAO;
}
@Override
public void addRoutes() {
for (String path : indexes) {
get(path, (req, rsp) -> index);
} | post("upload.json", new UploadRoute(workspaceDAO), new JsonTransformer()); |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/routes/PdfRouteGroup.java | // Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceException.java
// @SuppressWarnings("serial")
// public class WorkspaceException extends Exception {
//
// public WorkspaceException(Throwable cause) {
// super(cause);
// }
// }
| import spark.Request;
import spark.Response;
import spark.RouteGroup;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceException;
import static spark.Spark.*; | package technology.tabula.tabula_web.routes;
public class PdfRouteGroup implements RouteGroup {
private WorkspaceDAO workspaceDAO;
public PdfRouteGroup(WorkspaceDAO workspaceDAO) {
this.workspaceDAO = workspaceDAO;
}
private Object deleteDocument(Request request, Response response) {
try {
this.workspaceDAO.deleteDocument(request.params(":file_id")); | // Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceException.java
// @SuppressWarnings("serial")
// public class WorkspaceException extends Exception {
//
// public WorkspaceException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/technology/tabula/tabula_web/routes/PdfRouteGroup.java
import spark.Request;
import spark.Response;
import spark.RouteGroup;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceException;
import static spark.Spark.*;
package technology.tabula.tabula_web.routes;
public class PdfRouteGroup implements RouteGroup {
private WorkspaceDAO workspaceDAO;
public PdfRouteGroup(WorkspaceDAO workspaceDAO) {
this.workspaceDAO = workspaceDAO;
}
private Object deleteDocument(Request request, Response response) {
try {
this.workspaceDAO.deleteDocument(request.params(":file_id")); | } catch (WorkspaceException e) { |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/routes/PdfRouteGroup.java | // Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceException.java
// @SuppressWarnings("serial")
// public class WorkspaceException extends Exception {
//
// public WorkspaceException(Throwable cause) {
// super(cause);
// }
// }
| import spark.Request;
import spark.Response;
import spark.RouteGroup;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceException;
import static spark.Spark.*; | package technology.tabula.tabula_web.routes;
public class PdfRouteGroup implements RouteGroup {
private WorkspaceDAO workspaceDAO;
public PdfRouteGroup(WorkspaceDAO workspaceDAO) {
this.workspaceDAO = workspaceDAO;
}
private Object deleteDocument(Request request, Response response) {
try {
this.workspaceDAO.deleteDocument(request.params(":file_id"));
} catch (WorkspaceException e) {
halt(500, e.getMessage());
}
return "";
}
@Override
public void addRoutes() {
get(":file_id/metadata.json", (req, rsp) -> {
rsp.type("application/json");
return this.workspaceDAO.getDocumentMetadata(req.params(":file_id")); | // Path: src/main/java/technology/tabula/tabula_web/JsonTransformer.java
// public class JsonTransformer implements ResponseTransformer {
//
// private Gson gson = new Gson();
//
// @Override
// public String render(Object model) {
// return gson.toJson(model);
// }
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceException.java
// @SuppressWarnings("serial")
// public class WorkspaceException extends Exception {
//
// public WorkspaceException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/technology/tabula/tabula_web/routes/PdfRouteGroup.java
import spark.Request;
import spark.Response;
import spark.RouteGroup;
import technology.tabula.tabula_web.JsonTransformer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceException;
import static spark.Spark.*;
package technology.tabula.tabula_web.routes;
public class PdfRouteGroup implements RouteGroup {
private WorkspaceDAO workspaceDAO;
public PdfRouteGroup(WorkspaceDAO workspaceDAO) {
this.workspaceDAO = workspaceDAO;
}
private Object deleteDocument(Request request, Response response) {
try {
this.workspaceDAO.deleteDocument(request.params(":file_id"));
} catch (WorkspaceException e) {
halt(500, e.getMessage());
}
return "";
}
@Override
public void addRoutes() {
get(":file_id/metadata.json", (req, rsp) -> {
rsp.type("application/json");
return this.workspaceDAO.getDocumentMetadata(req.params(":file_id")); | }, new JsonTransformer()); |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/background/job/DetectTables.java | // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
| import com.google.gson.Gson;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
import technology.tabula.PageIterator;
import technology.tabula.Rectangle;
import technology.tabula.detectors.NurminenDetectionAlgorithm;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors; | package technology.tabula.tabula_web.background.job;
public class DetectTables extends Job {
private final String filePath;
private final String documentId; | // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
// Path: src/main/java/technology/tabula/tabula_web/background/job/DetectTables.java
import com.google.gson.Gson;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
import technology.tabula.PageIterator;
import technology.tabula.Rectangle;
import technology.tabula.detectors.NurminenDetectionAlgorithm;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
package technology.tabula.tabula_web.background.job;
public class DetectTables extends Job {
private final String filePath;
private final String documentId; | private WorkspaceDAO workspaceDAO; |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/background/job/DetectTables.java | // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
| import com.google.gson.Gson;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
import technology.tabula.PageIterator;
import technology.tabula.Rectangle;
import technology.tabula.detectors.NurminenDetectionAlgorithm;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors; | package technology.tabula.tabula_web.background.job;
public class DetectTables extends Job {
private final String filePath;
private final String documentId;
private WorkspaceDAO workspaceDAO;
public DetectTables(String filePath, String documentId, UUID batch, WorkspaceDAO workspaceDAO) {
super(batch);
this.filePath = filePath;
this.documentId = documentId;
this.workspaceDAO = workspaceDAO;
}
@Override
public void perform() throws Exception {
| // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
// Path: src/main/java/technology/tabula/tabula_web/background/job/DetectTables.java
import com.google.gson.Gson;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
import technology.tabula.PageIterator;
import technology.tabula.Rectangle;
import technology.tabula.detectors.NurminenDetectionAlgorithm;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
package technology.tabula.tabula_web.background.job;
public class DetectTables extends Job {
private final String filePath;
private final String documentId;
private WorkspaceDAO workspaceDAO;
public DetectTables(String filePath, String documentId, UUID batch, WorkspaceDAO workspaceDAO) {
super(batch);
this.filePath = filePath;
this.documentId = documentId;
this.workspaceDAO = workspaceDAO;
}
@Override
public void perform() throws Exception {
| PDDocument document = Utils.openPDF(filePath); |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/background/job/GenerateDocumentData.java | // Path: src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java
// public class PagesInfoExtractor {
//
// @SuppressWarnings("Convert2Diamond")
// public static List<DocumentPage> pagesInfo(String pdfPath) throws IOException {
// PDDocument document = Utils.openPDF(pdfPath);
// ObjectExtractor extractor = new ObjectExtractor(document);
//
// ArrayList<DocumentPage> rv = new ArrayList<DocumentPage>();
//
// PageIterator it = extractor.extract();
// Page p;
// while (it.hasNext()) {
// p = it.next();
// rv.add(new DocumentPage(p.getWidth(), p.getHeight(), p.getPageNumber(), p.getRotation(), p.hasText()));
// }
//
// extractor.close();
//
// return rv;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDocument.java
// public class WorkspaceDocument {
// public String original_filename;
// public String id;
// public String time;
// public int page_count;
// public long size;
// public int[] thumbnail_sizes;
//
//
// public WorkspaceDocument(String original_filename, String id, String time, int page_count, long size,
// int[] thumbnail_sizes) {
// this.original_filename = original_filename;
// this.id = id;
// this.time = time;
// this.page_count = page_count;
// this.size = size;
// this.thumbnail_sizes = thumbnail_sizes.clone();
// }
//
//
//
// }
| import java.io.File;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;
import technology.tabula.tabula_web.extractor.PagesInfoExtractor;
import technology.tabula.tabula_web.workspace.DocumentPage;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceDocument; | package technology.tabula.tabula_web.background.job;
public class GenerateDocumentData extends Job {
String filePath;
String originalFilename;
String id;
int[] thumbnailSizes;
| // Path: src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java
// public class PagesInfoExtractor {
//
// @SuppressWarnings("Convert2Diamond")
// public static List<DocumentPage> pagesInfo(String pdfPath) throws IOException {
// PDDocument document = Utils.openPDF(pdfPath);
// ObjectExtractor extractor = new ObjectExtractor(document);
//
// ArrayList<DocumentPage> rv = new ArrayList<DocumentPage>();
//
// PageIterator it = extractor.extract();
// Page p;
// while (it.hasNext()) {
// p = it.next();
// rv.add(new DocumentPage(p.getWidth(), p.getHeight(), p.getPageNumber(), p.getRotation(), p.hasText()));
// }
//
// extractor.close();
//
// return rv;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDocument.java
// public class WorkspaceDocument {
// public String original_filename;
// public String id;
// public String time;
// public int page_count;
// public long size;
// public int[] thumbnail_sizes;
//
//
// public WorkspaceDocument(String original_filename, String id, String time, int page_count, long size,
// int[] thumbnail_sizes) {
// this.original_filename = original_filename;
// this.id = id;
// this.time = time;
// this.page_count = page_count;
// this.size = size;
// this.thumbnail_sizes = thumbnail_sizes.clone();
// }
//
//
//
// }
// Path: src/main/java/technology/tabula/tabula_web/background/job/GenerateDocumentData.java
import java.io.File;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;
import technology.tabula.tabula_web.extractor.PagesInfoExtractor;
import technology.tabula.tabula_web.workspace.DocumentPage;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceDocument;
package technology.tabula.tabula_web.background.job;
public class GenerateDocumentData extends Job {
String filePath;
String originalFilename;
String id;
int[] thumbnailSizes;
| private WorkspaceDAO workspaceDAO; |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/background/job/GenerateDocumentData.java | // Path: src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java
// public class PagesInfoExtractor {
//
// @SuppressWarnings("Convert2Diamond")
// public static List<DocumentPage> pagesInfo(String pdfPath) throws IOException {
// PDDocument document = Utils.openPDF(pdfPath);
// ObjectExtractor extractor = new ObjectExtractor(document);
//
// ArrayList<DocumentPage> rv = new ArrayList<DocumentPage>();
//
// PageIterator it = extractor.extract();
// Page p;
// while (it.hasNext()) {
// p = it.next();
// rv.add(new DocumentPage(p.getWidth(), p.getHeight(), p.getPageNumber(), p.getRotation(), p.hasText()));
// }
//
// extractor.close();
//
// return rv;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDocument.java
// public class WorkspaceDocument {
// public String original_filename;
// public String id;
// public String time;
// public int page_count;
// public long size;
// public int[] thumbnail_sizes;
//
//
// public WorkspaceDocument(String original_filename, String id, String time, int page_count, long size,
// int[] thumbnail_sizes) {
// this.original_filename = original_filename;
// this.id = id;
// this.time = time;
// this.page_count = page_count;
// this.size = size;
// this.thumbnail_sizes = thumbnail_sizes.clone();
// }
//
//
//
// }
| import java.io.File;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;
import technology.tabula.tabula_web.extractor.PagesInfoExtractor;
import technology.tabula.tabula_web.workspace.DocumentPage;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceDocument; | package technology.tabula.tabula_web.background.job;
public class GenerateDocumentData extends Job {
String filePath;
String originalFilename;
String id;
int[] thumbnailSizes;
private WorkspaceDAO workspaceDAO;
public GenerateDocumentData(String filePath, String originalFilename, String id,
int[] thumbnailSizes, UUID batch, WorkspaceDAO workspaceDAO) {
super(batch);
this.filePath = filePath;
this.originalFilename = originalFilename;
this.id = id;
this.thumbnailSizes = thumbnailSizes.clone();
this.workspaceDAO = workspaceDAO;
}
@Override
public void perform() throws Exception {
at(1, 100, "opening workspace...");
| // Path: src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java
// public class PagesInfoExtractor {
//
// @SuppressWarnings("Convert2Diamond")
// public static List<DocumentPage> pagesInfo(String pdfPath) throws IOException {
// PDDocument document = Utils.openPDF(pdfPath);
// ObjectExtractor extractor = new ObjectExtractor(document);
//
// ArrayList<DocumentPage> rv = new ArrayList<DocumentPage>();
//
// PageIterator it = extractor.extract();
// Page p;
// while (it.hasNext()) {
// p = it.next();
// rv.add(new DocumentPage(p.getWidth(), p.getHeight(), p.getPageNumber(), p.getRotation(), p.hasText()));
// }
//
// extractor.close();
//
// return rv;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDocument.java
// public class WorkspaceDocument {
// public String original_filename;
// public String id;
// public String time;
// public int page_count;
// public long size;
// public int[] thumbnail_sizes;
//
//
// public WorkspaceDocument(String original_filename, String id, String time, int page_count, long size,
// int[] thumbnail_sizes) {
// this.original_filename = original_filename;
// this.id = id;
// this.time = time;
// this.page_count = page_count;
// this.size = size;
// this.thumbnail_sizes = thumbnail_sizes.clone();
// }
//
//
//
// }
// Path: src/main/java/technology/tabula/tabula_web/background/job/GenerateDocumentData.java
import java.io.File;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;
import technology.tabula.tabula_web.extractor.PagesInfoExtractor;
import technology.tabula.tabula_web.workspace.DocumentPage;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceDocument;
package technology.tabula.tabula_web.background.job;
public class GenerateDocumentData extends Job {
String filePath;
String originalFilename;
String id;
int[] thumbnailSizes;
private WorkspaceDAO workspaceDAO;
public GenerateDocumentData(String filePath, String originalFilename, String id,
int[] thumbnailSizes, UUID batch, WorkspaceDAO workspaceDAO) {
super(batch);
this.filePath = filePath;
this.originalFilename = originalFilename;
this.id = id;
this.thumbnailSizes = thumbnailSizes.clone();
this.workspaceDAO = workspaceDAO;
}
@Override
public void perform() throws Exception {
at(1, 100, "opening workspace...");
| List<DocumentPage> pages = PagesInfoExtractor.pagesInfo(this.filePath); |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/background/job/GenerateDocumentData.java | // Path: src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java
// public class PagesInfoExtractor {
//
// @SuppressWarnings("Convert2Diamond")
// public static List<DocumentPage> pagesInfo(String pdfPath) throws IOException {
// PDDocument document = Utils.openPDF(pdfPath);
// ObjectExtractor extractor = new ObjectExtractor(document);
//
// ArrayList<DocumentPage> rv = new ArrayList<DocumentPage>();
//
// PageIterator it = extractor.extract();
// Page p;
// while (it.hasNext()) {
// p = it.next();
// rv.add(new DocumentPage(p.getWidth(), p.getHeight(), p.getPageNumber(), p.getRotation(), p.hasText()));
// }
//
// extractor.close();
//
// return rv;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDocument.java
// public class WorkspaceDocument {
// public String original_filename;
// public String id;
// public String time;
// public int page_count;
// public long size;
// public int[] thumbnail_sizes;
//
//
// public WorkspaceDocument(String original_filename, String id, String time, int page_count, long size,
// int[] thumbnail_sizes) {
// this.original_filename = original_filename;
// this.id = id;
// this.time = time;
// this.page_count = page_count;
// this.size = size;
// this.thumbnail_sizes = thumbnail_sizes.clone();
// }
//
//
//
// }
| import java.io.File;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;
import technology.tabula.tabula_web.extractor.PagesInfoExtractor;
import technology.tabula.tabula_web.workspace.DocumentPage;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceDocument; | package technology.tabula.tabula_web.background.job;
public class GenerateDocumentData extends Job {
String filePath;
String originalFilename;
String id;
int[] thumbnailSizes;
private WorkspaceDAO workspaceDAO;
public GenerateDocumentData(String filePath, String originalFilename, String id,
int[] thumbnailSizes, UUID batch, WorkspaceDAO workspaceDAO) {
super(batch);
this.filePath = filePath;
this.originalFilename = originalFilename;
this.id = id;
this.thumbnailSizes = thumbnailSizes.clone();
this.workspaceDAO = workspaceDAO;
}
@Override
public void perform() throws Exception {
at(1, 100, "opening workspace...");
| // Path: src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java
// public class PagesInfoExtractor {
//
// @SuppressWarnings("Convert2Diamond")
// public static List<DocumentPage> pagesInfo(String pdfPath) throws IOException {
// PDDocument document = Utils.openPDF(pdfPath);
// ObjectExtractor extractor = new ObjectExtractor(document);
//
// ArrayList<DocumentPage> rv = new ArrayList<DocumentPage>();
//
// PageIterator it = extractor.extract();
// Page p;
// while (it.hasNext()) {
// p = it.next();
// rv.add(new DocumentPage(p.getWidth(), p.getHeight(), p.getPageNumber(), p.getRotation(), p.hasText()));
// }
//
// extractor.close();
//
// return rv;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDocument.java
// public class WorkspaceDocument {
// public String original_filename;
// public String id;
// public String time;
// public int page_count;
// public long size;
// public int[] thumbnail_sizes;
//
//
// public WorkspaceDocument(String original_filename, String id, String time, int page_count, long size,
// int[] thumbnail_sizes) {
// this.original_filename = original_filename;
// this.id = id;
// this.time = time;
// this.page_count = page_count;
// this.size = size;
// this.thumbnail_sizes = thumbnail_sizes.clone();
// }
//
//
//
// }
// Path: src/main/java/technology/tabula/tabula_web/background/job/GenerateDocumentData.java
import java.io.File;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;
import technology.tabula.tabula_web.extractor.PagesInfoExtractor;
import technology.tabula.tabula_web.workspace.DocumentPage;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceDocument;
package technology.tabula.tabula_web.background.job;
public class GenerateDocumentData extends Job {
String filePath;
String originalFilename;
String id;
int[] thumbnailSizes;
private WorkspaceDAO workspaceDAO;
public GenerateDocumentData(String filePath, String originalFilename, String id,
int[] thumbnailSizes, UUID batch, WorkspaceDAO workspaceDAO) {
super(batch);
this.filePath = filePath;
this.originalFilename = originalFilename;
this.id = id;
this.thumbnailSizes = thumbnailSizes.clone();
this.workspaceDAO = workspaceDAO;
}
@Override
public void perform() throws Exception {
at(1, 100, "opening workspace...");
| List<DocumentPage> pages = PagesInfoExtractor.pagesInfo(this.filePath); |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/background/job/GenerateDocumentData.java | // Path: src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java
// public class PagesInfoExtractor {
//
// @SuppressWarnings("Convert2Diamond")
// public static List<DocumentPage> pagesInfo(String pdfPath) throws IOException {
// PDDocument document = Utils.openPDF(pdfPath);
// ObjectExtractor extractor = new ObjectExtractor(document);
//
// ArrayList<DocumentPage> rv = new ArrayList<DocumentPage>();
//
// PageIterator it = extractor.extract();
// Page p;
// while (it.hasNext()) {
// p = it.next();
// rv.add(new DocumentPage(p.getWidth(), p.getHeight(), p.getPageNumber(), p.getRotation(), p.hasText()));
// }
//
// extractor.close();
//
// return rv;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDocument.java
// public class WorkspaceDocument {
// public String original_filename;
// public String id;
// public String time;
// public int page_count;
// public long size;
// public int[] thumbnail_sizes;
//
//
// public WorkspaceDocument(String original_filename, String id, String time, int page_count, long size,
// int[] thumbnail_sizes) {
// this.original_filename = original_filename;
// this.id = id;
// this.time = time;
// this.page_count = page_count;
// this.size = size;
// this.thumbnail_sizes = thumbnail_sizes.clone();
// }
//
//
//
// }
| import java.io.File;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;
import technology.tabula.tabula_web.extractor.PagesInfoExtractor;
import technology.tabula.tabula_web.workspace.DocumentPage;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceDocument; | package technology.tabula.tabula_web.background.job;
public class GenerateDocumentData extends Job {
String filePath;
String originalFilename;
String id;
int[] thumbnailSizes;
private WorkspaceDAO workspaceDAO;
public GenerateDocumentData(String filePath, String originalFilename, String id,
int[] thumbnailSizes, UUID batch, WorkspaceDAO workspaceDAO) {
super(batch);
this.filePath = filePath;
this.originalFilename = originalFilename;
this.id = id;
this.thumbnailSizes = thumbnailSizes.clone();
this.workspaceDAO = workspaceDAO;
}
@Override
public void perform() throws Exception {
at(1, 100, "opening workspace...");
List<DocumentPage> pages = PagesInfoExtractor.pagesInfo(this.filePath);
| // Path: src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java
// public class PagesInfoExtractor {
//
// @SuppressWarnings("Convert2Diamond")
// public static List<DocumentPage> pagesInfo(String pdfPath) throws IOException {
// PDDocument document = Utils.openPDF(pdfPath);
// ObjectExtractor extractor = new ObjectExtractor(document);
//
// ArrayList<DocumentPage> rv = new ArrayList<DocumentPage>();
//
// PageIterator it = extractor.extract();
// Page p;
// while (it.hasNext()) {
// p = it.next();
// rv.add(new DocumentPage(p.getWidth(), p.getHeight(), p.getPageNumber(), p.getRotation(), p.hasText()));
// }
//
// extractor.close();
//
// return rv;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDAO.java
// public interface WorkspaceDAO {
//
// Workspace getWorkspace() throws WorkspaceException;
//
// void addDocument(WorkspaceDocument we, List<DocumentPage> pages) throws WorkspaceException;
//
// void deleteDocument(String documentId) throws WorkspaceException;
//
// WorkspaceDocument getDocumentMetadata(String documentId) throws WorkspaceException;
//
// List<DocumentPage> getDocumentPages(String documentId) throws WorkspaceException;
//
// String getDocumentPath(String documentId);
//
// String getDocumentDir(String documentId);
//
// String getDataDir();
//
// void addFile(InputStream stream, String documentId, String filename) throws WorkspaceException;
//
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/WorkspaceDocument.java
// public class WorkspaceDocument {
// public String original_filename;
// public String id;
// public String time;
// public int page_count;
// public long size;
// public int[] thumbnail_sizes;
//
//
// public WorkspaceDocument(String original_filename, String id, String time, int page_count, long size,
// int[] thumbnail_sizes) {
// this.original_filename = original_filename;
// this.id = id;
// this.time = time;
// this.page_count = page_count;
// this.size = size;
// this.thumbnail_sizes = thumbnail_sizes.clone();
// }
//
//
//
// }
// Path: src/main/java/technology/tabula/tabula_web/background/job/GenerateDocumentData.java
import java.io.File;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;
import technology.tabula.tabula_web.extractor.PagesInfoExtractor;
import technology.tabula.tabula_web.workspace.DocumentPage;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.tabula_web.workspace.WorkspaceDocument;
package technology.tabula.tabula_web.background.job;
public class GenerateDocumentData extends Job {
String filePath;
String originalFilename;
String id;
int[] thumbnailSizes;
private WorkspaceDAO workspaceDAO;
public GenerateDocumentData(String filePath, String originalFilename, String id,
int[] thumbnailSizes, UUID batch, WorkspaceDAO workspaceDAO) {
super(batch);
this.filePath = filePath;
this.originalFilename = originalFilename;
this.id = id;
this.thumbnailSizes = thumbnailSizes.clone();
this.workspaceDAO = workspaceDAO;
}
@Override
public void perform() throws Exception {
at(1, 100, "opening workspace...");
List<DocumentPage> pages = PagesInfoExtractor.pagesInfo(this.filePath);
| WorkspaceDocument we = new WorkspaceDocument(originalFilename, id, |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/background/JobExecutor.java | // Path: src/main/java/technology/tabula/tabula_web/background/job/Job.java
// public abstract class Job implements Callable<String> {
//
// private UUID uuid;
// private UUID batch;
// private JobStatus status;
//
// final static Logger logger = LoggerFactory.getLogger(JobExecutor.class);
//
// public Job(UUID batch) {
// this.uuid = UUID.randomUUID();
// this.batch = batch;
// this.status = new JobStatus();
// }
//
// public String getUUID() {
// return this.uuid.toString();
// }
//
// public String getBatch() {
// return this.batch.toString();
// }
//
// @Override
// public String call() throws Exception {
// this.status.status = JobStatus.STATUS.WORKING;
// this.status.startedOn = LocalDateTime.now();
//
// logger.info("Starting job {} {}", this.getUUID(), this.getClass().getName());
// perform();
// return this.getUUID();
// }
//
// public int percentComplete() {
// switch (this.status.status) {
// case COMPLETED:
// return 100;
// case QUEUED:
// return 0;
// default:
// int t = status.total == 0 ? 1 : status.total;
// return status.num / t;
// }
// }
//
// public void at(int num, int total, String message) {
// this.status.status = JobStatus.STATUS.WORKING;
// this.status.num = num;
// this.status.total = total;
// this.status.message = message;
// }
//
// public boolean isFailed() {
// return this.status.status == JobStatus.STATUS.FAILED;
// }
// public boolean isWorking() {
// return this.status.status == JobStatus.STATUS.WORKING;
// }
//
// public abstract void perform() throws Exception;
// }
| import java.util.List;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import technology.tabula.tabula_web.background.job.Job; | package technology.tabula.tabula_web.background;
public class JobExecutor extends ThreadPoolExecutor {
@SuppressWarnings("Convert2Diamond") | // Path: src/main/java/technology/tabula/tabula_web/background/job/Job.java
// public abstract class Job implements Callable<String> {
//
// private UUID uuid;
// private UUID batch;
// private JobStatus status;
//
// final static Logger logger = LoggerFactory.getLogger(JobExecutor.class);
//
// public Job(UUID batch) {
// this.uuid = UUID.randomUUID();
// this.batch = batch;
// this.status = new JobStatus();
// }
//
// public String getUUID() {
// return this.uuid.toString();
// }
//
// public String getBatch() {
// return this.batch.toString();
// }
//
// @Override
// public String call() throws Exception {
// this.status.status = JobStatus.STATUS.WORKING;
// this.status.startedOn = LocalDateTime.now();
//
// logger.info("Starting job {} {}", this.getUUID(), this.getClass().getName());
// perform();
// return this.getUUID();
// }
//
// public int percentComplete() {
// switch (this.status.status) {
// case COMPLETED:
// return 100;
// case QUEUED:
// return 0;
// default:
// int t = status.total == 0 ? 1 : status.total;
// return status.num / t;
// }
// }
//
// public void at(int num, int total, String message) {
// this.status.status = JobStatus.STATUS.WORKING;
// this.status.num = num;
// this.status.total = total;
// this.status.message = message;
// }
//
// public boolean isFailed() {
// return this.status.status == JobStatus.STATUS.FAILED;
// }
// public boolean isWorking() {
// return this.status.status == JobStatus.STATUS.WORKING;
// }
//
// public abstract void perform() throws Exception;
// }
// Path: src/main/java/technology/tabula/tabula_web/background/JobExecutor.java
import java.util.List;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import technology.tabula.tabula_web.background.job.Job;
package technology.tabula.tabula_web.background;
public class JobExecutor extends ThreadPoolExecutor {
@SuppressWarnings("Convert2Diamond") | private Map<String, Job> jobs = new ConcurrentHashMap<String, Job>(); |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java | // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
import technology.tabula.PageIterator;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.DocumentPage; | package technology.tabula.tabula_web.extractor;
public class PagesInfoExtractor {
@SuppressWarnings("Convert2Diamond") | // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
// Path: src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
import technology.tabula.PageIterator;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.DocumentPage;
package technology.tabula.tabula_web.extractor;
public class PagesInfoExtractor {
@SuppressWarnings("Convert2Diamond") | public static List<DocumentPage> pagesInfo(String pdfPath) throws IOException { |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java | // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
import technology.tabula.PageIterator;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.DocumentPage; | package technology.tabula.tabula_web.extractor;
public class PagesInfoExtractor {
@SuppressWarnings("Convert2Diamond")
public static List<DocumentPage> pagesInfo(String pdfPath) throws IOException { | // Path: src/main/java/technology/tabula/tabula_web/Utils.java
// public class Utils {
//
// private static final String DEFAULT_PASSWORD = "";
//
// public static PDDocument openPDF(String documentPath) throws IOException {
// PDDocument document = PDDocument.load(new File(documentPath));
// if (document.isEncrypted()) {
// document.close();
// document = PDDocument.load(new File(documentPath), DEFAULT_PASSWORD);
// document.setAllSecurityToBeRemoved(true);
// }
// return document;
// }
// }
//
// Path: src/main/java/technology/tabula/tabula_web/workspace/DocumentPage.java
// public class DocumentPage {
//
// public double width;
// public double height;
// public int number;
// public int rotation;
// public boolean hasText;
//
// public DocumentPage(double width, double height, int number, int rotation, boolean hasText) {
// this.width = width;
// this.height = height;
// this.number = number;
// this.rotation = rotation;
// this.hasText = hasText;
// }
// }
// Path: src/main/java/technology/tabula/tabula_web/extractor/PagesInfoExtractor.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
import technology.tabula.PageIterator;
import technology.tabula.tabula_web.Utils;
import technology.tabula.tabula_web.workspace.DocumentPage;
package technology.tabula.tabula_web.extractor;
public class PagesInfoExtractor {
@SuppressWarnings("Convert2Diamond")
public static List<DocumentPage> pagesInfo(String pdfPath) throws IOException { | PDDocument document = Utils.openPDF(pdfPath); |
AngelaFabregues/dipGame | gameManager/src/org/dipgame/gameManager/LogFrame.java | // Path: gameManager/src/org/dipgame/gameManager/utils/BareBonesBrowserLaunch.java
// public class BareBonesBrowserLaunch {
//
// static final String[] browsers = { "google-chrome", "firefox", "opera",
// "epiphany", "konqueror", "conkeror", "midori", "kazehakase",
// "mozilla" };
// static final String errMsg = "Error attempting to launch web browser";
//
// public static void openURL(String url) {
// try { // attempt to use Desktop library from JDK 1.6+
// Class<?> d = Class.forName("java.awt.Desktop");
// d.getDeclaredMethod("browse", new Class[] { java.net.URI.class })
// .invoke(d.getDeclaredMethod("getDesktop").invoke(null),
// new Object[] { java.net.URI.create(url) });
// // above code mimicks: java.awt.Desktop.getDesktop().browse()
// } catch (Exception ignore) { // library not available or failed
// String osName = System.getProperty("os.name");
// try {
// if (osName.startsWith("Mac OS")) {
// Class.forName("com.apple.eio.FileManager")
// .getDeclaredMethod("openURL",
// new Class[] { String.class })
// .invoke(null, new Object[] { url });
// } else if (osName.startsWith("Windows"))
// Runtime.getRuntime().exec(
// "rundll32 url.dll,FileProtocolHandler " + url);
// else { // assume Unix or Linux
// String browser = null;
// for (String b : browsers)
// if (browser == null
// && Runtime.getRuntime()
// .exec(new String[] { "which", b })
// .getInputStream().read() != -1)
// Runtime.getRuntime().exec(
// new String[] { browser = b, url });
// if (browser == null)
// throw new Exception(Arrays.toString(browsers));
// }
// } catch (Exception e) {
// JOptionPane.showMessageDialog(null,
// errMsg + "\n" + e.toString());
// }
// }
// }
//
// }
| import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.dipgame.gameManager.utils.BareBonesBrowserLaunch; | @Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentResized(ComponentEvent e) {
setSizes();
revalidateAll();
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
});
gameMainPanel = new JPanel();
gameMainPanel.setPreferredSize(this.getSize());
gameMainPanel.setBackground(Utils.CYAN);
BoxLayout boxLayout = new BoxLayout(gameMainPanel, BoxLayout.Y_AXIS);
gameMainPanel.setLayout(boxLayout);
gameMainPanel.add(MainPanel.createHeader());
MouseAdapter adapter = new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) { | // Path: gameManager/src/org/dipgame/gameManager/utils/BareBonesBrowserLaunch.java
// public class BareBonesBrowserLaunch {
//
// static final String[] browsers = { "google-chrome", "firefox", "opera",
// "epiphany", "konqueror", "conkeror", "midori", "kazehakase",
// "mozilla" };
// static final String errMsg = "Error attempting to launch web browser";
//
// public static void openURL(String url) {
// try { // attempt to use Desktop library from JDK 1.6+
// Class<?> d = Class.forName("java.awt.Desktop");
// d.getDeclaredMethod("browse", new Class[] { java.net.URI.class })
// .invoke(d.getDeclaredMethod("getDesktop").invoke(null),
// new Object[] { java.net.URI.create(url) });
// // above code mimicks: java.awt.Desktop.getDesktop().browse()
// } catch (Exception ignore) { // library not available or failed
// String osName = System.getProperty("os.name");
// try {
// if (osName.startsWith("Mac OS")) {
// Class.forName("com.apple.eio.FileManager")
// .getDeclaredMethod("openURL",
// new Class[] { String.class })
// .invoke(null, new Object[] { url });
// } else if (osName.startsWith("Windows"))
// Runtime.getRuntime().exec(
// "rundll32 url.dll,FileProtocolHandler " + url);
// else { // assume Unix or Linux
// String browser = null;
// for (String b : browsers)
// if (browser == null
// && Runtime.getRuntime()
// .exec(new String[] { "which", b })
// .getInputStream().read() != -1)
// Runtime.getRuntime().exec(
// new String[] { browser = b, url });
// if (browser == null)
// throw new Exception(Arrays.toString(browsers));
// }
// } catch (Exception e) {
// JOptionPane.showMessageDialog(null,
// errMsg + "\n" + e.toString());
// }
// }
// }
//
// }
// Path: gameManager/src/org/dipgame/gameManager/LogFrame.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.dipgame.gameManager.utils.BareBonesBrowserLaunch;
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentResized(ComponentEvent e) {
setSizes();
revalidateAll();
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
});
gameMainPanel = new JPanel();
gameMainPanel.setPreferredSize(this.getSize());
gameMainPanel.setBackground(Utils.CYAN);
BoxLayout boxLayout = new BoxLayout(gameMainPanel, BoxLayout.Y_AXIS);
gameMainPanel.setLayout(boxLayout);
gameMainPanel.add(MainPanel.createHeader());
MouseAdapter adapter = new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) { | BareBonesBrowserLaunch.openURL("http://www.dipgame.org/browse/gameManager"); |
AngelaFabregues/dipGame | dip/src/es/csic/iiia/fabregues/dip/orders/SUPOrder.java | // Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java
// public class Power {
//
// private String name;
//
// private List<Province> own;
// private List<Province> homes;
// private List<Region> control;
//
// public Power(String name) {
// this.name = name;
//
// resetControl();
//
// resetOwn();
// homes = new ArrayList<Province>();
//
// }
//
// public String getName() {
// return name;
// }
//
// public void addControlledRegion(Region region){
// control.add(region);
// }
//
// public List<Region> getControlledRegions() {
// return control;
// }
//
// public boolean isControlling(Region region){
// return control.contains(region);
// }
//
// /**
// * Returns true if the province is a SC owned by the power or false otherwise.
// * @param Province
// * @return
// */
// public boolean isOwning(Province Province){
// if(Province instanceof Province){
// return own.contains((Province)Province);
// }
// return false;
// }
//
// public List<Province> getOwnedSCs() {
// return own;
// }
//
// public void resetControl() {
// control = new Vector<Region>();
// }
//
// public void addOwn(Province sc) {
// own.add(sc);
// }
//
// public void resetOwn() {
// own = new Vector<Province>();
// }
//
// public void addHome(Province province) {
// homes.add(province);
// }
//
// public List<Province> getHomes() {
// return homes;
// }
//
// public String toString(){
// return name;
// }
//
// public boolean isControlling(Province province) {
// for(Region region: province.getRegions()){
// if(isControlling(region)){
// return true;
// }
// }
// return false;
// }
//
// public boolean equals(Object o){
// if(o instanceof Power){
// Power power = (Power) o;
// return name.equals(power.getName());
// }
// return super.equals(o);
// }
// }
//
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java
// public class Region {
//
// private String name;
// private Province province;
// private Vector<Region> adjacentRegions;
//
// public Region(String name) {
// adjacentRegions = new Vector<Region>();
// this.name = name;
// }
//
// public Province getProvince() {
// return province;
// }
//
// public void setProvince(Province province) {
// this.province = province;
// }
//
// public String getName() {
// return name;
// }
//
// public void addAdjacentRegion(Region adjNode) {
// adjacentRegions.add(adjNode);
// }
//
// public Vector<Region> getAdjacentRegions() {
// return adjacentRegions;
// }
//
// public String toString() {
// return name;
// }
//
// public boolean equals(Object o){
// if(o instanceof Region){
// Region region = (Region) o;
// return name.equals(region.getName());
// }
// return super.equals(o);
// }
// }
| import es.csic.iiia.fabregues.dip.board.Power;
import es.csic.iiia.fabregues.dip.board.Region; | package es.csic.iiia.fabregues.dip.orders;
/**
* Support hold order
*
* @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es
*/
public class SUPOrder extends Order {
private Order supportedOrder;
| // Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java
// public class Power {
//
// private String name;
//
// private List<Province> own;
// private List<Province> homes;
// private List<Region> control;
//
// public Power(String name) {
// this.name = name;
//
// resetControl();
//
// resetOwn();
// homes = new ArrayList<Province>();
//
// }
//
// public String getName() {
// return name;
// }
//
// public void addControlledRegion(Region region){
// control.add(region);
// }
//
// public List<Region> getControlledRegions() {
// return control;
// }
//
// public boolean isControlling(Region region){
// return control.contains(region);
// }
//
// /**
// * Returns true if the province is a SC owned by the power or false otherwise.
// * @param Province
// * @return
// */
// public boolean isOwning(Province Province){
// if(Province instanceof Province){
// return own.contains((Province)Province);
// }
// return false;
// }
//
// public List<Province> getOwnedSCs() {
// return own;
// }
//
// public void resetControl() {
// control = new Vector<Region>();
// }
//
// public void addOwn(Province sc) {
// own.add(sc);
// }
//
// public void resetOwn() {
// own = new Vector<Province>();
// }
//
// public void addHome(Province province) {
// homes.add(province);
// }
//
// public List<Province> getHomes() {
// return homes;
// }
//
// public String toString(){
// return name;
// }
//
// public boolean isControlling(Province province) {
// for(Region region: province.getRegions()){
// if(isControlling(region)){
// return true;
// }
// }
// return false;
// }
//
// public boolean equals(Object o){
// if(o instanceof Power){
// Power power = (Power) o;
// return name.equals(power.getName());
// }
// return super.equals(o);
// }
// }
//
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java
// public class Region {
//
// private String name;
// private Province province;
// private Vector<Region> adjacentRegions;
//
// public Region(String name) {
// adjacentRegions = new Vector<Region>();
// this.name = name;
// }
//
// public Province getProvince() {
// return province;
// }
//
// public void setProvince(Province province) {
// this.province = province;
// }
//
// public String getName() {
// return name;
// }
//
// public void addAdjacentRegion(Region adjNode) {
// adjacentRegions.add(adjNode);
// }
//
// public Vector<Region> getAdjacentRegions() {
// return adjacentRegions;
// }
//
// public String toString() {
// return name;
// }
//
// public boolean equals(Object o){
// if(o instanceof Region){
// Region region = (Region) o;
// return name.equals(region.getName());
// }
// return super.equals(o);
// }
// }
// Path: dip/src/es/csic/iiia/fabregues/dip/orders/SUPOrder.java
import es.csic.iiia.fabregues.dip.board.Power;
import es.csic.iiia.fabregues.dip.board.Region;
package es.csic.iiia.fabregues.dip.orders;
/**
* Support hold order
*
* @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es
*/
public class SUPOrder extends Order {
private Order supportedOrder;
| public SUPOrder(Power power, Region region, Order supportedOrder) { |
AngelaFabregues/dipGame | dip/src/es/csic/iiia/fabregues/dip/orders/SUPOrder.java | // Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java
// public class Power {
//
// private String name;
//
// private List<Province> own;
// private List<Province> homes;
// private List<Region> control;
//
// public Power(String name) {
// this.name = name;
//
// resetControl();
//
// resetOwn();
// homes = new ArrayList<Province>();
//
// }
//
// public String getName() {
// return name;
// }
//
// public void addControlledRegion(Region region){
// control.add(region);
// }
//
// public List<Region> getControlledRegions() {
// return control;
// }
//
// public boolean isControlling(Region region){
// return control.contains(region);
// }
//
// /**
// * Returns true if the province is a SC owned by the power or false otherwise.
// * @param Province
// * @return
// */
// public boolean isOwning(Province Province){
// if(Province instanceof Province){
// return own.contains((Province)Province);
// }
// return false;
// }
//
// public List<Province> getOwnedSCs() {
// return own;
// }
//
// public void resetControl() {
// control = new Vector<Region>();
// }
//
// public void addOwn(Province sc) {
// own.add(sc);
// }
//
// public void resetOwn() {
// own = new Vector<Province>();
// }
//
// public void addHome(Province province) {
// homes.add(province);
// }
//
// public List<Province> getHomes() {
// return homes;
// }
//
// public String toString(){
// return name;
// }
//
// public boolean isControlling(Province province) {
// for(Region region: province.getRegions()){
// if(isControlling(region)){
// return true;
// }
// }
// return false;
// }
//
// public boolean equals(Object o){
// if(o instanceof Power){
// Power power = (Power) o;
// return name.equals(power.getName());
// }
// return super.equals(o);
// }
// }
//
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java
// public class Region {
//
// private String name;
// private Province province;
// private Vector<Region> adjacentRegions;
//
// public Region(String name) {
// adjacentRegions = new Vector<Region>();
// this.name = name;
// }
//
// public Province getProvince() {
// return province;
// }
//
// public void setProvince(Province province) {
// this.province = province;
// }
//
// public String getName() {
// return name;
// }
//
// public void addAdjacentRegion(Region adjNode) {
// adjacentRegions.add(adjNode);
// }
//
// public Vector<Region> getAdjacentRegions() {
// return adjacentRegions;
// }
//
// public String toString() {
// return name;
// }
//
// public boolean equals(Object o){
// if(o instanceof Region){
// Region region = (Region) o;
// return name.equals(region.getName());
// }
// return super.equals(o);
// }
// }
| import es.csic.iiia.fabregues.dip.board.Power;
import es.csic.iiia.fabregues.dip.board.Region; | package es.csic.iiia.fabregues.dip.orders;
/**
* Support hold order
*
* @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es
*/
public class SUPOrder extends Order {
private Order supportedOrder;
| // Path: dip/src/es/csic/iiia/fabregues/dip/board/Power.java
// public class Power {
//
// private String name;
//
// private List<Province> own;
// private List<Province> homes;
// private List<Region> control;
//
// public Power(String name) {
// this.name = name;
//
// resetControl();
//
// resetOwn();
// homes = new ArrayList<Province>();
//
// }
//
// public String getName() {
// return name;
// }
//
// public void addControlledRegion(Region region){
// control.add(region);
// }
//
// public List<Region> getControlledRegions() {
// return control;
// }
//
// public boolean isControlling(Region region){
// return control.contains(region);
// }
//
// /**
// * Returns true if the province is a SC owned by the power or false otherwise.
// * @param Province
// * @return
// */
// public boolean isOwning(Province Province){
// if(Province instanceof Province){
// return own.contains((Province)Province);
// }
// return false;
// }
//
// public List<Province> getOwnedSCs() {
// return own;
// }
//
// public void resetControl() {
// control = new Vector<Region>();
// }
//
// public void addOwn(Province sc) {
// own.add(sc);
// }
//
// public void resetOwn() {
// own = new Vector<Province>();
// }
//
// public void addHome(Province province) {
// homes.add(province);
// }
//
// public List<Province> getHomes() {
// return homes;
// }
//
// public String toString(){
// return name;
// }
//
// public boolean isControlling(Province province) {
// for(Region region: province.getRegions()){
// if(isControlling(region)){
// return true;
// }
// }
// return false;
// }
//
// public boolean equals(Object o){
// if(o instanceof Power){
// Power power = (Power) o;
// return name.equals(power.getName());
// }
// return super.equals(o);
// }
// }
//
// Path: dip/src/es/csic/iiia/fabregues/dip/board/Region.java
// public class Region {
//
// private String name;
// private Province province;
// private Vector<Region> adjacentRegions;
//
// public Region(String name) {
// adjacentRegions = new Vector<Region>();
// this.name = name;
// }
//
// public Province getProvince() {
// return province;
// }
//
// public void setProvince(Province province) {
// this.province = province;
// }
//
// public String getName() {
// return name;
// }
//
// public void addAdjacentRegion(Region adjNode) {
// adjacentRegions.add(adjNode);
// }
//
// public Vector<Region> getAdjacentRegions() {
// return adjacentRegions;
// }
//
// public String toString() {
// return name;
// }
//
// public boolean equals(Object o){
// if(o instanceof Region){
// Region region = (Region) o;
// return name.equals(region.getName());
// }
// return super.equals(o);
// }
// }
// Path: dip/src/es/csic/iiia/fabregues/dip/orders/SUPOrder.java
import es.csic.iiia.fabregues.dip.board.Power;
import es.csic.iiia.fabregues.dip.board.Region;
package es.csic.iiia.fabregues.dip.orders;
/**
* Support hold order
*
* @author Angela Fabregues, IIIA-CSIC, fabregues@iiia.csic.es
*/
public class SUPOrder extends Order {
private Order supportedOrder;
| public SUPOrder(Power power, Region region, Order supportedOrder) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.