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 |
|---|---|---|---|---|---|---|
ehsane/rainbownlp | src/main/java/rainbownlp/machinelearning/SVMLight.java | // Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public class ConfigurationUtil {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile = new Properties();
// static boolean loadedRNLPConfig = false;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// public static String[] getArrayValues(String key)
// {
// if(getValue(key)==null)
// return null;
// String[] arrayValues = getValue(key).split("\\|");
// return arrayValues;
// }
// public static void init()
// {
// if(!loadedRNLPConfig){
// Properties rnlpConfigFile = new Properties();
// try {
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream("configuration.conf");//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// rnlpConfigFile.load(config_file);
//
// configFile.putAll(rnlpConfigFile);
//
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//
// public static void init(String configurationFileName) throws IOException
// {
// init();
// configFile = new Properties();
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream(configurationFileName);//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// configFile.load(config_file);
// }
// public static void init(String configurationFileName, String hibernateConfigFile) throws IOException
// {
// init(configurationFileName);
// HibernateUtil.initialize("hibernate-oss.cfg.xml");
// }
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// String val = getValue(key);
// if(val==null) return 0;
// int result = Integer.parseInt(val);
// return result;
// }
//
// public static String getResourcePath(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResource(resourceName).getPath();
// }
//
// public static InputStream getResourceStream(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
//
//
//
// }
| import java.util.List;
import rainbownlp.util.ConfigurationUtil; | package rainbownlp.machinelearning;
public class SVMLight extends SVMLightBasedLearnerEngine {
private SVMLight()
{
}
@Override
public void test(List<MLExample> pTestExamples) throws Exception {
}
public static LearnerEngine getLearnerEngine(String pTaskName) {
SVMLight learnerEngine = new SVMLight();
learnerEngine.setTaskName(pTaskName);
return learnerEngine;
}
@Override
protected String getTrainCommand() { | // Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public class ConfigurationUtil {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile = new Properties();
// static boolean loadedRNLPConfig = false;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// public static String[] getArrayValues(String key)
// {
// if(getValue(key)==null)
// return null;
// String[] arrayValues = getValue(key).split("\\|");
// return arrayValues;
// }
// public static void init()
// {
// if(!loadedRNLPConfig){
// Properties rnlpConfigFile = new Properties();
// try {
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream("configuration.conf");//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// rnlpConfigFile.load(config_file);
//
// configFile.putAll(rnlpConfigFile);
//
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//
// public static void init(String configurationFileName) throws IOException
// {
// init();
// configFile = new Properties();
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream(configurationFileName);//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// configFile.load(config_file);
// }
// public static void init(String configurationFileName, String hibernateConfigFile) throws IOException
// {
// init(configurationFileName);
// HibernateUtil.initialize("hibernate-oss.cfg.xml");
// }
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// String val = getValue(key);
// if(val==null) return 0;
// int result = Integer.parseInt(val);
// return result;
// }
//
// public static String getResourcePath(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResource(resourceName).getPath();
// }
//
// public static InputStream getResourceStream(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
//
//
//
// }
// Path: src/main/java/rainbownlp/machinelearning/SVMLight.java
import java.util.List;
import rainbownlp.util.ConfigurationUtil;
package rainbownlp.machinelearning;
public class SVMLight extends SVMLightBasedLearnerEngine {
private SVMLight()
{
}
@Override
public void test(List<MLExample> pTestExamples) throws Exception {
}
public static LearnerEngine getLearnerEngine(String pTaskName) {
SVMLight learnerEngine = new SVMLight();
learnerEngine.setTaskName(pTaskName);
return learnerEngine;
}
@Override
protected String getTrainCommand() { | String trainCommand = ConfigurationUtil.getValue("SVMLightLearnerPath") |
ehsane/rainbownlp | src/main/java/rainbownlp/preprocess/SentenceDetector.java | // Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public class ConfigurationUtil {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile = new Properties();
// static boolean loadedRNLPConfig = false;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// public static String[] getArrayValues(String key)
// {
// if(getValue(key)==null)
// return null;
// String[] arrayValues = getValue(key).split("\\|");
// return arrayValues;
// }
// public static void init()
// {
// if(!loadedRNLPConfig){
// Properties rnlpConfigFile = new Properties();
// try {
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream("configuration.conf");//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// rnlpConfigFile.load(config_file);
//
// configFile.putAll(rnlpConfigFile);
//
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//
// public static void init(String configurationFileName) throws IOException
// {
// init();
// configFile = new Properties();
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream(configurationFileName);//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// configFile.load(config_file);
// }
// public static void init(String configurationFileName, String hibernateConfigFile) throws IOException
// {
// init(configurationFileName);
// HibernateUtil.initialize("hibernate-oss.cfg.xml");
// }
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// String val = getValue(key);
// if(val==null) return 0;
// int result = Integer.parseInt(val);
// return result;
// }
//
// public static String getResourcePath(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResource(resourceName).getPath();
// }
//
// public static InputStream getResourceStream(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
//
//
//
// }
| import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.util.Span;
import rainbownlp.util.ConfigurationUtil; | package rainbownlp.preprocess;
public class SentenceDetector {
SentenceDetectorME sentenceDetector = null;
public SentenceDetector() throws FileNotFoundException{ | // Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public class ConfigurationUtil {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile = new Properties();
// static boolean loadedRNLPConfig = false;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// public static String[] getArrayValues(String key)
// {
// if(getValue(key)==null)
// return null;
// String[] arrayValues = getValue(key).split("\\|");
// return arrayValues;
// }
// public static void init()
// {
// if(!loadedRNLPConfig){
// Properties rnlpConfigFile = new Properties();
// try {
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream("configuration.conf");//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// rnlpConfigFile.load(config_file);
//
// configFile.putAll(rnlpConfigFile);
//
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//
// public static void init(String configurationFileName) throws IOException
// {
// init();
// configFile = new Properties();
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream(configurationFileName);//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// configFile.load(config_file);
// }
// public static void init(String configurationFileName, String hibernateConfigFile) throws IOException
// {
// init(configurationFileName);
// HibernateUtil.initialize("hibernate-oss.cfg.xml");
// }
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// String val = getValue(key);
// if(val==null) return 0;
// int result = Integer.parseInt(val);
// return result;
// }
//
// public static String getResourcePath(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResource(resourceName).getPath();
// }
//
// public static InputStream getResourceStream(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
//
//
//
// }
// Path: src/main/java/rainbownlp/preprocess/SentenceDetector.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.util.Span;
import rainbownlp.util.ConfigurationUtil;
package rainbownlp.preprocess;
public class SentenceDetector {
SentenceDetectorME sentenceDetector = null;
public SentenceDetector() throws FileNotFoundException{ | InputStream modelIn = ConfigurationUtil.class.getClassLoader().getResourceAsStream("en-sent.bin"); |
ehsane/rainbownlp | src/main/java/rainbownlp/machinelearning/SVMLightRegression.java | // Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public class ConfigurationUtil {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile = new Properties();
// static boolean loadedRNLPConfig = false;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// public static String[] getArrayValues(String key)
// {
// if(getValue(key)==null)
// return null;
// String[] arrayValues = getValue(key).split("\\|");
// return arrayValues;
// }
// public static void init()
// {
// if(!loadedRNLPConfig){
// Properties rnlpConfigFile = new Properties();
// try {
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream("configuration.conf");//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// rnlpConfigFile.load(config_file);
//
// configFile.putAll(rnlpConfigFile);
//
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//
// public static void init(String configurationFileName) throws IOException
// {
// init();
// configFile = new Properties();
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream(configurationFileName);//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// configFile.load(config_file);
// }
// public static void init(String configurationFileName, String hibernateConfigFile) throws IOException
// {
// init(configurationFileName);
// HibernateUtil.initialize("hibernate-oss.cfg.xml");
// }
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// String val = getValue(key);
// if(val==null) return 0;
// int result = Integer.parseInt(val);
// return result;
// }
//
// public static String getResourcePath(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResource(resourceName).getPath();
// }
//
// public static InputStream getResourceStream(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
//
//
//
// }
| import rainbownlp.util.ConfigurationUtil; | package rainbownlp.machinelearning;
public class SVMLightRegression extends SVMLightBasedLearnerEngine {
private SVMLightRegression()
{
}
public static LearnerEngine getLearnerEngine(String pTaskName) {
SVMLightRegression learnerEngine = new SVMLightRegression();
learnerEngine.setTaskName(pTaskName);
return learnerEngine;
}
@Override
protected boolean isBinaryClassification() {
return false;
}
@Override
protected String getTrainCommand() {
String myShellScript = | // Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public class ConfigurationUtil {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile = new Properties();
// static boolean loadedRNLPConfig = false;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// public static String[] getArrayValues(String key)
// {
// if(getValue(key)==null)
// return null;
// String[] arrayValues = getValue(key).split("\\|");
// return arrayValues;
// }
// public static void init()
// {
// if(!loadedRNLPConfig){
// Properties rnlpConfigFile = new Properties();
// try {
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream("configuration.conf");//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// rnlpConfigFile.load(config_file);
//
// configFile.putAll(rnlpConfigFile);
//
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//
// public static void init(String configurationFileName) throws IOException
// {
// init();
// configFile = new Properties();
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream(configurationFileName);//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// configFile.load(config_file);
// }
// public static void init(String configurationFileName, String hibernateConfigFile) throws IOException
// {
// init(configurationFileName);
// HibernateUtil.initialize("hibernate-oss.cfg.xml");
// }
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// String val = getValue(key);
// if(val==null) return 0;
// int result = Integer.parseInt(val);
// return result;
// }
//
// public static String getResourcePath(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResource(resourceName).getPath();
// }
//
// public static InputStream getResourceStream(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
//
//
//
// }
// Path: src/main/java/rainbownlp/machinelearning/SVMLightRegression.java
import rainbownlp.util.ConfigurationUtil;
package rainbownlp.machinelearning;
public class SVMLightRegression extends SVMLightBasedLearnerEngine {
private SVMLightRegression()
{
}
public static LearnerEngine getLearnerEngine(String pTaskName) {
SVMLightRegression learnerEngine = new SVMLightRegression();
learnerEngine.setTaskName(pTaskName);
return learnerEngine;
}
@Override
protected boolean isBinaryClassification() {
return false;
}
@Override
protected String getTrainCommand() {
String myShellScript = | ConfigurationUtil.getValue("SVMLightLearnerPath") |
ehsane/rainbownlp | src/main/java/rainbownlp/analyzer/sentenceclause/Clause.java | // Path: src/main/java/rainbownlp/parser/DependencyLine.java
// public class DependencyLine {
// public String relationName;
// public String firstPart;
// public String secondPart;
// public int firstOffset;
// public int secondOffset;
// public boolean hasWord(String word) {
// if(firstPart.equals(word) ||
// secondPart.equals(word))
// return true;
// return false;
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import rainbownlp.parser.DependencyLine; | package rainbownlp.analyzer.sentenceclause;
public class Clause implements Cloneable, Comparable<Clause>{
@Override
protected Clause clone() throws CloneNotSupportedException {
Clause newClause = new Clause();
newClause.clauseSubject = clauseSubject;
newClause.clauseVerb = clauseVerb;
newClause.clauseObject = clauseObject;
newClause.clauseIObjPrep = clauseIObjPrep;
newClause.conjuctedLines = conjuctedLines;
newClause.isNegated = isNegated;
newClause.clauseMark =clauseMark;
newClause.isPleasant = isPleasant;
newClause.clauseComplements = clauseComplements;
newClause.complement = complement;
newClause.complementOffset = complementOffset;
newClause.modifierDepMap = modifierDepMap;
newClause.conjuctedBut = conjuctedBut;
newClause.clauseSubjStrings = clauseSubjStrings;
newClause.clauseIObjs = clauseIObjs;
newClause.isMarked = isMarked;
newClause.adjModifierDepMap=adjModifierDepMap;
//newClause.offsetMap = offsetMap;
return newClause;
}
| // Path: src/main/java/rainbownlp/parser/DependencyLine.java
// public class DependencyLine {
// public String relationName;
// public String firstPart;
// public String secondPart;
// public int firstOffset;
// public int secondOffset;
// public boolean hasWord(String word) {
// if(firstPart.equals(word) ||
// secondPart.equals(word))
// return true;
// return false;
// }
// }
// Path: src/main/java/rainbownlp/analyzer/sentenceclause/Clause.java
import java.util.ArrayList;
import java.util.HashMap;
import rainbownlp.parser.DependencyLine;
package rainbownlp.analyzer.sentenceclause;
public class Clause implements Cloneable, Comparable<Clause>{
@Override
protected Clause clone() throws CloneNotSupportedException {
Clause newClause = new Clause();
newClause.clauseSubject = clauseSubject;
newClause.clauseVerb = clauseVerb;
newClause.clauseObject = clauseObject;
newClause.clauseIObjPrep = clauseIObjPrep;
newClause.conjuctedLines = conjuctedLines;
newClause.isNegated = isNegated;
newClause.clauseMark =clauseMark;
newClause.isPleasant = isPleasant;
newClause.clauseComplements = clauseComplements;
newClause.complement = complement;
newClause.complementOffset = complementOffset;
newClause.modifierDepMap = modifierDepMap;
newClause.conjuctedBut = conjuctedBut;
newClause.clauseSubjStrings = clauseSubjStrings;
newClause.clauseIObjs = clauseIObjs;
newClause.isMarked = isMarked;
newClause.adjModifierDepMap=adjModifierDepMap;
//newClause.offsetMap = offsetMap;
return newClause;
}
| public ArrayList<DependencyLine> clauseSubject; |
ehsane/rainbownlp | src/main/java/rainbownlp/machinelearning/SVMMultiClass.java | // Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public class ConfigurationUtil {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile = new Properties();
// static boolean loadedRNLPConfig = false;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// public static String[] getArrayValues(String key)
// {
// if(getValue(key)==null)
// return null;
// String[] arrayValues = getValue(key).split("\\|");
// return arrayValues;
// }
// public static void init()
// {
// if(!loadedRNLPConfig){
// Properties rnlpConfigFile = new Properties();
// try {
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream("configuration.conf");//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// rnlpConfigFile.load(config_file);
//
// configFile.putAll(rnlpConfigFile);
//
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//
// public static void init(String configurationFileName) throws IOException
// {
// init();
// configFile = new Properties();
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream(configurationFileName);//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// configFile.load(config_file);
// }
// public static void init(String configurationFileName, String hibernateConfigFile) throws IOException
// {
// init(configurationFileName);
// HibernateUtil.initialize("hibernate-oss.cfg.xml");
// }
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// String val = getValue(key);
// if(val==null) return 0;
// int result = Integer.parseInt(val);
// return result;
// }
//
// public static String getResourcePath(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResource(resourceName).getPath();
// }
//
// public static InputStream getResourceStream(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
//
//
//
// }
| import rainbownlp.util.ConfigurationUtil; | package rainbownlp.machinelearning;
public class SVMMultiClass extends SVMLightBasedLearnerEngine {
String modelFile;
String taskName;
String trainFile;
String testFile;
private SVMMultiClass()
{
}
public static LearnerEngine getLearnerEngine(String pTaskName) {
SVMMultiClass learnerEngine = new SVMMultiClass();
learnerEngine.setTaskName(pTaskName);
return learnerEngine;
}
@Override
protected boolean isBinaryClassification() {
return false;
}
@Override
protected String getTrainCommand() {
String myShellScript = | // Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public class ConfigurationUtil {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile = new Properties();
// static boolean loadedRNLPConfig = false;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// public static String[] getArrayValues(String key)
// {
// if(getValue(key)==null)
// return null;
// String[] arrayValues = getValue(key).split("\\|");
// return arrayValues;
// }
// public static void init()
// {
// if(!loadedRNLPConfig){
// Properties rnlpConfigFile = new Properties();
// try {
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream("configuration.conf");//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// rnlpConfigFile.load(config_file);
//
// configFile.putAll(rnlpConfigFile);
//
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//
// public static void init(String configurationFileName) throws IOException
// {
// init();
// configFile = new Properties();
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream(configurationFileName);//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// configFile.load(config_file);
// }
// public static void init(String configurationFileName, String hibernateConfigFile) throws IOException
// {
// init(configurationFileName);
// HibernateUtil.initialize("hibernate-oss.cfg.xml");
// }
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// String val = getValue(key);
// if(val==null) return 0;
// int result = Integer.parseInt(val);
// return result;
// }
//
// public static String getResourcePath(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResource(resourceName).getPath();
// }
//
// public static InputStream getResourceStream(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
//
//
//
// }
// Path: src/main/java/rainbownlp/machinelearning/SVMMultiClass.java
import rainbownlp.util.ConfigurationUtil;
package rainbownlp.machinelearning;
public class SVMMultiClass extends SVMLightBasedLearnerEngine {
String modelFile;
String taskName;
String trainFile;
String testFile;
private SVMMultiClass()
{
}
public static LearnerEngine getLearnerEngine(String pTaskName) {
SVMMultiClass learnerEngine = new SVMMultiClass();
learnerEngine.setTaskName(pTaskName);
return learnerEngine;
}
@Override
protected boolean isBinaryClassification() {
return false;
}
@Override
protected String getTrainCommand() {
String myShellScript = | ConfigurationUtil.getValue("SVMMulticlassLearnerPath") |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteNetworkConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to create the input xml for DiscreteSpatialPhyloSimulator,
* specifically for a network.
* It reads the edge list from edgeList.csv, assumes 1 host per deme, and infection parameters, and writes example_network_params.xml
* @author Samantha Lycett
* @version 29 Dec 2014
*
*/
public class WriteNetworkConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
String edgeListName = "example_network_edgeList.csv";
ReadEdgeList edgeList;
String dn = "N";
| // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteNetworkConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to create the input xml for DiscreteSpatialPhyloSimulator,
* specifically for a network.
* It reads the edge list from edgeList.csv, assumes 1 host per deme, and infection parameters, and writes example_network_params.xml
* @author Samantha Lycett
* @version 29 Dec 2014
*
*/
public class WriteNetworkConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
String edgeListName = "example_network_edgeList.csv";
ReadEdgeList edgeList;
String dn = "N";
| Sampler theSampler = new JustBeforeRecoverySampler(); |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteNetworkConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to create the input xml for DiscreteSpatialPhyloSimulator,
* specifically for a network.
* It reads the edge list from edgeList.csv, assumes 1 host per deme, and infection parameters, and writes example_network_params.xml
* @author Samantha Lycett
* @version 29 Dec 2014
*
*/
public class WriteNetworkConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
String edgeListName = "example_network_edgeList.csv";
ReadEdgeList edgeList;
String dn = "N";
| // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteNetworkConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to create the input xml for DiscreteSpatialPhyloSimulator,
* specifically for a network.
* It reads the edge list from edgeList.csv, assumes 1 host per deme, and infection parameters, and writes example_network_params.xml
* @author Samantha Lycett
* @version 29 Dec 2014
*
*/
public class WriteNetworkConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
String edgeListName = "example_network_edgeList.csv";
ReadEdgeList edgeList;
String dn = "N";
| Sampler theSampler = new JustBeforeRecoverySampler(); |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteNetworkConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to create the input xml for DiscreteSpatialPhyloSimulator,
* specifically for a network.
* It reads the edge list from edgeList.csv, assumes 1 host per deme, and infection parameters, and writes example_network_params.xml
* @author Samantha Lycett
* @version 29 Dec 2014
*
*/
public class WriteNetworkConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
String edgeListName = "example_network_edgeList.csv";
ReadEdgeList edgeList;
String dn = "N";
Sampler theSampler = new JustBeforeRecoverySampler(); | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteNetworkConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to create the input xml for DiscreteSpatialPhyloSimulator,
* specifically for a network.
* It reads the edge list from edgeList.csv, assumes 1 host per deme, and infection parameters, and writes example_network_params.xml
* @author Samantha Lycett
* @version 29 Dec 2014
*
*/
public class WriteNetworkConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
String edgeListName = "example_network_edgeList.csv";
ReadEdgeList edgeList;
String dn = "N";
Sampler theSampler = new JustBeforeRecoverySampler(); | PopulationType popType = PopulationType.NETWORK; |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteNetworkConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to create the input xml for DiscreteSpatialPhyloSimulator,
* specifically for a network.
* It reads the edge list from edgeList.csv, assumes 1 host per deme, and infection parameters, and writes example_network_params.xml
* @author Samantha Lycett
* @version 29 Dec 2014
*
*/
public class WriteNetworkConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
String edgeListName = "example_network_edgeList.csv";
ReadEdgeList edgeList;
String dn = "N";
Sampler theSampler = new JustBeforeRecoverySampler();
PopulationType popType = PopulationType.NETWORK; | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteNetworkConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to create the input xml for DiscreteSpatialPhyloSimulator,
* specifically for a network.
* It reads the edge list from edgeList.csv, assumes 1 host per deme, and infection parameters, and writes example_network_params.xml
* @author Samantha Lycett
* @version 29 Dec 2014
*
*/
public class WriteNetworkConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
String edgeListName = "example_network_edgeList.csv";
ReadEdgeList edgeList;
String dn = "N";
Sampler theSampler = new JustBeforeRecoverySampler();
PopulationType popType = PopulationType.NETWORK; | ModelType modelType = ModelType.SIR; |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/networks/SpatialModelNetwork.java | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
| import io.Parameter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*; | package networks;
/**
*
* @author slycett
* @created 23 July 2014
* @version 24 July 2014
*/
public class SpatialModelNetwork implements Network {
List<NetworkNode> nodes;
NetworkModelType modelType = NetworkModelType.GRAVITY_MODEL; | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
// Path: src/networks/SpatialModelNetwork.java
import io.Parameter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
package networks;
/**
*
* @author slycett
* @created 23 July 2014
* @version 24 July 2014
*/
public class SpatialModelNetwork implements Network {
List<NetworkNode> nodes;
NetworkModelType modelType = NetworkModelType.GRAVITY_MODEL; | List<Parameter> params; |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/individualBasedModel/Sampler.java | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
| import io.Parameter;
import java.util.List; | package individualBasedModel;
/**
* inferface for classes generating SAMPLING events
* @author sam
* @created 25 June 2013
* @version 1 July 2013
* @version 4 July 2013 - using Parameters
*/
public interface Sampler {
/**
* generate sampling events from the population
* @param thePopulation
* @param actionTime
* @return
*/
List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
/**
* generated sampling events based on this event (e.g. infection, recovery)
* @param e
* @return
*/
List<Event> generateSamplingEvents(Event e);
/**
* return parameter,value pairs for use with Logger etc
* @return
*/
List<String[]> getSamplerParameterList();
/**
* set parameters from parameter,value pairs
* @param params
*/
//void setSamplerParameters( List<String[]> params); | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
// Path: src/individualBasedModel/Sampler.java
import io.Parameter;
import java.util.List;
package individualBasedModel;
/**
* inferface for classes generating SAMPLING events
* @author sam
* @created 25 June 2013
* @version 1 July 2013
* @version 4 July 2013 - using Parameters
*/
public interface Sampler {
/**
* generate sampling events from the population
* @param thePopulation
* @param actionTime
* @return
*/
List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
/**
* generated sampling events based on this event (e.g. infection, recovery)
* @param e
* @return
*/
List<Event> generateSamplingEvents(Event e);
/**
* return parameter,value pairs for use with Logger etc
* @return
*/
List<String[]> getSamplerParameterList();
/**
* set parameters from parameter,value pairs
* @param params
*/
//void setSamplerParameters( List<String[]> params); | void setSamplerParameters( List<Parameter> params); |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteNetworkShapeConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to write specific network shape configuration xmls, e.g. FULL, RANDOM, LINE, STAR etc
* @author slycett
* @version 29 Dec 2014
* @version 23 Mar 2015
*/
public class WriteNetworkShapeConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
| // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteNetworkShapeConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to write specific network shape configuration xmls, e.g. FULL, RANDOM, LINE, STAR etc
* @author slycett
* @version 29 Dec 2014
* @version 23 Mar 2015
*/
public class WriteNetworkShapeConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
| Sampler theSampler = new JustBeforeRecoverySampler(); |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteNetworkShapeConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to write specific network shape configuration xmls, e.g. FULL, RANDOM, LINE, STAR etc
* @author slycett
* @version 29 Dec 2014
* @version 23 Mar 2015
*/
public class WriteNetworkShapeConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
| // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteNetworkShapeConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to write specific network shape configuration xmls, e.g. FULL, RANDOM, LINE, STAR etc
* @author slycett
* @version 29 Dec 2014
* @version 23 Mar 2015
*/
public class WriteNetworkShapeConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
| Sampler theSampler = new JustBeforeRecoverySampler(); |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteNetworkShapeConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to write specific network shape configuration xmls, e.g. FULL, RANDOM, LINE, STAR etc
* @author slycett
* @version 29 Dec 2014
* @version 23 Mar 2015
*/
public class WriteNetworkShapeConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
Sampler theSampler = new JustBeforeRecoverySampler();
| // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteNetworkShapeConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to write specific network shape configuration xmls, e.g. FULL, RANDOM, LINE, STAR etc
* @author slycett
* @version 29 Dec 2014
* @version 23 Mar 2015
*/
public class WriteNetworkShapeConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
Sampler theSampler = new JustBeforeRecoverySampler();
| PopulationType popType = PopulationType.RANDOM; |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteNetworkShapeConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to write specific network shape configuration xmls, e.g. FULL, RANDOM, LINE, STAR etc
* @author slycett
* @version 29 Dec 2014
* @version 23 Mar 2015
*/
public class WriteNetworkShapeConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
Sampler theSampler = new JustBeforeRecoverySampler();
PopulationType popType = PopulationType.RANDOM;
double probConnect = 0.1; | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteNetworkShapeConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to write specific network shape configuration xmls, e.g. FULL, RANDOM, LINE, STAR etc
* @author slycett
* @version 29 Dec 2014
* @version 23 Mar 2015
*/
public class WriteNetworkShapeConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
Sampler theSampler = new JustBeforeRecoverySampler();
PopulationType popType = PopulationType.RANDOM;
double probConnect = 0.1; | String demeType = DemeType.INFECTION_OVER_NETWORK.toString(); |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteNetworkShapeConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to write specific network shape configuration xmls, e.g. FULL, RANDOM, LINE, STAR etc
* @author slycett
* @version 29 Dec 2014
* @version 23 Mar 2015
*/
public class WriteNetworkShapeConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
Sampler theSampler = new JustBeforeRecoverySampler();
PopulationType popType = PopulationType.RANDOM;
double probConnect = 0.1;
String demeType = DemeType.INFECTION_OVER_NETWORK.toString();
String dirType = "FALSE";
int numberOfDemes = 100;
int hostsInDeme = 1;
double pinfectother = 1;
| // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteNetworkShapeConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to write specific network shape configuration xmls, e.g. FULL, RANDOM, LINE, STAR etc
* @author slycett
* @version 29 Dec 2014
* @version 23 Mar 2015
*/
public class WriteNetworkShapeConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
long seed = -1;
int nreps = 1;
double tauleap = 0;
Sampler theSampler = new JustBeforeRecoverySampler();
PopulationType popType = PopulationType.RANDOM;
double probConnect = 0.1;
String demeType = DemeType.INFECTION_OVER_NETWORK.toString();
String dirType = "FALSE";
int numberOfDemes = 100;
int hostsInDeme = 1;
double pinfectother = 1;
| ModelType modelType = ModelType.SIR; |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/individualBasedModel/JustBeforeRecoveryOrDeathSampler.java | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
| import io.Parameter;
import java.util.ArrayList;
import java.util.List; | // need to check whether the host actually was in infected state first, otherwise no need to sample
// (note could make this exposed or infected, but I think actually just infected here)
samplingEvents = new ArrayList<Event>();
Event e = new Event();
Host h = eventPerformed.toHost;
if ( h.getState().equals(InfectionState.INFECTED) ) {
e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
samplingEvents.add(e);
}
}
}
return samplingEvents;
}
@Override
public List<String[]> getSamplerParameterList() {
List<String[]> params = new ArrayList<String[]>();
String className = this.getClass().getName();
params.add(new String[]{"SamplerType", className});
params.add(new String[]{"justBefore",""+justBefore});
return params;
}
@Override | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
// Path: src/individualBasedModel/JustBeforeRecoveryOrDeathSampler.java
import io.Parameter;
import java.util.ArrayList;
import java.util.List;
// need to check whether the host actually was in infected state first, otherwise no need to sample
// (note could make this exposed or infected, but I think actually just infected here)
samplingEvents = new ArrayList<Event>();
Event e = new Event();
Host h = eventPerformed.toHost;
if ( h.getState().equals(InfectionState.INFECTED) ) {
e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
samplingEvents.add(e);
}
}
}
return samplingEvents;
}
@Override
public List<String[]> getSamplerParameterList() {
List<String[]> params = new ArrayList<String[]>();
String className = this.getClass().getName();
params.add(new String[]{"SamplerType", className});
params.add(new String[]{"justBefore",""+justBefore});
return params;
}
@Override | public void setSamplerParameters(List<Parameter> params) { |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/DSPSConfigurationWriter.java | // Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
| import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner; | simType = chooseASetting(question, choices, explains);
if (simType == null) {
System.out.println("** Done **");
} else {
if (simType.equals("ONE-DEME")) {
writer = new WriteNetworkShapeConfigurationXML();
} else if (simType.equals("TWO-DEME")) {
writer = new WriteNetworkShapeConfigurationXML();
} else if (simType.equals("SHAPED-NETWORK")) {
writer = new WriteNetworkShapeConfigurationXML();
} else if (simType.equals("GENERAL-NETWORK")) {
writer = new WriteNetworkConfigurationXML();
} else if (simType.equals("STRUCTURED-POPULATION")) {
writer = new WriteStructuredPopulationConfigurationXML();
} else {
System.out.println("Sorry cant understand "+simType);
writer = null;
}
}
}
private static void setModelType() {
System.out.println("Typical model type = SIR with infection parameters = 0.1, 0.05");
String question = "Please enter model type";
List<String> choices = new ArrayList<String>();
List<String> explains = new ArrayList<String>();
| // Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
// Path: src/io/DSPSConfigurationWriter.java
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
simType = chooseASetting(question, choices, explains);
if (simType == null) {
System.out.println("** Done **");
} else {
if (simType.equals("ONE-DEME")) {
writer = new WriteNetworkShapeConfigurationXML();
} else if (simType.equals("TWO-DEME")) {
writer = new WriteNetworkShapeConfigurationXML();
} else if (simType.equals("SHAPED-NETWORK")) {
writer = new WriteNetworkShapeConfigurationXML();
} else if (simType.equals("GENERAL-NETWORK")) {
writer = new WriteNetworkConfigurationXML();
} else if (simType.equals("STRUCTURED-POPULATION")) {
writer = new WriteStructuredPopulationConfigurationXML();
} else {
System.out.println("Sorry cant understand "+simType);
writer = null;
}
}
}
private static void setModelType() {
System.out.println("Typical model type = SIR with infection parameters = 0.1, 0.05");
String question = "Please enter model type";
List<String> choices = new ArrayList<String>();
List<String> explains = new ArrayList<String>();
| for (ModelType mt : ModelType.values()) { |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/DSPSConfigurationWriter.java | // Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
| import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner; |
} else if (simType.equals("TWO-DEME")) {
numDemes = 2;
System.out.println("Please enter the number of hosts per deme");
String ans = keyboard.nextLine().trim();
try {
hostsPerDeme = Integer.parseInt(ans);
} catch (NumberFormatException e) {
hostsPerDeme = 500;
System.out.println("Error, but setting number of hosts per deme = "+hostsPerDeme);
}
netWriter.setPopulationType("FULL");
netWriter.reportSummary = "FALSE";
} else if (simType.equals("SHAPED-NETWORK")) {
System.out.println("Please enter the number of demes");
String ans = keyboard.nextLine().trim();
try {
numDemes = Integer.parseInt(ans);
} catch (NumberFormatException e) {
numDemes = 100;
System.out.println("Error, but setting number of demes = "+numDemes);
}
hostsPerDeme = 1;
String question = "Please enter network shape type";
List<String> choices = new ArrayList<String>();
List<String> explains = new ArrayList<String>(); | // Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
// Path: src/io/DSPSConfigurationWriter.java
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
} else if (simType.equals("TWO-DEME")) {
numDemes = 2;
System.out.println("Please enter the number of hosts per deme");
String ans = keyboard.nextLine().trim();
try {
hostsPerDeme = Integer.parseInt(ans);
} catch (NumberFormatException e) {
hostsPerDeme = 500;
System.out.println("Error, but setting number of hosts per deme = "+hostsPerDeme);
}
netWriter.setPopulationType("FULL");
netWriter.reportSummary = "FALSE";
} else if (simType.equals("SHAPED-NETWORK")) {
System.out.println("Please enter the number of demes");
String ans = keyboard.nextLine().trim();
try {
numDemes = Integer.parseInt(ans);
} catch (NumberFormatException e) {
numDemes = 100;
System.out.println("Error, but setting number of demes = "+numDemes);
}
hostsPerDeme = 1;
String question = "Please enter network shape type";
List<String> choices = new ArrayList<String>();
List<String> explains = new ArrayList<String>(); | for (PopulationType pt : PopulationType.values()) { |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/networks/Network.java | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
| import io.Parameter;
import java.util.List; | package networks;
/**
*
* @author Samantha Lycett
* @created 2 Oct 2013
* @version 23 July 2014
*/
public interface Network {
public NetworkModelType getNetworkModelType();
//public void setNumberOfNodes(int n); | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
// Path: src/networks/Network.java
import io.Parameter;
import java.util.List;
package networks;
/**
*
* @author Samantha Lycett
* @created 2 Oct 2013
* @version 23 July 2014
*/
public interface Network {
public NetworkModelType getNetworkModelType();
//public void setNumberOfNodes(int n); | public void setParameter(Parameter p); |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/trees/TransmissionNode.java | // Path: src/individualBasedModel/Host.java
// public class Host {
//
// ///////////////////////////////////
// // class variables and methods
// private static long hostCounter = -1;
//
// private static long nextHostUID() {
// hostCounter++;
// return (hostCounter);
// }
//
// /**
// * reset the host counter between multiple replicate runs of DiscreteSpatialPhyloSimulator
// */
// static void resetHostCounter() {
// hostCounter = -1;
// }
//
// ///////////////////////////////////
// // instance variables & methods
//
// // instance variables
// protected String name = null;
// protected long uid;
// protected InfectionState state = InfectionState.SUSCEPTIBLE;
//
// protected Deme myDeme;
//
// // constructors
// public Host(Deme myDeme) {
// this.uid = nextHostUID();
// this.name = "H"+String.format("%07d", uid); //""+uid;
// this.myDeme = myDeme;
// }
//
// public Host(Deme myDeme, String name) {
// this.uid = nextHostUID();
// this.name = name;
// this.myDeme = myDeme;
// }
//
// //////////////////////////////////
// // setters
//
// public void setState(InfectionState state) {
// this.state = state;
// }
//
// ///////////////////////////////////
// // getters
//
// public InfectionState getState() {
// return state;
// }
//
// public String getName() {
// if (this.name == null) {
// this.name = ""+uid;
// }
// return this.name;
// }
//
// public String getNameWithDeme() {
// //return (getName() + "_" + myDeme.getName());
// return (name + "_" + myDeme);
// }
//
// public long getUid() {
// return uid;
// }
//
// /////////////////////////////////////////////////////////////////////////
// // comparison methods and toString
//
// @Override
// public String toString() {
// return "Host [name=" + name + ", uid=" + uid + ", state=" + state
// + ", myDeme=" + myDeme + "]";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (int) (uid ^ (uid >>> 32));
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Host other = (Host) obj;
// if (uid != other.uid)
// return false;
// return true;
// }
//
//
//
// }
| import java.util.*;
import individualBasedModel.Host; | package trees;
/**
*
* @author Samantha Lycett
* @created 26 Nov 2012
* @version 28 Nov 2012
* @version 17 June 2013
* @version 2 July 2013
*/
public class TransmissionNode implements Node, Cloneable {
///////////////////////////////////
// class variables and methods
private static long nodeCounter = -1;
private static long nextNodeUID() {
nodeCounter++;
return (nodeCounter);
}
/**
* only use this to reset the node counter between runs
*/
public static void resetNodeCounter() {
nodeCounter = -1;
}
///////////////////////////////////
protected long uid;
protected String name; // access through getName because is set from host
| // Path: src/individualBasedModel/Host.java
// public class Host {
//
// ///////////////////////////////////
// // class variables and methods
// private static long hostCounter = -1;
//
// private static long nextHostUID() {
// hostCounter++;
// return (hostCounter);
// }
//
// /**
// * reset the host counter between multiple replicate runs of DiscreteSpatialPhyloSimulator
// */
// static void resetHostCounter() {
// hostCounter = -1;
// }
//
// ///////////////////////////////////
// // instance variables & methods
//
// // instance variables
// protected String name = null;
// protected long uid;
// protected InfectionState state = InfectionState.SUSCEPTIBLE;
//
// protected Deme myDeme;
//
// // constructors
// public Host(Deme myDeme) {
// this.uid = nextHostUID();
// this.name = "H"+String.format("%07d", uid); //""+uid;
// this.myDeme = myDeme;
// }
//
// public Host(Deme myDeme, String name) {
// this.uid = nextHostUID();
// this.name = name;
// this.myDeme = myDeme;
// }
//
// //////////////////////////////////
// // setters
//
// public void setState(InfectionState state) {
// this.state = state;
// }
//
// ///////////////////////////////////
// // getters
//
// public InfectionState getState() {
// return state;
// }
//
// public String getName() {
// if (this.name == null) {
// this.name = ""+uid;
// }
// return this.name;
// }
//
// public String getNameWithDeme() {
// //return (getName() + "_" + myDeme.getName());
// return (name + "_" + myDeme);
// }
//
// public long getUid() {
// return uid;
// }
//
// /////////////////////////////////////////////////////////////////////////
// // comparison methods and toString
//
// @Override
// public String toString() {
// return "Host [name=" + name + ", uid=" + uid + ", state=" + state
// + ", myDeme=" + myDeme + "]";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (int) (uid ^ (uid >>> 32));
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Host other = (Host) obj;
// if (uid != other.uid)
// return false;
// return true;
// }
//
//
//
// }
// Path: src/trees/TransmissionNode.java
import java.util.*;
import individualBasedModel.Host;
package trees;
/**
*
* @author Samantha Lycett
* @created 26 Nov 2012
* @version 28 Nov 2012
* @version 17 June 2013
* @version 2 July 2013
*/
public class TransmissionNode implements Node, Cloneable {
///////////////////////////////////
// class variables and methods
private static long nodeCounter = -1;
private static long nextNodeUID() {
nodeCounter++;
return (nodeCounter);
}
/**
* only use this to reset the node counter between runs
*/
public static void resetNodeCounter() {
nodeCounter = -1;
}
///////////////////////////////////
protected long uid;
protected String name; // access through getName because is set from host
| Host host; |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteStructuredPopulationConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to read in Deme properties and connections and make XML
* defaults set for H7N9 work (12 Nov 2013)
* defaults set for Line & Star comparison work (2 May 2014)
* @author Samantha Lycett
* @version 12 Nov 2013
* @version 2 May 2014
* @version 29 Dec 2014
*/
public class WriteStructuredPopulationConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
int echoEvery = 10000;
long seed = -1;
int nreps = 1;
double tauleap = 0;
String demeSizesName = "demeSizes.csv";
String edgeListName = "edgeList.csv";
ReadSimpleNamedParameters demeSizes;
ReadEdgeList edgeList;
//String dn = "N";
| // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteStructuredPopulationConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to read in Deme properties and connections and make XML
* defaults set for H7N9 work (12 Nov 2013)
* defaults set for Line & Star comparison work (2 May 2014)
* @author Samantha Lycett
* @version 12 Nov 2013
* @version 2 May 2014
* @version 29 Dec 2014
*/
public class WriteStructuredPopulationConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
int echoEvery = 10000;
long seed = -1;
int nreps = 1;
double tauleap = 0;
String demeSizesName = "demeSizes.csv";
String edgeListName = "edgeList.csv";
ReadSimpleNamedParameters demeSizes;
ReadEdgeList edgeList;
//String dn = "N";
| Sampler theSampler = new JustBeforeRecoverySampler(); |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteStructuredPopulationConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to read in Deme properties and connections and make XML
* defaults set for H7N9 work (12 Nov 2013)
* defaults set for Line & Star comparison work (2 May 2014)
* @author Samantha Lycett
* @version 12 Nov 2013
* @version 2 May 2014
* @version 29 Dec 2014
*/
public class WriteStructuredPopulationConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
int echoEvery = 10000;
long seed = -1;
int nreps = 1;
double tauleap = 0;
String demeSizesName = "demeSizes.csv";
String edgeListName = "edgeList.csv";
ReadSimpleNamedParameters demeSizes;
ReadEdgeList edgeList;
//String dn = "N";
| // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteStructuredPopulationConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to read in Deme properties and connections and make XML
* defaults set for H7N9 work (12 Nov 2013)
* defaults set for Line & Star comparison work (2 May 2014)
* @author Samantha Lycett
* @version 12 Nov 2013
* @version 2 May 2014
* @version 29 Dec 2014
*/
public class WriteStructuredPopulationConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
int echoEvery = 10000;
long seed = -1;
int nreps = 1;
double tauleap = 0;
String demeSizesName = "demeSizes.csv";
String edgeListName = "edgeList.csv";
ReadSimpleNamedParameters demeSizes;
ReadEdgeList edgeList;
//String dn = "N";
| Sampler theSampler = new JustBeforeRecoverySampler(); |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/io/WriteStructuredPopulationConfigurationXML.java | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
| import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List; | package io;
/**
* class to read in Deme properties and connections and make XML
* defaults set for H7N9 work (12 Nov 2013)
* defaults set for Line & Star comparison work (2 May 2014)
* @author Samantha Lycett
* @version 12 Nov 2013
* @version 2 May 2014
* @version 29 Dec 2014
*/
public class WriteStructuredPopulationConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
int echoEvery = 10000;
long seed = -1;
int nreps = 1;
double tauleap = 0;
String demeSizesName = "demeSizes.csv";
String edgeListName = "edgeList.csv";
ReadSimpleNamedParameters demeSizes;
ReadEdgeList edgeList;
//String dn = "N";
Sampler theSampler = new JustBeforeRecoverySampler(); | // Path: src/individualBasedModel/DemeType.java
// public enum DemeType {
// MIGRATION_OF_INFECTEDS, INFECTION_OVER_NETWORK
// }
//
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
// public class JustBeforeRecoverySampler implements Sampler {
//
// protected double justBefore = 1e-16;
//
// public JustBeforeRecoverySampler() {
//
// }
//
// public void setJustBefore(double d) {
// this.justBefore = d;
// }
//
// /**
// * never does population sampling
// */
// @Override
// public List<Event> generateSamplingEvents(Population thePopulation,
// double actionTime) {
// // TODO Auto-generated method stub
// return null;
// }
//
// @Override
// public List<Event> generateSamplingEvents(Event eventPerformed) {
//
// List<Event> samplingEvents = null;
//
// if ((eventPerformed.success) && (eventPerformed.type == EventType.RECOVERY)) {
// //System.out.println("Attempt to set sampling from "+eventPerformed.toOutput());
//
// samplingEvents = new ArrayList<Event>();
// Event e = new Event();
//
// e.setSamplingEvent(eventPerformed.toHost, eventPerformed.creationTime, eventPerformed.actionTime - justBefore);
// samplingEvents.add(e);
//
// //System.out.println("Sampling: "+e.toOutput());
// }
//
// return samplingEvents;
// }
//
// @Override
// public List<String[]> getSamplerParameterList() {
// List<String[]> params = new ArrayList<String[]>();
//
// String className = this.getClass().getName();
// params.add(new String[]{"SamplerType", className});
// params.add(new String[]{"justBefore",""+justBefore});
//
// return params;
// }
//
// /*
// @Override
//
// public void setSamplerParameters(List<String[]> params) {
//
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("SamplerType")) {
// found = (pairs[1].equals(className));
// }
//
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// String[] pairs = params.get(i);
//
// if (pairs[0].equals("justBefore")) {
// justBefore = Double.parseDouble(pairs[1]);
// }
// i++;
// }
// }
// }
// */
//
// @Override
// public void setSamplerParameters(List<Parameter> params) {
// int i = 0;
// boolean found = false;
// String className = this.getClass().getName();
//
// while ( (i < params.size()) && (!found) ) {
// Parameter p = params.get(i);
// if ( (p.getParentTag().equals("Sampler")) && (p.getId().equals("SamplerType")) ) {
// found = (p.getValue().equals(className));
// }
// i++;
// }
//
// if (found) {
// while (i < params.size()) {
// Parameter p = params.get(i);
//
// if (p.getId().equals("justBefore")) {
// justBefore = Double.parseDouble(p.getValue());
// }
//
// i++;
// }
// }
// }
//
// }
//
// Path: src/individualBasedModel/ModelType.java
// public enum ModelType {
// SI, SIR, SEIR
// }
//
// Path: src/individualBasedModel/PopulationType.java
// public enum PopulationType {
// FULL, RANDOM, LINE, STAR, NETWORK
// }
//
// Path: src/individualBasedModel/Sampler.java
// public interface Sampler {
//
// /**
// * generate sampling events from the population
// * @param thePopulation
// * @param actionTime
// * @return
// */
// List<Event> generateSamplingEvents(Population thePopulation, double actionTime);
//
// /**
// * generated sampling events based on this event (e.g. infection, recovery)
// * @param e
// * @return
// */
// List<Event> generateSamplingEvents(Event e);
//
// /**
// * return parameter,value pairs for use with Logger etc
// * @return
// */
// List<String[]> getSamplerParameterList();
//
// /**
// * set parameters from parameter,value pairs
// * @param params
// */
// //void setSamplerParameters( List<String[]> params);
// void setSamplerParameters( List<Parameter> params);
// }
// Path: src/io/WriteStructuredPopulationConfigurationXML.java
import individualBasedModel.DemeType;
import individualBasedModel.JustBeforeRecoverySampler;
import individualBasedModel.ModelType;
import individualBasedModel.PopulationType;
import individualBasedModel.Sampler;
import java.util.ArrayList;
import java.util.List;
package io;
/**
* class to read in Deme properties and connections and make XML
* defaults set for H7N9 work (12 Nov 2013)
* defaults set for Line & Star comparison work (2 May 2014)
* @author Samantha Lycett
* @version 12 Nov 2013
* @version 2 May 2014
* @version 29 Dec 2014
*/
public class WriteStructuredPopulationConfigurationXML implements ConfigurationXMLInterface {
String path = "test//";
String rootname = "example_network";
String simpath = "test//";
String simname = "example_network";
int echoEvery = 10000;
long seed = -1;
int nreps = 1;
double tauleap = 0;
String demeSizesName = "demeSizes.csv";
String edgeListName = "edgeList.csv";
ReadSimpleNamedParameters demeSizes;
ReadEdgeList edgeList;
//String dn = "N";
Sampler theSampler = new JustBeforeRecoverySampler(); | PopulationType popType = PopulationType.NETWORK; |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/individualBasedModel/Population.java | // Path: src/math/Distributions.java
// public class Distributions {
//
// public static long initialise() {
// return MersenneTwisterFast.getSeed();
// }
//
// public static void initialiseWithSeed(int seed) {
// MersenneTwisterFast.initialiseWithSeed(seed);
// }
//
// /*
// public static double randomExponential(double mean) {
// double u = MersenneTwisterFast.getDouble();
// double x = (Math.log(1-u))*mean;
// return x;
// }
// */
//
// public static double randomGaussian() {
// return MersenneTwisterFast.getGaussian();
// }
//
// public static double randomUniform() {
// return MersenneTwisterFast.getDouble();
// }
//
// public static int randomInt() {
// return MersenneTwisterFast.getInt();
// }
//
// public static int randomInt(int upper) {
// return MersenneTwisterFast.getInt(upper);
// }
//
// /**
// * chooses index according to weights; if the final weight is not 1 then index longer than array can be returned
// * @param cumProb
// * @return
// */
// public static int weightedChoice(double[] cumProb) {
// double x = MersenneTwisterFast.getDouble();
// int choice = 0;
// if (x > cumProb[cumProb.length-1]) {
// choice = cumProb.length;
// } else {
// while ( (choice < cumProb.length) && (x > cumProb[choice]) ) {
// choice++;
// }
// }
//
// return choice;
// }
//
// /**
// * chooses index according to weights; use for when the weights are not normalised to 1 (i.e. when last weight != 1)
// * @param cumProb
// * @return
// */
// /*
// public static int unNormalisedWeightedChoice(double[] cumW) {
// double x = MersenneTwisterFast.getDouble()*cumW[cumW.length-1] ;
// int choice = 0;
// if (x > cumW[cumW.length-1]) {
// choice = cumW.length;
// } else {
// while ( (choice < cumW.length) && (x > cumW[choice]) ) {
// choice++;
// }
// }
//
// return choice;
// }
// */
//
// /**
// * chooses index according to weights, weights are not cumulative or normalised
// * @param weights
// * @param totalWeights
// * @return
// */
// public static int chooseWithWeights(double[] weights, double totalWeights) {
// double x = MersenneTwisterFast.getDouble() * totalWeights;
// double ctr = 0;
// int choice = -1;
// //int i = 0;
//
// //while ( (i < weights.length) && (choice==-1) ) {
// for (int i = 0; i < weights.length; i++) {
// double ctr2 = ctr + weights[i];
// if ( (ctr < x) && (x < ctr2) ) {
// choice = i;
// }
// ctr = ctr2;
// //i++;
// }
//
// return choice;
// }
// }
| import java.util.*;
import math.Distributions;
import io.*; | }
/////////////////////////////////////////////////////////////////////
// access methods for demes
public void setDemes(List<Deme> demes) {
this.demes = demes;
}
public void addDeme(Deme deme) {
if (this.demes == null) {
this.demes = new ArrayList<Deme>();
}
if (!this.demes.contains(deme)) {
this.demes.add(deme);
} else {
System.out.println("Population.addDeme - sorry cant add Deme "+deme.getName()+" because already in list");
}
}
/**
* adds one infected host into the first deme
*/
public void setIndexCaseFirstDeme() {
Deme d = demes.get(0);
d.setIndexCase();
}
public void setIndexCaseAnyDeme() {
if (demes.size() > 1) { | // Path: src/math/Distributions.java
// public class Distributions {
//
// public static long initialise() {
// return MersenneTwisterFast.getSeed();
// }
//
// public static void initialiseWithSeed(int seed) {
// MersenneTwisterFast.initialiseWithSeed(seed);
// }
//
// /*
// public static double randomExponential(double mean) {
// double u = MersenneTwisterFast.getDouble();
// double x = (Math.log(1-u))*mean;
// return x;
// }
// */
//
// public static double randomGaussian() {
// return MersenneTwisterFast.getGaussian();
// }
//
// public static double randomUniform() {
// return MersenneTwisterFast.getDouble();
// }
//
// public static int randomInt() {
// return MersenneTwisterFast.getInt();
// }
//
// public static int randomInt(int upper) {
// return MersenneTwisterFast.getInt(upper);
// }
//
// /**
// * chooses index according to weights; if the final weight is not 1 then index longer than array can be returned
// * @param cumProb
// * @return
// */
// public static int weightedChoice(double[] cumProb) {
// double x = MersenneTwisterFast.getDouble();
// int choice = 0;
// if (x > cumProb[cumProb.length-1]) {
// choice = cumProb.length;
// } else {
// while ( (choice < cumProb.length) && (x > cumProb[choice]) ) {
// choice++;
// }
// }
//
// return choice;
// }
//
// /**
// * chooses index according to weights; use for when the weights are not normalised to 1 (i.e. when last weight != 1)
// * @param cumProb
// * @return
// */
// /*
// public static int unNormalisedWeightedChoice(double[] cumW) {
// double x = MersenneTwisterFast.getDouble()*cumW[cumW.length-1] ;
// int choice = 0;
// if (x > cumW[cumW.length-1]) {
// choice = cumW.length;
// } else {
// while ( (choice < cumW.length) && (x > cumW[choice]) ) {
// choice++;
// }
// }
//
// return choice;
// }
// */
//
// /**
// * chooses index according to weights, weights are not cumulative or normalised
// * @param weights
// * @param totalWeights
// * @return
// */
// public static int chooseWithWeights(double[] weights, double totalWeights) {
// double x = MersenneTwisterFast.getDouble() * totalWeights;
// double ctr = 0;
// int choice = -1;
// //int i = 0;
//
// //while ( (i < weights.length) && (choice==-1) ) {
// for (int i = 0; i < weights.length; i++) {
// double ctr2 = ctr + weights[i];
// if ( (ctr < x) && (x < ctr2) ) {
// choice = i;
// }
// ctr = ctr2;
// //i++;
// }
//
// return choice;
// }
// }
// Path: src/individualBasedModel/Population.java
import java.util.*;
import math.Distributions;
import io.*;
}
/////////////////////////////////////////////////////////////////////
// access methods for demes
public void setDemes(List<Deme> demes) {
this.demes = demes;
}
public void addDeme(Deme deme) {
if (this.demes == null) {
this.demes = new ArrayList<Deme>();
}
if (!this.demes.contains(deme)) {
this.demes.add(deme);
} else {
System.out.println("Population.addDeme - sorry cant add Deme "+deme.getName()+" because already in list");
}
}
/**
* adds one infected host into the first deme
*/
public void setIndexCaseFirstDeme() {
Deme d = demes.get(0);
d.setIndexCase();
}
public void setIndexCaseAnyDeme() {
if (demes.size() > 1) { | int choice = Distributions.randomInt(demes.size()); |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/individualBasedModel/SamplerFactory.java | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
| import io.Parameter;
import java.util.List; | package individualBasedModel;
/**
* factory class for creating a sampling scheme from parameter list
* @author Samantha Lycett
* @created 4 July 2013
* @version 4 July 2013
* @version 30 March 2016 - include JustBeforeRecoveryOrDeath sampler
*/
public class SamplerFactory {
private static boolean echo = true;
| // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
// Path: src/individualBasedModel/SamplerFactory.java
import io.Parameter;
import java.util.List;
package individualBasedModel;
/**
* factory class for creating a sampling scheme from parameter list
* @author Samantha Lycett
* @created 4 July 2013
* @version 4 July 2013
* @version 30 March 2016 - include JustBeforeRecoveryOrDeath sampler
*/
public class SamplerFactory {
private static boolean echo = true;
| public static Sampler getSampler(List<Parameter> params) { |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/individualBasedModel/JustBeforeRecoverySampler.java | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
| import io.Parameter;
import java.util.List;
import java.util.ArrayList; | public void setSamplerParameters(List<String[]> params) {
int i = 0;
boolean found = false;
String className = this.getClass().getName();
while ( (i < params.size()) && (!found) ) {
String[] pairs = params.get(i);
if (pairs[0].equals("SamplerType")) {
found = (pairs[1].equals(className));
}
i++;
}
if (found) {
while (i < params.size()) {
String[] pairs = params.get(i);
if (pairs[0].equals("justBefore")) {
justBefore = Double.parseDouble(pairs[1]);
}
i++;
}
}
}
*/
@Override | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
// Path: src/individualBasedModel/JustBeforeRecoverySampler.java
import io.Parameter;
import java.util.List;
import java.util.ArrayList;
public void setSamplerParameters(List<String[]> params) {
int i = 0;
boolean found = false;
String className = this.getClass().getName();
while ( (i < params.size()) && (!found) ) {
String[] pairs = params.get(i);
if (pairs[0].equals("SamplerType")) {
found = (pairs[1].equals(className));
}
i++;
}
if (found) {
while (i < params.size()) {
String[] pairs = params.get(i);
if (pairs[0].equals("justBefore")) {
justBefore = Double.parseDouble(pairs[1]);
}
i++;
}
}
}
*/
@Override | public void setSamplerParameters(List<Parameter> params) { |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/trees/SampledNode.java | // Path: src/individualBasedModel/Host.java
// public class Host {
//
// ///////////////////////////////////
// // class variables and methods
// private static long hostCounter = -1;
//
// private static long nextHostUID() {
// hostCounter++;
// return (hostCounter);
// }
//
// /**
// * reset the host counter between multiple replicate runs of DiscreteSpatialPhyloSimulator
// */
// static void resetHostCounter() {
// hostCounter = -1;
// }
//
// ///////////////////////////////////
// // instance variables & methods
//
// // instance variables
// protected String name = null;
// protected long uid;
// protected InfectionState state = InfectionState.SUSCEPTIBLE;
//
// protected Deme myDeme;
//
// // constructors
// public Host(Deme myDeme) {
// this.uid = nextHostUID();
// this.name = "H"+String.format("%07d", uid); //""+uid;
// this.myDeme = myDeme;
// }
//
// public Host(Deme myDeme, String name) {
// this.uid = nextHostUID();
// this.name = name;
// this.myDeme = myDeme;
// }
//
// //////////////////////////////////
// // setters
//
// public void setState(InfectionState state) {
// this.state = state;
// }
//
// ///////////////////////////////////
// // getters
//
// public InfectionState getState() {
// return state;
// }
//
// public String getName() {
// if (this.name == null) {
// this.name = ""+uid;
// }
// return this.name;
// }
//
// public String getNameWithDeme() {
// //return (getName() + "_" + myDeme.getName());
// return (name + "_" + myDeme);
// }
//
// public long getUid() {
// return uid;
// }
//
// /////////////////////////////////////////////////////////////////////////
// // comparison methods and toString
//
// @Override
// public String toString() {
// return "Host [name=" + name + ", uid=" + uid + ", state=" + state
// + ", myDeme=" + myDeme + "]";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (int) (uid ^ (uid >>> 32));
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Host other = (Host) obj;
// if (uid != other.uid)
// return false;
// return true;
// }
//
//
//
// }
| import individualBasedModel.Host;
import java.util.List; | package trees;
/**
*
* @author Samantha Lycett
* @version 24 Oct 2013 - added include time in sampled name (defaults to true)
*
*/
public class SampledNode extends TransmissionNode {
static boolean includeTimeInSampledName = true;
static String delim = "|"; // good for BEAST 1
| // Path: src/individualBasedModel/Host.java
// public class Host {
//
// ///////////////////////////////////
// // class variables and methods
// private static long hostCounter = -1;
//
// private static long nextHostUID() {
// hostCounter++;
// return (hostCounter);
// }
//
// /**
// * reset the host counter between multiple replicate runs of DiscreteSpatialPhyloSimulator
// */
// static void resetHostCounter() {
// hostCounter = -1;
// }
//
// ///////////////////////////////////
// // instance variables & methods
//
// // instance variables
// protected String name = null;
// protected long uid;
// protected InfectionState state = InfectionState.SUSCEPTIBLE;
//
// protected Deme myDeme;
//
// // constructors
// public Host(Deme myDeme) {
// this.uid = nextHostUID();
// this.name = "H"+String.format("%07d", uid); //""+uid;
// this.myDeme = myDeme;
// }
//
// public Host(Deme myDeme, String name) {
// this.uid = nextHostUID();
// this.name = name;
// this.myDeme = myDeme;
// }
//
// //////////////////////////////////
// // setters
//
// public void setState(InfectionState state) {
// this.state = state;
// }
//
// ///////////////////////////////////
// // getters
//
// public InfectionState getState() {
// return state;
// }
//
// public String getName() {
// if (this.name == null) {
// this.name = ""+uid;
// }
// return this.name;
// }
//
// public String getNameWithDeme() {
// //return (getName() + "_" + myDeme.getName());
// return (name + "_" + myDeme);
// }
//
// public long getUid() {
// return uid;
// }
//
// /////////////////////////////////////////////////////////////////////////
// // comparison methods and toString
//
// @Override
// public String toString() {
// return "Host [name=" + name + ", uid=" + uid + ", state=" + state
// + ", myDeme=" + myDeme + "]";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (int) (uid ^ (uid >>> 32));
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Host other = (Host) obj;
// if (uid != other.uid)
// return false;
// return true;
// }
//
//
//
// }
// Path: src/trees/SampledNode.java
import individualBasedModel.Host;
import java.util.List;
package trees;
/**
*
* @author Samantha Lycett
* @version 24 Oct 2013 - added include time in sampled name (defaults to true)
*
*/
public class SampledNode extends TransmissionNode {
static boolean includeTimeInSampledName = true;
static String delim = "|"; // good for BEAST 1
| public SampledNode(Host h) { |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/individualBasedModel/EventGenerator.java | // Path: src/math/Distributions.java
// public class Distributions {
//
// public static long initialise() {
// return MersenneTwisterFast.getSeed();
// }
//
// public static void initialiseWithSeed(int seed) {
// MersenneTwisterFast.initialiseWithSeed(seed);
// }
//
// /*
// public static double randomExponential(double mean) {
// double u = MersenneTwisterFast.getDouble();
// double x = (Math.log(1-u))*mean;
// return x;
// }
// */
//
// public static double randomGaussian() {
// return MersenneTwisterFast.getGaussian();
// }
//
// public static double randomUniform() {
// return MersenneTwisterFast.getDouble();
// }
//
// public static int randomInt() {
// return MersenneTwisterFast.getInt();
// }
//
// public static int randomInt(int upper) {
// return MersenneTwisterFast.getInt(upper);
// }
//
// /**
// * chooses index according to weights; if the final weight is not 1 then index longer than array can be returned
// * @param cumProb
// * @return
// */
// public static int weightedChoice(double[] cumProb) {
// double x = MersenneTwisterFast.getDouble();
// int choice = 0;
// if (x > cumProb[cumProb.length-1]) {
// choice = cumProb.length;
// } else {
// while ( (choice < cumProb.length) && (x > cumProb[choice]) ) {
// choice++;
// }
// }
//
// return choice;
// }
//
// /**
// * chooses index according to weights; use for when the weights are not normalised to 1 (i.e. when last weight != 1)
// * @param cumProb
// * @return
// */
// /*
// public static int unNormalisedWeightedChoice(double[] cumW) {
// double x = MersenneTwisterFast.getDouble()*cumW[cumW.length-1] ;
// int choice = 0;
// if (x > cumW[cumW.length-1]) {
// choice = cumW.length;
// } else {
// while ( (choice < cumW.length) && (x > cumW[choice]) ) {
// choice++;
// }
// }
//
// return choice;
// }
// */
//
// /**
// * chooses index according to weights, weights are not cumulative or normalised
// * @param weights
// * @param totalWeights
// * @return
// */
// public static int chooseWithWeights(double[] weights, double totalWeights) {
// double x = MersenneTwisterFast.getDouble() * totalWeights;
// double ctr = 0;
// int choice = -1;
// //int i = 0;
//
// //while ( (i < weights.length) && (choice==-1) ) {
// for (int i = 0; i < weights.length; i++) {
// double ctr2 = ctr + weights[i];
// if ( (ctr < x) && (x < ctr2) ) {
// choice = i;
// }
// ctr = ctr2;
// //i++;
// }
//
// return choice;
// }
// }
| import java.util.*;
import math.Distributions; | package individualBasedModel;
/**
* class to generate events from list of hazards
* @author Samantha Lycett
* @created 24 Sept 2013
*
*/
public class EventGenerator {
public EventGenerator() {
}
public Event generateEvent(List<Hazard> hazards, double currentTime) {
if (hazards.size() > 1) {
// find time to any event
double rateAny = 0;
double[] demeRates = new double[hazards.size()];
for (int i = 0; i < hazards.size(); i++) {
Hazard h = hazards.get(i);
double demeHazard = h.getTotalHazard();
rateAny += demeHazard;
demeRates[i] = demeHazard;
}
if (rateAny > 0) {
| // Path: src/math/Distributions.java
// public class Distributions {
//
// public static long initialise() {
// return MersenneTwisterFast.getSeed();
// }
//
// public static void initialiseWithSeed(int seed) {
// MersenneTwisterFast.initialiseWithSeed(seed);
// }
//
// /*
// public static double randomExponential(double mean) {
// double u = MersenneTwisterFast.getDouble();
// double x = (Math.log(1-u))*mean;
// return x;
// }
// */
//
// public static double randomGaussian() {
// return MersenneTwisterFast.getGaussian();
// }
//
// public static double randomUniform() {
// return MersenneTwisterFast.getDouble();
// }
//
// public static int randomInt() {
// return MersenneTwisterFast.getInt();
// }
//
// public static int randomInt(int upper) {
// return MersenneTwisterFast.getInt(upper);
// }
//
// /**
// * chooses index according to weights; if the final weight is not 1 then index longer than array can be returned
// * @param cumProb
// * @return
// */
// public static int weightedChoice(double[] cumProb) {
// double x = MersenneTwisterFast.getDouble();
// int choice = 0;
// if (x > cumProb[cumProb.length-1]) {
// choice = cumProb.length;
// } else {
// while ( (choice < cumProb.length) && (x > cumProb[choice]) ) {
// choice++;
// }
// }
//
// return choice;
// }
//
// /**
// * chooses index according to weights; use for when the weights are not normalised to 1 (i.e. when last weight != 1)
// * @param cumProb
// * @return
// */
// /*
// public static int unNormalisedWeightedChoice(double[] cumW) {
// double x = MersenneTwisterFast.getDouble()*cumW[cumW.length-1] ;
// int choice = 0;
// if (x > cumW[cumW.length-1]) {
// choice = cumW.length;
// } else {
// while ( (choice < cumW.length) && (x > cumW[choice]) ) {
// choice++;
// }
// }
//
// return choice;
// }
// */
//
// /**
// * chooses index according to weights, weights are not cumulative or normalised
// * @param weights
// * @param totalWeights
// * @return
// */
// public static int chooseWithWeights(double[] weights, double totalWeights) {
// double x = MersenneTwisterFast.getDouble() * totalWeights;
// double ctr = 0;
// int choice = -1;
// //int i = 0;
//
// //while ( (i < weights.length) && (choice==-1) ) {
// for (int i = 0; i < weights.length; i++) {
// double ctr2 = ctr + weights[i];
// if ( (ctr < x) && (x < ctr2) ) {
// choice = i;
// }
// ctr = ctr2;
// //i++;
// }
//
// return choice;
// }
// }
// Path: src/individualBasedModel/EventGenerator.java
import java.util.*;
import math.Distributions;
package individualBasedModel;
/**
* class to generate events from list of hazards
* @author Samantha Lycett
* @created 24 Sept 2013
*
*/
public class EventGenerator {
public EventGenerator() {
}
public Event generateEvent(List<Hazard> hazards, double currentTime) {
if (hazards.size() > 1) {
// find time to any event
double rateAny = 0;
double[] demeRates = new double[hazards.size()];
for (int i = 0; i < hazards.size(); i++) {
Hazard h = hazards.get(i);
double demeHazard = h.getTotalHazard();
rateAny += demeHazard;
demeRates[i] = demeHazard;
}
if (rateAny > 0) {
| double dt = -Math.log( Distributions.randomUniform() )/rateAny; |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/networks/NetworkTest.java | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
| import io.Parameter;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; | NetworkInformation ni = new NetworkInformation(network);
System.out.println(ni);
}
@Test
public void testSpatialNetwork() {
SpatialModelNetwork network = new SpatialModelNetwork();
System.out.println("Network information (empty)");
NetworkInformation ni = new NetworkInformation(network);
System.out.println(ni);
String fname = "test//example_UK_cities.csv";
String delim = ",";
network.readNodeLocationsFromFile(fname, delim);
network.create();
System.out.println("Network information (created)");
ni = new NetworkInformation(network);
System.out.println(ni);
System.out.println("First Node:");
LocationNetworkNode locN = (LocationNetworkNode)network.getNodes().get(0);
System.out.println(locN.neighboursLine());
System.out.println(locN.distancesLine());
System.out.println(locN.weightsLine());
System.out.println();
System.out.println("Now restrict to 100km"); | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
// Path: src/networks/NetworkTest.java
import io.Parameter;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
NetworkInformation ni = new NetworkInformation(network);
System.out.println(ni);
}
@Test
public void testSpatialNetwork() {
SpatialModelNetwork network = new SpatialModelNetwork();
System.out.println("Network information (empty)");
NetworkInformation ni = new NetworkInformation(network);
System.out.println(ni);
String fname = "test//example_UK_cities.csv";
String delim = ",";
network.readNodeLocationsFromFile(fname, delim);
network.create();
System.out.println("Network information (created)");
ni = new NetworkInformation(network);
System.out.println(ni);
System.out.println("First Node:");
LocationNetworkNode locN = (LocationNetworkNode)network.getNodes().get(0);
System.out.println(locN.neighboursLine());
System.out.println(locN.distancesLine());
System.out.println(locN.weightsLine());
System.out.println();
System.out.println("Now restrict to 100km"); | network.setParameter(new Parameter("distanceThreshold","100")); |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/networks/BasicNetwork.java | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
| import io.Parameter;
import java.util.*; | }
public BasicNetwork(int numberOfNodes) {
setBasicNodes(numberOfNodes);
}
public void setBasicNodes(int numberOfNodes) {
this.numberOfNodes = numberOfNodes;
nodes = new ArrayList<NetworkNode>();
for (int i = 0; i < numberOfNodes; i++) {
nodes.add( new BasicNode() );
}
}
@Override
public void setNodes(List<NetworkNode> nn) {
this.nodes = nn;
}
@Override
public int getNumberOfNodes() {
return numberOfNodes;
}
@Override
public boolean isDirected() {
return directed;
}
@Override | // Path: src/io/Parameter.java
// public class Parameter {
//
// String id;
// String value;
// String parentTag;
// int parentNumber;
//
// public Parameter(String parentTag, int parentNumber, Element el) {
// this.id = el.getAttribute("id");
// this.value = el.getAttribute("value");
// this.parentTag = parentTag;
// this.parentNumber = parentNumber;
// }
//
// /**
// * use this constructor to make a dummy object which is used in searches ( e.g. ArrayList . contains etc)
// * @param id
// */
// public Parameter(String id) {
// this.id = id;
// }
//
// /**
// * use this constructor to make simple parameters (e.g. when not configuring from XML).
// * @param id
// * @param value
// */
// public Parameter(String id, String value) {
// this.parentTag = "";
// this.parentNumber = 0;
// this.id = id;
// this.value = value;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// /**
// * @return the id
// */
// public String getId() {
// return id;
// }
//
// /**
// * @return the value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * @return the parentTag
// */
// public String getParentTag() {
// return parentTag;
// }
//
// /**
// * @return the parentNumber
// */
// public int getParentNumber() {
// return parentNumber;
// }
//
//
// //////////////////////////////////////////////////////////////////////////////////
//
//
// public String[] getNameValuePair() {
// String[] pair = new String[2];
// pair[0] = id;
// pair[1] = value;
// return pair;
// }
//
// //////////////////////////////////////////////////////////////////////////////////
//
// public String toString() {
// return (parentTag + "-" + parentNumber + "\t" + id + "\t" + value);
// }
//
//
//
// //////////////////////////////////////////////////////////////////////////////////
// // hash code and equals based on id only
//
// /* (non-Javadoc)
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Parameter))
// return false;
// Parameter other = (Parameter) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// return true;
// }
//
//
//
//
//
// }
// Path: src/networks/BasicNetwork.java
import io.Parameter;
import java.util.*;
}
public BasicNetwork(int numberOfNodes) {
setBasicNodes(numberOfNodes);
}
public void setBasicNodes(int numberOfNodes) {
this.numberOfNodes = numberOfNodes;
nodes = new ArrayList<NetworkNode>();
for (int i = 0; i < numberOfNodes; i++) {
nodes.add( new BasicNode() );
}
}
@Override
public void setNodes(List<NetworkNode> nn) {
this.nodes = nn;
}
@Override
public int getNumberOfNodes() {
return numberOfNodes;
}
@Override
public boolean isDirected() {
return directed;
}
@Override | public void setParameter(Parameter p) { |
hxnx-sam/DiscreteSpatialPhyloSimulator | src/trees/DeadNode.java | // Path: src/individualBasedModel/Host.java
// public class Host {
//
// ///////////////////////////////////
// // class variables and methods
// private static long hostCounter = -1;
//
// private static long nextHostUID() {
// hostCounter++;
// return (hostCounter);
// }
//
// /**
// * reset the host counter between multiple replicate runs of DiscreteSpatialPhyloSimulator
// */
// static void resetHostCounter() {
// hostCounter = -1;
// }
//
// ///////////////////////////////////
// // instance variables & methods
//
// // instance variables
// protected String name = null;
// protected long uid;
// protected InfectionState state = InfectionState.SUSCEPTIBLE;
//
// protected Deme myDeme;
//
// // constructors
// public Host(Deme myDeme) {
// this.uid = nextHostUID();
// this.name = "H"+String.format("%07d", uid); //""+uid;
// this.myDeme = myDeme;
// }
//
// public Host(Deme myDeme, String name) {
// this.uid = nextHostUID();
// this.name = name;
// this.myDeme = myDeme;
// }
//
// //////////////////////////////////
// // setters
//
// public void setState(InfectionState state) {
// this.state = state;
// }
//
// ///////////////////////////////////
// // getters
//
// public InfectionState getState() {
// return state;
// }
//
// public String getName() {
// if (this.name == null) {
// this.name = ""+uid;
// }
// return this.name;
// }
//
// public String getNameWithDeme() {
// //return (getName() + "_" + myDeme.getName());
// return (name + "_" + myDeme);
// }
//
// public long getUid() {
// return uid;
// }
//
// /////////////////////////////////////////////////////////////////////////
// // comparison methods and toString
//
// @Override
// public String toString() {
// return "Host [name=" + name + ", uid=" + uid + ", state=" + state
// + ", myDeme=" + myDeme + "]";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (int) (uid ^ (uid >>> 32));
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Host other = (Host) obj;
// if (uid != other.uid)
// return false;
// return true;
// }
//
//
//
// }
| import individualBasedModel.Host;
import java.util.List; | package trees;
/**
*
* @author slycett2
* @created 28 Oct 2015
*
* A Dead node is a special type of sampled node (but extend from TransmissionNode)
*/
public class DeadNode extends TransmissionNode {
static boolean includeTimeInSampledName = true;
static String delim = "|"; // good for BEAST 1
| // Path: src/individualBasedModel/Host.java
// public class Host {
//
// ///////////////////////////////////
// // class variables and methods
// private static long hostCounter = -1;
//
// private static long nextHostUID() {
// hostCounter++;
// return (hostCounter);
// }
//
// /**
// * reset the host counter between multiple replicate runs of DiscreteSpatialPhyloSimulator
// */
// static void resetHostCounter() {
// hostCounter = -1;
// }
//
// ///////////////////////////////////
// // instance variables & methods
//
// // instance variables
// protected String name = null;
// protected long uid;
// protected InfectionState state = InfectionState.SUSCEPTIBLE;
//
// protected Deme myDeme;
//
// // constructors
// public Host(Deme myDeme) {
// this.uid = nextHostUID();
// this.name = "H"+String.format("%07d", uid); //""+uid;
// this.myDeme = myDeme;
// }
//
// public Host(Deme myDeme, String name) {
// this.uid = nextHostUID();
// this.name = name;
// this.myDeme = myDeme;
// }
//
// //////////////////////////////////
// // setters
//
// public void setState(InfectionState state) {
// this.state = state;
// }
//
// ///////////////////////////////////
// // getters
//
// public InfectionState getState() {
// return state;
// }
//
// public String getName() {
// if (this.name == null) {
// this.name = ""+uid;
// }
// return this.name;
// }
//
// public String getNameWithDeme() {
// //return (getName() + "_" + myDeme.getName());
// return (name + "_" + myDeme);
// }
//
// public long getUid() {
// return uid;
// }
//
// /////////////////////////////////////////////////////////////////////////
// // comparison methods and toString
//
// @Override
// public String toString() {
// return "Host [name=" + name + ", uid=" + uid + ", state=" + state
// + ", myDeme=" + myDeme + "]";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (int) (uid ^ (uid >>> 32));
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Host other = (Host) obj;
// if (uid != other.uid)
// return false;
// return true;
// }
//
//
//
// }
// Path: src/trees/DeadNode.java
import individualBasedModel.Host;
import java.util.List;
package trees;
/**
*
* @author slycett2
* @created 28 Oct 2015
*
* A Dead node is a special type of sampled node (but extend from TransmissionNode)
*/
public class DeadNode extends TransmissionNode {
static boolean includeTimeInSampledName = true;
static String delim = "|"; // good for BEAST 1
| public DeadNode(Host h) { |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-mybatis-example/src/test/java/com/github/trang/druid/example/mybatis/test/coveralls/MyBatisTests.java | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/model/City.java
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private Long id;
// private String name;
// private String state;
// private String country;
//
// }
| import java.util.List;
import java.util.Optional;
import org.junit.Assert;
import org.junit.Test;
import com.github.trang.druid.example.mybatis.model.City; | package com.github.trang.druid.example.mybatis.test.coveralls;
/**
* MyBatis 测试
*
* @author trang
*/
public class MyBatisTests extends BaseTest {
@Test
public void testOne() {
Optional.ofNullable(cityMapper.findById(1L))
.map(gson::toJson)
.ifPresent(city -> log.info("{}", city));
}
@Test
public void testAll() { | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/model/City.java
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private Long id;
// private String name;
// private String state;
// private String country;
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/test/java/com/github/trang/druid/example/mybatis/test/coveralls/MyBatisTests.java
import java.util.List;
import java.util.Optional;
import org.junit.Assert;
import org.junit.Test;
import com.github.trang.druid.example.mybatis.model.City;
package com.github.trang.druid.example.mybatis.test.coveralls;
/**
* MyBatis 测试
*
* @author trang
*/
public class MyBatisTests extends BaseTest {
@Test
public void testOne() {
Optional.ofNullable(cityMapper.findById(1L))
.map(gson::toJson)
.ifPresent(city -> log.info("{}", city));
}
@Test
public void testAll() { | List<City> cities = cityMapper.findAll(); |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-jpa-example/src/test/java/com/github/trang/druid/example/jpa/test/coveralls/JpaTests.java | // Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/model/City.java
// @Entity
// @Table(name = "city")
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id")
// private Long id;
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "state")
// private String state;
//
// @Column(name = "country")
// private String country;
//
// }
| import java.util.List;
import java.util.Optional;
import org.junit.Assert;
import org.junit.Test;
import com.github.trang.druid.example.jpa.model.City; | package com.github.trang.druid.example.jpa.test.coveralls;
/**
* MyBatis 测试
*
* @author trang
*/
public class JpaTests extends BaseTest {
@Test
public void testOne() {
Optional.ofNullable(cityRepository.findOne(1L))
.map(gson::toJson)
.ifPresent(city -> log.info("{}", city));
}
@Test
public void testAll() { | // Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/model/City.java
// @Entity
// @Table(name = "city")
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id")
// private Long id;
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "state")
// private String state;
//
// @Column(name = "country")
// private String country;
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/test/java/com/github/trang/druid/example/jpa/test/coveralls/JpaTests.java
import java.util.List;
import java.util.Optional;
import org.junit.Assert;
import org.junit.Test;
import com.github.trang.druid.example.jpa.model.City;
package com.github.trang.druid.example.jpa.test.coveralls;
/**
* MyBatis 测试
*
* @author trang
*/
public class JpaTests extends BaseTest {
@Test
public void testOne() {
Optional.ofNullable(cityRepository.findOne(1L))
.map(gson::toJson)
.ifPresent(city -> log.info("{}", city));
}
@Test
public void testAll() { | List<City> cities = cityRepository.findAll(); |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/DruidJpaApplication.java | // Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/repository/CityRepository.java
// public interface CityRepository extends JpaRepository<City, Long> {
//
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.github.trang.druid.example.jpa.repository.CityRepository;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j; | package com.github.trang.druid.example.jpa;
/**
* DruidSpringBootStarterApplication
*
* @author trang
*/
@SpringBootApplication
@Slf4j
public class DruidJpaApplication implements CommandLineRunner {
public static void main(String[] args) {
System.setProperty("druid.logType", "slf4j");
SpringApplication.run(DruidJpaApplication.class, args);
}
@Autowired | // Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/repository/CityRepository.java
// public interface CityRepository extends JpaRepository<City, Long> {
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/DruidJpaApplication.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.github.trang.druid.example.jpa.repository.CityRepository;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
package com.github.trang.druid.example.jpa;
/**
* DruidSpringBootStarterApplication
*
* @author trang
*/
@SpringBootApplication
@Slf4j
public class DruidJpaApplication implements CommandLineRunner {
public static void main(String[] args) {
System.setProperty("druid.logType", "slf4j");
SpringApplication.run(DruidJpaApplication.class, args);
}
@Autowired | private CityRepository cityRepository; |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-mybatis-example/src/test/java/com/github/trang/druid/example/mybatis/test/coveralls/BaseTest.java | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/DruidMybatisApplication.java
// @SpringBootApplication
// @MapperScan("com.github.trang.druid.example.mapper")
// @Slf4j
// public class DruidMybatisApplication implements CommandLineRunner {
//
// public static void main(String[] args) {
// System.setProperty("druid.logType", "slf4j");
// SpringApplication.run(DruidMybatisApplication.class, args);
// }
//
// @Autowired
// private CityMapper cityRepository;
//
// @Override
// public void run(String... args) {
// Gson gson = new Gson();
// cityRepository.findAll().stream()
// .map(gson::toJson)
// .forEach(log::info);
// }
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/mapper/CityMapper.java
// @Mapper
// public interface CityMapper {
//
// @Select("select * from city")
// List<City> findAll();
//
// @Select("select * from city where id = #{id}")
// City findById(@Param("id") Long id);
//
// }
| import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.github.trang.druid.example.mybatis.DruidMybatisApplication;
import com.github.trang.druid.example.mybatis.mapper.CityMapper;
import com.google.gson.Gson; | package com.github.trang.druid.example.mybatis.test.coveralls;
/**
* BaseTest
*
* @author trang
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DruidMybatisApplication.class)
public abstract class BaseTest {
protected static final Logger log = LoggerFactory.getLogger(BaseTest.class.getSimpleName());
protected Gson gson = new Gson();
@Autowired(required = false) | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/DruidMybatisApplication.java
// @SpringBootApplication
// @MapperScan("com.github.trang.druid.example.mapper")
// @Slf4j
// public class DruidMybatisApplication implements CommandLineRunner {
//
// public static void main(String[] args) {
// System.setProperty("druid.logType", "slf4j");
// SpringApplication.run(DruidMybatisApplication.class, args);
// }
//
// @Autowired
// private CityMapper cityRepository;
//
// @Override
// public void run(String... args) {
// Gson gson = new Gson();
// cityRepository.findAll().stream()
// .map(gson::toJson)
// .forEach(log::info);
// }
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/mapper/CityMapper.java
// @Mapper
// public interface CityMapper {
//
// @Select("select * from city")
// List<City> findAll();
//
// @Select("select * from city where id = #{id}")
// City findById(@Param("id") Long id);
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/test/java/com/github/trang/druid/example/mybatis/test/coveralls/BaseTest.java
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.github.trang.druid.example.mybatis.DruidMybatisApplication;
import com.github.trang.druid.example.mybatis.mapper.CityMapper;
import com.google.gson.Gson;
package com.github.trang.druid.example.mybatis.test.coveralls;
/**
* BaseTest
*
* @author trang
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DruidMybatisApplication.class)
public abstract class BaseTest {
protected static final Logger log = LoggerFactory.getLogger(BaseTest.class.getSimpleName());
protected Gson gson = new Gson();
@Autowired(required = false) | protected CityMapper cityMapper; |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/DruidMybatisApplication.java | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/mapper/CityMapper.java
// @Mapper
// public interface CityMapper {
//
// @Select("select * from city")
// List<City> findAll();
//
// @Select("select * from city where id = #{id}")
// City findById(@Param("id") Long id);
//
// }
| import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.github.trang.druid.example.mybatis.mapper.CityMapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j; | package com.github.trang.druid.example.mybatis;
/**
* DruidSpringBootStarterApplication
*
* @author trang
*/
@SpringBootApplication
@MapperScan("com.github.trang.druid.example.mapper")
@Slf4j
public class DruidMybatisApplication implements CommandLineRunner {
public static void main(String[] args) {
System.setProperty("druid.logType", "slf4j");
SpringApplication.run(DruidMybatisApplication.class, args);
}
@Autowired | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/mapper/CityMapper.java
// @Mapper
// public interface CityMapper {
//
// @Select("select * from city")
// List<City> findAll();
//
// @Select("select * from city where id = #{id}")
// City findById(@Param("id") Long id);
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/DruidMybatisApplication.java
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.github.trang.druid.example.mybatis.mapper.CityMapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
package com.github.trang.druid.example.mybatis;
/**
* DruidSpringBootStarterApplication
*
* @author trang
*/
@SpringBootApplication
@MapperScan("com.github.trang.druid.example.mapper")
@Slf4j
public class DruidMybatisApplication implements CommandLineRunner {
public static void main(String[] args) {
System.setProperty("druid.logType", "slf4j");
SpringApplication.run(DruidMybatisApplication.class, args);
}
@Autowired | private CityMapper cityRepository; |
drtrang/druid-spring-boot | druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/autoconfigure/DruidDataSourceMetadataProviderConfiguration.java | // Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/DruidDataSourcePoolMetadata.java
// public class DruidDataSourcePoolMetadata extends AbstractDataSourcePoolMetadata<DruidDataSource> {
//
// public DruidDataSourcePoolMetadata(DruidDataSource dataSource) {
// super(dataSource);
// }
//
// @Override
// public Integer getActive() {
// return getDataSource().getActiveCount();
// }
//
// @Override
// public Integer getMax() {
// return getDataSource().getMaxActive();
// }
//
// @Override
// public Integer getMin() {
// return getDataSource().getMinIdle();
// }
//
// @Override
// public String getValidationQuery() {
// return getDataSource().getValidationQuery();
// }
//
// }
| import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.actuate.DruidDataSourcePoolMetadata; | package com.github.trang.druid.actuate.autoconfigure;
/**
* Druid Metadata 自动配置,适用于 Metrics,默认开启
*
* @author trang
*/
@Configuration
@ConditionalOnClass(DruidDataSource.class)
public class DruidDataSourceMetadataProviderConfiguration {
@Bean
@ConditionalOnMissingBean
public DataSourcePoolMetadataProvider dataSourcePoolMetadataProvider() {
return (dataSource) -> {
if (dataSource instanceof DruidDataSource) { | // Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/DruidDataSourcePoolMetadata.java
// public class DruidDataSourcePoolMetadata extends AbstractDataSourcePoolMetadata<DruidDataSource> {
//
// public DruidDataSourcePoolMetadata(DruidDataSource dataSource) {
// super(dataSource);
// }
//
// @Override
// public Integer getActive() {
// return getDataSource().getActiveCount();
// }
//
// @Override
// public Integer getMax() {
// return getDataSource().getMaxActive();
// }
//
// @Override
// public Integer getMin() {
// return getDataSource().getMinIdle();
// }
//
// @Override
// public String getValidationQuery() {
// return getDataSource().getValidationQuery();
// }
//
// }
// Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/autoconfigure/DruidDataSourceMetadataProviderConfiguration.java
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.actuate.DruidDataSourcePoolMetadata;
package com.github.trang.druid.actuate.autoconfigure;
/**
* Druid Metadata 自动配置,适用于 Metrics,默认开启
*
* @author trang
*/
@Configuration
@ConditionalOnClass(DruidDataSource.class)
public class DruidDataSourceMetadataProviderConfiguration {
@Bean
@ConditionalOnMissingBean
public DataSourcePoolMetadataProvider dataSourcePoolMetadataProvider() {
return (dataSource) -> {
if (dataSource instanceof DruidDataSource) { | return new DruidDataSourcePoolMetadata((DruidDataSource) dataSource); |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/config/SpringDataSourceConfig.java | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/DruidDataSourceCustomizer.java
// public interface DruidDataSourceCustomizer {
//
// /**
// * 自定义 DruidDataSource
// *
// * @param druidDataSource druid 数据源
// */
// void customize(DruidDataSource druidDataSource);
//
// }
| import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.DruidDataSourceCustomizer;
import lombok.extern.slf4j.Slf4j; | package com.github.trang.druid.example.mybatis.config;
/**
* 多数据源配置,只在 #{@code spring.profiles.active=dynamic} 时生效
*
* @author trang
*/
@Configuration
@Profile({"dynamic", "dynamic-dev-yaml", "dynamic-dev-props"})
@Slf4j
public class SpringDataSourceConfig {
/**
* 自定义 DruidDataSource,所有的数据源都会生效
*
* @return druidDataSourceCustomizer
*/
@Bean | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/DruidDataSourceCustomizer.java
// public interface DruidDataSourceCustomizer {
//
// /**
// * 自定义 DruidDataSource
// *
// * @param druidDataSource druid 数据源
// */
// void customize(DruidDataSource druidDataSource);
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/config/SpringDataSourceConfig.java
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.DruidDataSourceCustomizer;
import lombok.extern.slf4j.Slf4j;
package com.github.trang.druid.example.mybatis.config;
/**
* 多数据源配置,只在 #{@code spring.profiles.active=dynamic} 时生效
*
* @author trang
*/
@Configuration
@Profile({"dynamic", "dynamic-dev-yaml", "dynamic-dev-props"})
@Slf4j
public class SpringDataSourceConfig {
/**
* 自定义 DruidDataSource,所有的数据源都会生效
*
* @return druidDataSourceCustomizer
*/
@Bean | public DruidDataSourceCustomizer druidDataSourceCustomizer() { |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-mybatis-example/src/test/java/com/github/trang/druid/example/mybatis/test/coveralls/DynamicDataSourceTests.java | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/datasource/DruidDataSource2.java
// public class DruidDataSource2 extends AbstractDruidDataSource2 {
//
// private static final long serialVersionUID = 4980333179163868927L;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/config/DynamicDataSource.java
// @Slf4j
// @Getter
// @RequiredArgsConstructor
// public class DynamicDataSource extends AbstractRoutingDataSource {
//
// private final AtomicInteger count = new AtomicInteger();
// private final Map<String, DataSource> targetDataSources;
//
// /**
// * 基于轮询算法指定实际的数据源
// *
// * @return dataSource
// */
// @Override
// protected Object determineCurrentLookupKey() {
// int i = count.incrementAndGet();
// List<String> list = new ArrayList<>(targetDataSources.keySet());
// String dataSource = list.get(i % list.size());
// log.info(">>>>>> 当前数据库: {} <<<<<<", dataSource);
// return dataSource;
// }
//
// @Override
// public void afterPropertiesSet() {
// super.setTargetDataSources(new HashMap<>(targetDataSources));
// super.afterPropertiesSet();
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.datasource.DruidDataSource2;
import com.github.trang.druid.example.mybatis.config.DynamicDataSource; | package com.github.trang.druid.example.mybatis.test.coveralls;
/**
* 动态数据源测试
*
* @author trang
*/
@ActiveProfiles("dynamic")
public class DynamicDataSourceTests extends BaseTest {
@Autowired
private DruidDataSource masterDataSource;
@Autowired
private DruidDataSource slaveDataSource;
@Autowired | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/datasource/DruidDataSource2.java
// public class DruidDataSource2 extends AbstractDruidDataSource2 {
//
// private static final long serialVersionUID = 4980333179163868927L;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/config/DynamicDataSource.java
// @Slf4j
// @Getter
// @RequiredArgsConstructor
// public class DynamicDataSource extends AbstractRoutingDataSource {
//
// private final AtomicInteger count = new AtomicInteger();
// private final Map<String, DataSource> targetDataSources;
//
// /**
// * 基于轮询算法指定实际的数据源
// *
// * @return dataSource
// */
// @Override
// protected Object determineCurrentLookupKey() {
// int i = count.incrementAndGet();
// List<String> list = new ArrayList<>(targetDataSources.keySet());
// String dataSource = list.get(i % list.size());
// log.info(">>>>>> 当前数据库: {} <<<<<<", dataSource);
// return dataSource;
// }
//
// @Override
// public void afterPropertiesSet() {
// super.setTargetDataSources(new HashMap<>(targetDataSources));
// super.afterPropertiesSet();
// }
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/test/java/com/github/trang/druid/example/mybatis/test/coveralls/DynamicDataSourceTests.java
import static org.junit.Assert.assertEquals;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.datasource.DruidDataSource2;
import com.github.trang.druid.example.mybatis.config.DynamicDataSource;
package com.github.trang.druid.example.mybatis.test.coveralls;
/**
* 动态数据源测试
*
* @author trang
*/
@ActiveProfiles("dynamic")
public class DynamicDataSourceTests extends BaseTest {
@Autowired
private DruidDataSource masterDataSource;
@Autowired
private DruidDataSource slaveDataSource;
@Autowired | private DynamicDataSource dataSource; |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-mybatis-example/src/test/java/com/github/trang/druid/example/mybatis/test/coveralls/DynamicDataSourceTests.java | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/datasource/DruidDataSource2.java
// public class DruidDataSource2 extends AbstractDruidDataSource2 {
//
// private static final long serialVersionUID = 4980333179163868927L;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/config/DynamicDataSource.java
// @Slf4j
// @Getter
// @RequiredArgsConstructor
// public class DynamicDataSource extends AbstractRoutingDataSource {
//
// private final AtomicInteger count = new AtomicInteger();
// private final Map<String, DataSource> targetDataSources;
//
// /**
// * 基于轮询算法指定实际的数据源
// *
// * @return dataSource
// */
// @Override
// protected Object determineCurrentLookupKey() {
// int i = count.incrementAndGet();
// List<String> list = new ArrayList<>(targetDataSources.keySet());
// String dataSource = list.get(i % list.size());
// log.info(">>>>>> 当前数据库: {} <<<<<<", dataSource);
// return dataSource;
// }
//
// @Override
// public void afterPropertiesSet() {
// super.setTargetDataSources(new HashMap<>(targetDataSources));
// super.afterPropertiesSet();
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.datasource.DruidDataSource2;
import com.github.trang.druid.example.mybatis.config.DynamicDataSource; | public void testDynamicDataSource() {
assertEquals(dataSource.getTargetDataSources().size(), 2);
}
@Autowired(required = false)
private Map<String, DruidDataSource> dataSourceMap;
@Autowired(required = false)
private Map<String, DruidDataSource> druidDataSourceMap;
@Autowired(required = false)
private Map<String, DruidDataSource> foolDataSourceMap;
@Autowired(required = false)
private List<DruidDataSource> dataSourceList;
@Autowired(required = false)
private List<DruidDataSource> dataSources;
@Autowired(required = false)
private List<DruidDataSource> druidDataSourceList;
@Autowired(required = false)
private List<DruidDataSource> druidDataSources;
@Autowired(required = false)
private List<DruidDataSource> foolDataSources;
@Autowired(required = false)
private Collection<DruidDataSource> druidDataSourceCollection;
@Autowired(required = false)
private Set<DruidDataSource> druidDataSourceSet;
@Autowired(required = false)
private DruidDataSource[] druidDataSourceArray;
@Autowired(required = false) | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/datasource/DruidDataSource2.java
// public class DruidDataSource2 extends AbstractDruidDataSource2 {
//
// private static final long serialVersionUID = 4980333179163868927L;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/config/DynamicDataSource.java
// @Slf4j
// @Getter
// @RequiredArgsConstructor
// public class DynamicDataSource extends AbstractRoutingDataSource {
//
// private final AtomicInteger count = new AtomicInteger();
// private final Map<String, DataSource> targetDataSources;
//
// /**
// * 基于轮询算法指定实际的数据源
// *
// * @return dataSource
// */
// @Override
// protected Object determineCurrentLookupKey() {
// int i = count.incrementAndGet();
// List<String> list = new ArrayList<>(targetDataSources.keySet());
// String dataSource = list.get(i % list.size());
// log.info(">>>>>> 当前数据库: {} <<<<<<", dataSource);
// return dataSource;
// }
//
// @Override
// public void afterPropertiesSet() {
// super.setTargetDataSources(new HashMap<>(targetDataSources));
// super.afterPropertiesSet();
// }
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/test/java/com/github/trang/druid/example/mybatis/test/coveralls/DynamicDataSourceTests.java
import static org.junit.Assert.assertEquals;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.datasource.DruidDataSource2;
import com.github.trang.druid.example.mybatis.config.DynamicDataSource;
public void testDynamicDataSource() {
assertEquals(dataSource.getTargetDataSources().size(), 2);
}
@Autowired(required = false)
private Map<String, DruidDataSource> dataSourceMap;
@Autowired(required = false)
private Map<String, DruidDataSource> druidDataSourceMap;
@Autowired(required = false)
private Map<String, DruidDataSource> foolDataSourceMap;
@Autowired(required = false)
private List<DruidDataSource> dataSourceList;
@Autowired(required = false)
private List<DruidDataSource> dataSources;
@Autowired(required = false)
private List<DruidDataSource> druidDataSourceList;
@Autowired(required = false)
private List<DruidDataSource> druidDataSources;
@Autowired(required = false)
private List<DruidDataSource> foolDataSources;
@Autowired(required = false)
private Collection<DruidDataSource> druidDataSourceCollection;
@Autowired(required = false)
private Set<DruidDataSource> druidDataSourceSet;
@Autowired(required = false)
private DruidDataSource[] druidDataSourceArray;
@Autowired(required = false) | private Map<String, DruidDataSource2> dataSource2Map; |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-jpa-example/src/test/java/com/github/trang/druid/example/jpa/test/coveralls/DynamicDataSourceTests.java | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/datasource/DruidDataSource2.java
// public class DruidDataSource2 extends AbstractDruidDataSource2 {
//
// private static final long serialVersionUID = 4980333179163868927L;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/config/DynamicDataSource.java
// @Slf4j
// @Getter
// @RequiredArgsConstructor
// public class DynamicDataSource extends AbstractRoutingDataSource {
//
// private final AtomicInteger count = new AtomicInteger();
// private final Map<String, DataSource> targetDataSources;
//
// /**
// * 基于轮询算法指定实际的数据源
// *
// * @return dataSource
// */
// @Override
// protected Object determineCurrentLookupKey() {
// int i = count.incrementAndGet();
// List<String> list = new ArrayList<>(targetDataSources.keySet());
// String dataSource = list.get(i % list.size());
// log.info(">>>>>> 当前数据库: {} <<<<<<", dataSource);
// return dataSource;
// }
//
// @Override
// public void afterPropertiesSet() {
// super.setTargetDataSources(new HashMap<>(targetDataSources));
// super.afterPropertiesSet();
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.datasource.DruidDataSource2;
import com.github.trang.druid.example.jpa.config.DynamicDataSource; | package com.github.trang.druid.example.jpa.test.coveralls;
/**
* 动态数据源测试
*
* @author trang
*/
@ActiveProfiles("dynamic")
public class DynamicDataSourceTests extends BaseTest {
@Autowired
private DruidDataSource masterDataSource;
@Autowired
private DruidDataSource slaveDataSource;
@Autowired | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/datasource/DruidDataSource2.java
// public class DruidDataSource2 extends AbstractDruidDataSource2 {
//
// private static final long serialVersionUID = 4980333179163868927L;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/config/DynamicDataSource.java
// @Slf4j
// @Getter
// @RequiredArgsConstructor
// public class DynamicDataSource extends AbstractRoutingDataSource {
//
// private final AtomicInteger count = new AtomicInteger();
// private final Map<String, DataSource> targetDataSources;
//
// /**
// * 基于轮询算法指定实际的数据源
// *
// * @return dataSource
// */
// @Override
// protected Object determineCurrentLookupKey() {
// int i = count.incrementAndGet();
// List<String> list = new ArrayList<>(targetDataSources.keySet());
// String dataSource = list.get(i % list.size());
// log.info(">>>>>> 当前数据库: {} <<<<<<", dataSource);
// return dataSource;
// }
//
// @Override
// public void afterPropertiesSet() {
// super.setTargetDataSources(new HashMap<>(targetDataSources));
// super.afterPropertiesSet();
// }
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/test/java/com/github/trang/druid/example/jpa/test/coveralls/DynamicDataSourceTests.java
import static org.junit.Assert.assertEquals;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.datasource.DruidDataSource2;
import com.github.trang.druid.example.jpa.config.DynamicDataSource;
package com.github.trang.druid.example.jpa.test.coveralls;
/**
* 动态数据源测试
*
* @author trang
*/
@ActiveProfiles("dynamic")
public class DynamicDataSourceTests extends BaseTest {
@Autowired
private DruidDataSource masterDataSource;
@Autowired
private DruidDataSource slaveDataSource;
@Autowired | private DynamicDataSource dataSource; |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-jpa-example/src/test/java/com/github/trang/druid/example/jpa/test/coveralls/DynamicDataSourceTests.java | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/datasource/DruidDataSource2.java
// public class DruidDataSource2 extends AbstractDruidDataSource2 {
//
// private static final long serialVersionUID = 4980333179163868927L;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/config/DynamicDataSource.java
// @Slf4j
// @Getter
// @RequiredArgsConstructor
// public class DynamicDataSource extends AbstractRoutingDataSource {
//
// private final AtomicInteger count = new AtomicInteger();
// private final Map<String, DataSource> targetDataSources;
//
// /**
// * 基于轮询算法指定实际的数据源
// *
// * @return dataSource
// */
// @Override
// protected Object determineCurrentLookupKey() {
// int i = count.incrementAndGet();
// List<String> list = new ArrayList<>(targetDataSources.keySet());
// String dataSource = list.get(i % list.size());
// log.info(">>>>>> 当前数据库: {} <<<<<<", dataSource);
// return dataSource;
// }
//
// @Override
// public void afterPropertiesSet() {
// super.setTargetDataSources(new HashMap<>(targetDataSources));
// super.afterPropertiesSet();
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.datasource.DruidDataSource2;
import com.github.trang.druid.example.jpa.config.DynamicDataSource; | public void testDynamicDataSource() {
assertEquals(dataSource.getTargetDataSources().size(), 2);
}
@Autowired(required = false)
private Map<String, DruidDataSource> dataSourceMap;
@Autowired(required = false)
private Map<String, DruidDataSource> druidDataSourceMap;
@Autowired(required = false)
private Map<String, DruidDataSource> foolDataSourceMap;
@Autowired(required = false)
private List<DruidDataSource> dataSourceList;
@Autowired(required = false)
private List<DruidDataSource> dataSources;
@Autowired(required = false)
private List<DruidDataSource> druidDataSourceList;
@Autowired(required = false)
private List<DruidDataSource> druidDataSources;
@Autowired(required = false)
private List<DruidDataSource> foolDataSources;
@Autowired(required = false)
private Collection<DruidDataSource> druidDataSourceCollection;
@Autowired(required = false)
private Set<DruidDataSource> druidDataSourceSet;
@Autowired(required = false)
private DruidDataSource[] druidDataSourceArray;
@Autowired(required = false) | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/datasource/DruidDataSource2.java
// public class DruidDataSource2 extends AbstractDruidDataSource2 {
//
// private static final long serialVersionUID = 4980333179163868927L;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/config/DynamicDataSource.java
// @Slf4j
// @Getter
// @RequiredArgsConstructor
// public class DynamicDataSource extends AbstractRoutingDataSource {
//
// private final AtomicInteger count = new AtomicInteger();
// private final Map<String, DataSource> targetDataSources;
//
// /**
// * 基于轮询算法指定实际的数据源
// *
// * @return dataSource
// */
// @Override
// protected Object determineCurrentLookupKey() {
// int i = count.incrementAndGet();
// List<String> list = new ArrayList<>(targetDataSources.keySet());
// String dataSource = list.get(i % list.size());
// log.info(">>>>>> 当前数据库: {} <<<<<<", dataSource);
// return dataSource;
// }
//
// @Override
// public void afterPropertiesSet() {
// super.setTargetDataSources(new HashMap<>(targetDataSources));
// super.afterPropertiesSet();
// }
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/test/java/com/github/trang/druid/example/jpa/test/coveralls/DynamicDataSourceTests.java
import static org.junit.Assert.assertEquals;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.datasource.DruidDataSource2;
import com.github.trang.druid.example.jpa.config.DynamicDataSource;
public void testDynamicDataSource() {
assertEquals(dataSource.getTargetDataSources().size(), 2);
}
@Autowired(required = false)
private Map<String, DruidDataSource> dataSourceMap;
@Autowired(required = false)
private Map<String, DruidDataSource> druidDataSourceMap;
@Autowired(required = false)
private Map<String, DruidDataSource> foolDataSourceMap;
@Autowired(required = false)
private List<DruidDataSource> dataSourceList;
@Autowired(required = false)
private List<DruidDataSource> dataSources;
@Autowired(required = false)
private List<DruidDataSource> druidDataSourceList;
@Autowired(required = false)
private List<DruidDataSource> druidDataSources;
@Autowired(required = false)
private List<DruidDataSource> foolDataSources;
@Autowired(required = false)
private Collection<DruidDataSource> druidDataSourceCollection;
@Autowired(required = false)
private Set<DruidDataSource> druidDataSourceSet;
@Autowired(required = false)
private DruidDataSource[] druidDataSourceArray;
@Autowired(required = false) | private Map<String, DruidDataSource2> dataSource2Map; |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-jpa-example/src/test/java/com/github/trang/druid/example/jpa/test/coveralls/BaseTest.java | // Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/DruidJpaApplication.java
// @SpringBootApplication
// @Slf4j
// public class DruidJpaApplication implements CommandLineRunner {
//
// public static void main(String[] args) {
// System.setProperty("druid.logType", "slf4j");
// SpringApplication.run(DruidJpaApplication.class, args);
// }
//
// @Autowired
// private CityRepository cityRepository;
//
// @Override
// public void run(String... args) {
// Gson gson = new Gson();
// cityRepository.findAll().stream()
// .map(gson::toJson)
// .forEach(log::info);
// }
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/repository/CityRepository.java
// public interface CityRepository extends JpaRepository<City, Long> {
//
// }
| import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.github.trang.druid.example.jpa.DruidJpaApplication;
import com.github.trang.druid.example.jpa.repository.CityRepository;
import com.google.gson.Gson; | package com.github.trang.druid.example.jpa.test.coveralls;
/**
* BaseTest
*
* @author trang
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DruidJpaApplication.class)
public abstract class BaseTest {
protected static final Logger log = LoggerFactory.getLogger(BaseTest.class.getSimpleName());
protected Gson gson = new Gson();
@Autowired(required = false) | // Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/DruidJpaApplication.java
// @SpringBootApplication
// @Slf4j
// public class DruidJpaApplication implements CommandLineRunner {
//
// public static void main(String[] args) {
// System.setProperty("druid.logType", "slf4j");
// SpringApplication.run(DruidJpaApplication.class, args);
// }
//
// @Autowired
// private CityRepository cityRepository;
//
// @Override
// public void run(String... args) {
// Gson gson = new Gson();
// cityRepository.findAll().stream()
// .map(gson::toJson)
// .forEach(log::info);
// }
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/repository/CityRepository.java
// public interface CityRepository extends JpaRepository<City, Long> {
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/test/java/com/github/trang/druid/example/jpa/test/coveralls/BaseTest.java
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.github.trang.druid.example.jpa.DruidJpaApplication;
import com.github.trang.druid.example.jpa.repository.CityRepository;
import com.google.gson.Gson;
package com.github.trang.druid.example.jpa.test.coveralls;
/**
* BaseTest
*
* @author trang
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DruidJpaApplication.class)
public abstract class BaseTest {
protected static final Logger log = LoggerFactory.getLogger(BaseTest.class.getSimpleName());
protected Gson gson = new Gson();
@Autowired(required = false) | protected CityRepository cityRepository; |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/controller/CityController.java | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/mapper/CityMapper.java
// @Mapper
// public interface CityMapper {
//
// @Select("select * from city")
// List<City> findAll();
//
// @Select("select * from city where id = #{id}")
// City findById(@Param("id") Long id);
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/model/City.java
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private Long id;
// private String name;
// private String state;
// private String country;
//
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.trang.druid.example.mybatis.mapper.CityMapper;
import com.github.trang.druid.example.mybatis.model.City; | package com.github.trang.druid.example.mybatis.controller;
/**
* CityController
*
* @author trang
*/
@RestController
@RequestMapping("/city")
public class CityController {
@Autowired | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/mapper/CityMapper.java
// @Mapper
// public interface CityMapper {
//
// @Select("select * from city")
// List<City> findAll();
//
// @Select("select * from city where id = #{id}")
// City findById(@Param("id") Long id);
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/model/City.java
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private Long id;
// private String name;
// private String state;
// private String country;
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/controller/CityController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.trang.druid.example.mybatis.mapper.CityMapper;
import com.github.trang.druid.example.mybatis.model.City;
package com.github.trang.druid.example.mybatis.controller;
/**
* CityController
*
* @author trang
*/
@RestController
@RequestMapping("/city")
public class CityController {
@Autowired | private CityMapper cityMapper; |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/controller/CityController.java | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/mapper/CityMapper.java
// @Mapper
// public interface CityMapper {
//
// @Select("select * from city")
// List<City> findAll();
//
// @Select("select * from city where id = #{id}")
// City findById(@Param("id") Long id);
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/model/City.java
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private Long id;
// private String name;
// private String state;
// private String country;
//
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.trang.druid.example.mybatis.mapper.CityMapper;
import com.github.trang.druid.example.mybatis.model.City; | package com.github.trang.druid.example.mybatis.controller;
/**
* CityController
*
* @author trang
*/
@RestController
@RequestMapping("/city")
public class CityController {
@Autowired
private CityMapper cityMapper;
@GetMapping("/get/{id}") | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/mapper/CityMapper.java
// @Mapper
// public interface CityMapper {
//
// @Select("select * from city")
// List<City> findAll();
//
// @Select("select * from city where id = #{id}")
// City findById(@Param("id") Long id);
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/model/City.java
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private Long id;
// private String name;
// private String state;
// private String country;
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/controller/CityController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.trang.druid.example.mybatis.mapper.CityMapper;
import com.github.trang.druid.example.mybatis.model.City;
package com.github.trang.druid.example.mybatis.controller;
/**
* CityController
*
* @author trang
*/
@RestController
@RequestMapping("/city")
public class CityController {
@Autowired
private CityMapper cityMapper;
@GetMapping("/get/{id}") | public City get(@PathVariable Long id) { |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/mapper/CityMapper.java | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/model/City.java
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private Long id;
// private String name;
// private String state;
// private String country;
//
// }
| import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.github.trang.druid.example.mybatis.model.City; | package com.github.trang.druid.example.mybatis.mapper;
/**
* CityMapper
*
* @author trang
*/
@Mapper
public interface CityMapper {
@Select("select * from city") | // Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/model/City.java
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private Long id;
// private String name;
// private String state;
// private String country;
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-mybatis-example/src/main/java/com/github/trang/druid/example/mybatis/mapper/CityMapper.java
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.github.trang.druid.example.mybatis.model.City;
package com.github.trang.druid.example.mybatis.mapper;
/**
* CityMapper
*
* @author trang
*/
@Mapper
public interface CityMapper {
@Select("select * from city") | List<City> findAll(); |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/controller/CityController.java | // Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/model/City.java
// @Entity
// @Table(name = "city")
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id")
// private Long id;
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "state")
// private String state;
//
// @Column(name = "country")
// private String country;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/repository/CityRepository.java
// public interface CityRepository extends JpaRepository<City, Long> {
//
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.trang.druid.example.jpa.model.City;
import com.github.trang.druid.example.jpa.repository.CityRepository; | package com.github.trang.druid.example.jpa.controller;
/**
* CityController
*
* @author trang
*/
@RestController
@RequestMapping("/city")
public class CityController {
@Autowired | // Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/model/City.java
// @Entity
// @Table(name = "city")
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id")
// private Long id;
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "state")
// private String state;
//
// @Column(name = "country")
// private String country;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/repository/CityRepository.java
// public interface CityRepository extends JpaRepository<City, Long> {
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/controller/CityController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.trang.druid.example.jpa.model.City;
import com.github.trang.druid.example.jpa.repository.CityRepository;
package com.github.trang.druid.example.jpa.controller;
/**
* CityController
*
* @author trang
*/
@RestController
@RequestMapping("/city")
public class CityController {
@Autowired | private CityRepository cityRepository; |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/controller/CityController.java | // Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/model/City.java
// @Entity
// @Table(name = "city")
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id")
// private Long id;
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "state")
// private String state;
//
// @Column(name = "country")
// private String country;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/repository/CityRepository.java
// public interface CityRepository extends JpaRepository<City, Long> {
//
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.trang.druid.example.jpa.model.City;
import com.github.trang.druid.example.jpa.repository.CityRepository; | package com.github.trang.druid.example.jpa.controller;
/**
* CityController
*
* @author trang
*/
@RestController
@RequestMapping("/city")
public class CityController {
@Autowired
private CityRepository cityRepository;
@GetMapping("/get/{id}") | // Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/model/City.java
// @Entity
// @Table(name = "city")
// @Data
// public class City implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id")
// private Long id;
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "state")
// private String state;
//
// @Column(name = "country")
// private String country;
//
// }
//
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/repository/CityRepository.java
// public interface CityRepository extends JpaRepository<City, Long> {
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/controller/CityController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.trang.druid.example.jpa.model.City;
import com.github.trang.druid.example.jpa.repository.CityRepository;
package com.github.trang.druid.example.jpa.controller;
/**
* CityController
*
* @author trang
*/
@RestController
@RequestMapping("/city")
public class CityController {
@Autowired
private CityRepository cityRepository;
@GetMapping("/get/{id}") | public City get(@PathVariable Long id) { |
drtrang/druid-spring-boot | druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/autoconfigure/DruidDataSourceEndpointConfiguration.java | // Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/DruidDataSourceEndpoint.java
// @ConfigurationProperties(prefix = "endpoints.druid")
// public class DruidDataSourceEndpoint extends AbstractEndpoint<List<Map<String, Object>>> {
//
// public DruidDataSourceEndpoint() {
// super("druid");
// }
//
// private static final DruidStatManagerFacade STAT_MANAGER = DruidStatManagerFacade.getInstance();
//
// @Override
// public List<Map<String, Object>> invoke() {
// return STAT_MANAGER.getDataSourceStatDataList();
// }
//
// }
//
// Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/DruidDataSourceMvcEndpoint.java
// @ConfigurationProperties(prefix = "endpoints.druid")
// public class DruidDataSourceMvcEndpoint extends EndpointMvcAdapter {
//
// private static final DruidStatService statService = DruidStatService.getInstance();
//
// private final long timeout;
// private final Lock lock = new ReentrantLock();
//
// public DruidDataSourceMvcEndpoint(DruidDataSourceEndpoint delegate) {
// super(delegate);
// this.timeout = TimeUnit.SECONDS.toMillis(10);
// }
//
// public DruidDataSourceMvcEndpoint(DruidDataSourceEndpoint delegate, long timeout) {
// super(delegate);
// this.timeout = timeout;
// }
//
// @GetMapping(value = "/{name:.*}", produces = {ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE,
// MediaType.APPLICATION_JSON_VALUE})
// @ResponseBody
// @HypermediaDisabled
// public String handle(@PathVariable String name) {
// String temp = name;
// if (name.contains(".")) {
// temp = name.substring(0, name.indexOf("."));
// }
// name = "/" + temp + ".json";
// return statService.service(name);
// }
//
// }
| import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.trang.druid.actuate.DruidDataSourceEndpoint;
import com.github.trang.druid.actuate.DruidDataSourceMvcEndpoint; | package com.github.trang.druid.actuate.autoconfigure;
/**
* Druid Endpoint & Druid MvcEndpoint 自动配置,默认开启
*
* @author trang
*/
@Configuration
@ConditionalOnProperty(prefix = "endpoints.druid", name = "enabled", havingValue = "true", matchIfMissing = true)
public class DruidDataSourceEndpointConfiguration {
@Bean
@ConditionalOnMissingBean | // Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/DruidDataSourceEndpoint.java
// @ConfigurationProperties(prefix = "endpoints.druid")
// public class DruidDataSourceEndpoint extends AbstractEndpoint<List<Map<String, Object>>> {
//
// public DruidDataSourceEndpoint() {
// super("druid");
// }
//
// private static final DruidStatManagerFacade STAT_MANAGER = DruidStatManagerFacade.getInstance();
//
// @Override
// public List<Map<String, Object>> invoke() {
// return STAT_MANAGER.getDataSourceStatDataList();
// }
//
// }
//
// Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/DruidDataSourceMvcEndpoint.java
// @ConfigurationProperties(prefix = "endpoints.druid")
// public class DruidDataSourceMvcEndpoint extends EndpointMvcAdapter {
//
// private static final DruidStatService statService = DruidStatService.getInstance();
//
// private final long timeout;
// private final Lock lock = new ReentrantLock();
//
// public DruidDataSourceMvcEndpoint(DruidDataSourceEndpoint delegate) {
// super(delegate);
// this.timeout = TimeUnit.SECONDS.toMillis(10);
// }
//
// public DruidDataSourceMvcEndpoint(DruidDataSourceEndpoint delegate, long timeout) {
// super(delegate);
// this.timeout = timeout;
// }
//
// @GetMapping(value = "/{name:.*}", produces = {ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE,
// MediaType.APPLICATION_JSON_VALUE})
// @ResponseBody
// @HypermediaDisabled
// public String handle(@PathVariable String name) {
// String temp = name;
// if (name.contains(".")) {
// temp = name.substring(0, name.indexOf("."));
// }
// name = "/" + temp + ".json";
// return statService.service(name);
// }
//
// }
// Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/autoconfigure/DruidDataSourceEndpointConfiguration.java
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.trang.druid.actuate.DruidDataSourceEndpoint;
import com.github.trang.druid.actuate.DruidDataSourceMvcEndpoint;
package com.github.trang.druid.actuate.autoconfigure;
/**
* Druid Endpoint & Druid MvcEndpoint 自动配置,默认开启
*
* @author trang
*/
@Configuration
@ConditionalOnProperty(prefix = "endpoints.druid", name = "enabled", havingValue = "true", matchIfMissing = true)
public class DruidDataSourceEndpointConfiguration {
@Bean
@ConditionalOnMissingBean | public DruidDataSourceEndpoint druidDataSourceEndpoint() { |
drtrang/druid-spring-boot | druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/autoconfigure/DruidDataSourceEndpointConfiguration.java | // Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/DruidDataSourceEndpoint.java
// @ConfigurationProperties(prefix = "endpoints.druid")
// public class DruidDataSourceEndpoint extends AbstractEndpoint<List<Map<String, Object>>> {
//
// public DruidDataSourceEndpoint() {
// super("druid");
// }
//
// private static final DruidStatManagerFacade STAT_MANAGER = DruidStatManagerFacade.getInstance();
//
// @Override
// public List<Map<String, Object>> invoke() {
// return STAT_MANAGER.getDataSourceStatDataList();
// }
//
// }
//
// Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/DruidDataSourceMvcEndpoint.java
// @ConfigurationProperties(prefix = "endpoints.druid")
// public class DruidDataSourceMvcEndpoint extends EndpointMvcAdapter {
//
// private static final DruidStatService statService = DruidStatService.getInstance();
//
// private final long timeout;
// private final Lock lock = new ReentrantLock();
//
// public DruidDataSourceMvcEndpoint(DruidDataSourceEndpoint delegate) {
// super(delegate);
// this.timeout = TimeUnit.SECONDS.toMillis(10);
// }
//
// public DruidDataSourceMvcEndpoint(DruidDataSourceEndpoint delegate, long timeout) {
// super(delegate);
// this.timeout = timeout;
// }
//
// @GetMapping(value = "/{name:.*}", produces = {ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE,
// MediaType.APPLICATION_JSON_VALUE})
// @ResponseBody
// @HypermediaDisabled
// public String handle(@PathVariable String name) {
// String temp = name;
// if (name.contains(".")) {
// temp = name.substring(0, name.indexOf("."));
// }
// name = "/" + temp + ".json";
// return statService.service(name);
// }
//
// }
| import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.trang.druid.actuate.DruidDataSourceEndpoint;
import com.github.trang.druid.actuate.DruidDataSourceMvcEndpoint; | package com.github.trang.druid.actuate.autoconfigure;
/**
* Druid Endpoint & Druid MvcEndpoint 自动配置,默认开启
*
* @author trang
*/
@Configuration
@ConditionalOnProperty(prefix = "endpoints.druid", name = "enabled", havingValue = "true", matchIfMissing = true)
public class DruidDataSourceEndpointConfiguration {
@Bean
@ConditionalOnMissingBean
public DruidDataSourceEndpoint druidDataSourceEndpoint() {
return new DruidDataSourceEndpoint();
}
@Bean
@ConditionalOnMissingBean | // Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/DruidDataSourceEndpoint.java
// @ConfigurationProperties(prefix = "endpoints.druid")
// public class DruidDataSourceEndpoint extends AbstractEndpoint<List<Map<String, Object>>> {
//
// public DruidDataSourceEndpoint() {
// super("druid");
// }
//
// private static final DruidStatManagerFacade STAT_MANAGER = DruidStatManagerFacade.getInstance();
//
// @Override
// public List<Map<String, Object>> invoke() {
// return STAT_MANAGER.getDataSourceStatDataList();
// }
//
// }
//
// Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/DruidDataSourceMvcEndpoint.java
// @ConfigurationProperties(prefix = "endpoints.druid")
// public class DruidDataSourceMvcEndpoint extends EndpointMvcAdapter {
//
// private static final DruidStatService statService = DruidStatService.getInstance();
//
// private final long timeout;
// private final Lock lock = new ReentrantLock();
//
// public DruidDataSourceMvcEndpoint(DruidDataSourceEndpoint delegate) {
// super(delegate);
// this.timeout = TimeUnit.SECONDS.toMillis(10);
// }
//
// public DruidDataSourceMvcEndpoint(DruidDataSourceEndpoint delegate, long timeout) {
// super(delegate);
// this.timeout = timeout;
// }
//
// @GetMapping(value = "/{name:.*}", produces = {ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE,
// MediaType.APPLICATION_JSON_VALUE})
// @ResponseBody
// @HypermediaDisabled
// public String handle(@PathVariable String name) {
// String temp = name;
// if (name.contains(".")) {
// temp = name.substring(0, name.indexOf("."));
// }
// name = "/" + temp + ".json";
// return statService.service(name);
// }
//
// }
// Path: druid-spring-boot-actuator/druid-spring-boot-actuator-autoconfigure/src/main/java/com/github/trang/druid/actuate/autoconfigure/DruidDataSourceEndpointConfiguration.java
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.trang.druid.actuate.DruidDataSourceEndpoint;
import com.github.trang.druid.actuate.DruidDataSourceMvcEndpoint;
package com.github.trang.druid.actuate.autoconfigure;
/**
* Druid Endpoint & Druid MvcEndpoint 自动配置,默认开启
*
* @author trang
*/
@Configuration
@ConditionalOnProperty(prefix = "endpoints.druid", name = "enabled", havingValue = "true", matchIfMissing = true)
public class DruidDataSourceEndpointConfiguration {
@Bean
@ConditionalOnMissingBean
public DruidDataSourceEndpoint druidDataSourceEndpoint() {
return new DruidDataSourceEndpoint();
}
@Bean
@ConditionalOnMissingBean | public DruidDataSourceMvcEndpoint druidDataSourceMvcEndpoint(DruidDataSourceEndpoint druidDataSourceEndpoint) { |
drtrang/druid-spring-boot | druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/config/SpringDataSourceConfig.java | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/DruidDataSourceCustomizer.java
// public interface DruidDataSourceCustomizer {
//
// /**
// * 自定义 DruidDataSource
// *
// * @param druidDataSource druid 数据源
// */
// void customize(DruidDataSource druidDataSource);
//
// }
| import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.DruidDataSourceCustomizer;
import lombok.extern.slf4j.Slf4j; | package com.github.trang.druid.example.jpa.config;
/**
* 多数据源配置,只在 #{@code spring.profiles.active=dynamic} 时生效
*
* @author trang
*/
@Configuration
@Profile("dynamic")
@Slf4j
public class SpringDataSourceConfig {
/**
* 自定义 DruidDataSource,所有的数据源都会生效
*
* @return druidDataSourceCustomizer
*/
@Bean | // Path: druid-spring-boot/druid-spring-boot-autoconfigure/src/main/java/com/github/trang/druid/autoconfigure/DruidDataSourceCustomizer.java
// public interface DruidDataSourceCustomizer {
//
// /**
// * 自定义 DruidDataSource
// *
// * @param druidDataSource druid 数据源
// */
// void customize(DruidDataSource druidDataSource);
//
// }
// Path: druid-spring-boot-example/druid-spring-boot-jpa-example/src/main/java/com/github/trang/druid/example/jpa/config/SpringDataSourceConfig.java
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.trang.druid.autoconfigure.DruidDataSourceCustomizer;
import lombok.extern.slf4j.Slf4j;
package com.github.trang.druid.example.jpa.config;
/**
* 多数据源配置,只在 #{@code spring.profiles.active=dynamic} 时生效
*
* @author trang
*/
@Configuration
@Profile("dynamic")
@Slf4j
public class SpringDataSourceConfig {
/**
* 自定义 DruidDataSource,所有的数据源都会生效
*
* @return druidDataSourceCustomizer
*/
@Bean | public DruidDataSourceCustomizer druidDataSourceCustomizer() { |
mql4j/mql4j | src/java/mql4j-core/src/main/java/com/mql4j/activemq/ActivemqClient.java | // Path: src/java/mql4j-core/src/main/java/com/mql4j/core/exception/Mql4jException.java
// @SuppressWarnings("serial")
// public class Mql4jException extends Exception {
// public Mql4jException(Throwable cause) {
// super(cause);
// }
//
// public Mql4jException(String msg) {
// super(msg);
// }
// }
| import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mql4j.core.exception.Mql4jException; | package com.mql4j.activemq;
public class ActivemqClient {
private final static Logger log = LoggerFactory.getLogger(ActivemqClient.class);
private Connection connection;
private Session session;
private boolean connected;
private TransactionType transactions;
public ActivemqClient() {
connected = false;
transactions = TransactionType.NO_TRANSACTIONS;
connection = null;
session = null;
}
| // Path: src/java/mql4j-core/src/main/java/com/mql4j/core/exception/Mql4jException.java
// @SuppressWarnings("serial")
// public class Mql4jException extends Exception {
// public Mql4jException(Throwable cause) {
// super(cause);
// }
//
// public Mql4jException(String msg) {
// super(msg);
// }
// }
// Path: src/java/mql4j-core/src/main/java/com/mql4j/activemq/ActivemqClient.java
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mql4j.core.exception.Mql4jException;
package com.mql4j.activemq;
public class ActivemqClient {
private final static Logger log = LoggerFactory.getLogger(ActivemqClient.class);
private Connection connection;
private Session session;
private boolean connected;
private TransactionType transactions;
public ActivemqClient() {
connected = false;
transactions = TransactionType.NO_TRANSACTIONS;
connection = null;
session = null;
}
| public void connect(final String brokerURI) throws Mql4jException, JMSException { |
vector-im/riot-android | vector/src/main/java/im/vector/activity/VectorMediaPickerActivity.java | // Path: vector/src/main/java/im/vector/view/RecentMediaLayout.java
// public class RecentMediaLayout extends RelativeLayout {
//
// private ImageView mThumbnailView;
// private ImageView mTypeView;
// private View mSelectedItemView;
//
// public RecentMediaLayout(Context context) {
// super(context);
// init();
// }
//
// public RecentMediaLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// init();
// }
//
// public RecentMediaLayout(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init();
// }
//
// private void init() {
// inflate(getContext(), R.layout.layout_media_thumbnail, this);
//
// mThumbnailView = findViewById(R.id.media_thumbnail_view);
// mTypeView = findViewById(R.id.media_type_view);
// mSelectedItemView = findViewById(R.id.media_selected_mask_view);
// }
//
// /**
// * @return true when the layout is displayed as selected
// */
// public boolean isSelected() {
// return mSelectedItemView.getVisibility() == View.VISIBLE;
// }
//
// /**
// * Update the layout thumbnail.
// *
// * @param thumbnail the thumbnail
// */
// public void setThumbnail(Bitmap thumbnail) {
// mThumbnailView.setImageBitmap(thumbnail);
// }
//
// public void setThumbnailByUri(Uri aThumbnailUri) {
// mThumbnailView.setImageURI(aThumbnailUri);
// }
//
// public void setThumbnailByResource(int aThumbnailResource) {
// mThumbnailView.setImageResource(aThumbnailResource);
// }
//
// /**
// * Enable the display of the video thumbnail
// *
// * @param isVideo true to display video thumbnail
// */
// public void setVideoType(boolean isVideo) {
// mTypeView.setImageResource(isVideo ? R.drawable.ic_material_movie : R.drawable.ic_material_photo);
// }
//
// /**
// * Enable the display of the gif thumbnail
// *
// * @param isGif true to display gif thumbnail
// */
// public void setGifType(boolean isGif) {
// mTypeView.setImageResource(isGif ? R.drawable.filetype_gif : R.drawable.ic_material_photo);
// }
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaActionSound;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.opengl.GLES20;
import android.os.Build;
import android.os.Bundle;
import android.os.HandlerThread;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
import org.jetbrains.annotations.NotNull;
import org.matrix.androidsdk.core.ImageUtils;
import org.matrix.androidsdk.core.Log;
import org.matrix.androidsdk.core.ResourceUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import im.vector.R;
import im.vector.VectorApp;
import im.vector.listeners.ImageViewOnTouchListener;
import im.vector.ui.themes.ActivityOtherThemes;
import im.vector.ui.themes.ThemeUtils;
import im.vector.util.PermissionsToolsKt;
import im.vector.util.PreferencesManager;
import im.vector.util.ViewUtilKt;
import im.vector.view.RecentMediaLayout;
import im.vector.view.VideoRecordView; |
mMediaStoreMediaList.clear();
// run away from the UI thread
mFileHandler.post(new Runnable() {
@Override
public void run() {
// populate the image thumbnails from multimedia store
final List<MediaStoreMedia> medias = listLatestMedias();
// update the UI part
runOnUiThread(new Runnable() {
@Override
public void run() {
mMediaStoreMediaList.addAll(medias);
buildGalleryTableLayout();
progressBar.setVisibility(View.GONE);
mTakeImageView.setEnabled(true);
mTakeImageView.setAlpha(ViewUtilKt.UTILS_OPACITY_FULL);
}
});
}
});
}
/**
* Build the image gallery widget programmatically.
*/
private void buildGalleryTableLayout() {
TableRow tableRow = null; | // Path: vector/src/main/java/im/vector/view/RecentMediaLayout.java
// public class RecentMediaLayout extends RelativeLayout {
//
// private ImageView mThumbnailView;
// private ImageView mTypeView;
// private View mSelectedItemView;
//
// public RecentMediaLayout(Context context) {
// super(context);
// init();
// }
//
// public RecentMediaLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// init();
// }
//
// public RecentMediaLayout(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init();
// }
//
// private void init() {
// inflate(getContext(), R.layout.layout_media_thumbnail, this);
//
// mThumbnailView = findViewById(R.id.media_thumbnail_view);
// mTypeView = findViewById(R.id.media_type_view);
// mSelectedItemView = findViewById(R.id.media_selected_mask_view);
// }
//
// /**
// * @return true when the layout is displayed as selected
// */
// public boolean isSelected() {
// return mSelectedItemView.getVisibility() == View.VISIBLE;
// }
//
// /**
// * Update the layout thumbnail.
// *
// * @param thumbnail the thumbnail
// */
// public void setThumbnail(Bitmap thumbnail) {
// mThumbnailView.setImageBitmap(thumbnail);
// }
//
// public void setThumbnailByUri(Uri aThumbnailUri) {
// mThumbnailView.setImageURI(aThumbnailUri);
// }
//
// public void setThumbnailByResource(int aThumbnailResource) {
// mThumbnailView.setImageResource(aThumbnailResource);
// }
//
// /**
// * Enable the display of the video thumbnail
// *
// * @param isVideo true to display video thumbnail
// */
// public void setVideoType(boolean isVideo) {
// mTypeView.setImageResource(isVideo ? R.drawable.ic_material_movie : R.drawable.ic_material_photo);
// }
//
// /**
// * Enable the display of the gif thumbnail
// *
// * @param isGif true to display gif thumbnail
// */
// public void setGifType(boolean isGif) {
// mTypeView.setImageResource(isGif ? R.drawable.filetype_gif : R.drawable.ic_material_photo);
// }
// }
// Path: vector/src/main/java/im/vector/activity/VectorMediaPickerActivity.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaActionSound;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.opengl.GLES20;
import android.os.Build;
import android.os.Bundle;
import android.os.HandlerThread;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
import org.jetbrains.annotations.NotNull;
import org.matrix.androidsdk.core.ImageUtils;
import org.matrix.androidsdk.core.Log;
import org.matrix.androidsdk.core.ResourceUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import im.vector.R;
import im.vector.VectorApp;
import im.vector.listeners.ImageViewOnTouchListener;
import im.vector.ui.themes.ActivityOtherThemes;
import im.vector.ui.themes.ThemeUtils;
import im.vector.util.PermissionsToolsKt;
import im.vector.util.PreferencesManager;
import im.vector.util.ViewUtilKt;
import im.vector.view.RecentMediaLayout;
import im.vector.view.VideoRecordView;
mMediaStoreMediaList.clear();
// run away from the UI thread
mFileHandler.post(new Runnable() {
@Override
public void run() {
// populate the image thumbnails from multimedia store
final List<MediaStoreMedia> medias = listLatestMedias();
// update the UI part
runOnUiThread(new Runnable() {
@Override
public void run() {
mMediaStoreMediaList.addAll(medias);
buildGalleryTableLayout();
progressBar.setVisibility(View.GONE);
mTakeImageView.setEnabled(true);
mTakeImageView.setAlpha(ViewUtilKt.UTILS_OPACITY_FULL);
}
});
}
});
}
/**
* Build the image gallery widget programmatically.
*/
private void buildGalleryTableLayout() {
TableRow tableRow = null; | RecentMediaLayout recentMediaView; |
vector-im/riot-android | vector/src/main/java/im/vector/push/PushManager.java | // Path: vector/src/app/java/im/vector/push/fcm/FcmHelper.java
// public class FcmHelper {
// private static final String LOG_TAG = FcmHelper.class.getSimpleName();
//
// private static final String PREFS_KEY_FCM_TOKEN = "FCM_TOKEN";
//
// /**
// * Retrieves the FCM registration token.
// *
// * @return the FCM token or null if not received from FCM
// */
// @Nullable
// public static String getFcmToken(Context context) {
// return PreferenceManager.getDefaultSharedPreferences(context).getString(PREFS_KEY_FCM_TOKEN, null);
// }
//
// /**
// * Store FCM token to the SharedPrefs
// *
// * @param context android context
// * @param token the token to store
// */
// public static void storeFcmToken(@NonNull Context context,
// @Nullable String token) {
// PreferenceManager.getDefaultSharedPreferences(context)
// .edit()
// .putString(PREFS_KEY_FCM_TOKEN, token)
// .apply();
// }
//
// /**
// * onNewToken may not be called on application upgrade, so ensure my shared pref is set
// *
// * @param activity the first launch Activity
// */
// public static void ensureFcmTokenIsRetrieved(final Activity activity) {
// if (TextUtils.isEmpty(getFcmToken(activity))) {
//
//
// //vfe: according to firebase doc
// //'app should always check the device for a compatible Google Play services APK before accessing Google Play services features'
// if (checkPlayServices(activity)) {
// try {
// FirebaseInstanceId.getInstance().getInstanceId()
// .addOnSuccessListener(activity, new OnSuccessListener<InstanceIdResult>() {
// @Override
// public void onSuccess(InstanceIdResult instanceIdResult) {
// storeFcmToken(activity, instanceIdResult.getToken());
// }
// })
// .addOnFailureListener(activity, new OnFailureListener() {
// @Override
// public void onFailure(@NonNull Exception e) {
// Log.e(LOG_TAG, "## ensureFcmTokenIsRetrieved() : failed " + e.getMessage(), e);
// }
// });
// } catch (Throwable e) {
// Log.e(LOG_TAG, "## ensureFcmTokenIsRetrieved() : failed " + e.getMessage(), e);
// }
// } else {
// Toast.makeText(activity, R.string.no_valid_google_play_services_apk, Toast.LENGTH_SHORT).show();
// Log.e(LOG_TAG, "No valid Google Play Services found. Cannot use FCM.");
// }
// }
// }
//
// /**
// * Check the device to make sure it has the Google Play Services APK. If
// * it doesn't, display a dialog that allows users to download the APK from
// * the Google Play Store or enable it in the device's system settings.
// */
// private static boolean checkPlayServices(Activity activity) {
// GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
// int resultCode = apiAvailability.isGooglePlayServicesAvailable(activity);
// if (resultCode != ConnectionResult.SUCCESS) {
// return false;
// }
// return true;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.core.Log;
import org.matrix.androidsdk.core.callback.ApiCallback;
import org.matrix.androidsdk.core.callback.SimpleApiCallback;
import org.matrix.androidsdk.core.listeners.IMXNetworkEventListener;
import org.matrix.androidsdk.core.model.MatrixError;
import org.matrix.androidsdk.data.Pusher;
import org.matrix.androidsdk.rest.model.PushersResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import im.vector.BuildConfig;
import im.vector.Matrix;
import im.vector.push.fcm.FcmHelper;
import im.vector.services.EventStreamServiceX;
import im.vector.util.PreferencesManager; | }
Matrix.getInstance(appContext).addNetworkEventListener(new IMXNetworkEventListener() {
@Override
public void onNetworkConnectionUpdate(boolean isConnected) {
if (isConnected) {
// test if the server registration / unregistration should be done
if (useFcm()) {
// test if the user expect having notifications on his device but it was not yet done
if (areDeviceNotificationsAllowed() && (mRegistrationState == RegistrationState.FCM_REGISTERED)) {
register(null);
} else if (!areDeviceNotificationsAllowed() && (mRegistrationState == RegistrationState.SERVER_REGISTERED)) {
unregister(null);
}
}
}
}
});
mRegistrationState = getStoredRegistrationState();
mRegistrationToken = getStoredRegistrationToken();
}
public void deepCheckRegistration(Context context) {
if (isFcmRegistered()) {
//Issue #2266 It might be possible that the FCMHelper saved token is different
//than the push manager saved token, and that the pushManager is not aware.
//And as per current code the pushMgr saved token is sent at each startup (resume?)
//So anyway, might be a good thing to check that it is synced?
//Very defensive code but, ya know :/ | // Path: vector/src/app/java/im/vector/push/fcm/FcmHelper.java
// public class FcmHelper {
// private static final String LOG_TAG = FcmHelper.class.getSimpleName();
//
// private static final String PREFS_KEY_FCM_TOKEN = "FCM_TOKEN";
//
// /**
// * Retrieves the FCM registration token.
// *
// * @return the FCM token or null if not received from FCM
// */
// @Nullable
// public static String getFcmToken(Context context) {
// return PreferenceManager.getDefaultSharedPreferences(context).getString(PREFS_KEY_FCM_TOKEN, null);
// }
//
// /**
// * Store FCM token to the SharedPrefs
// *
// * @param context android context
// * @param token the token to store
// */
// public static void storeFcmToken(@NonNull Context context,
// @Nullable String token) {
// PreferenceManager.getDefaultSharedPreferences(context)
// .edit()
// .putString(PREFS_KEY_FCM_TOKEN, token)
// .apply();
// }
//
// /**
// * onNewToken may not be called on application upgrade, so ensure my shared pref is set
// *
// * @param activity the first launch Activity
// */
// public static void ensureFcmTokenIsRetrieved(final Activity activity) {
// if (TextUtils.isEmpty(getFcmToken(activity))) {
//
//
// //vfe: according to firebase doc
// //'app should always check the device for a compatible Google Play services APK before accessing Google Play services features'
// if (checkPlayServices(activity)) {
// try {
// FirebaseInstanceId.getInstance().getInstanceId()
// .addOnSuccessListener(activity, new OnSuccessListener<InstanceIdResult>() {
// @Override
// public void onSuccess(InstanceIdResult instanceIdResult) {
// storeFcmToken(activity, instanceIdResult.getToken());
// }
// })
// .addOnFailureListener(activity, new OnFailureListener() {
// @Override
// public void onFailure(@NonNull Exception e) {
// Log.e(LOG_TAG, "## ensureFcmTokenIsRetrieved() : failed " + e.getMessage(), e);
// }
// });
// } catch (Throwable e) {
// Log.e(LOG_TAG, "## ensureFcmTokenIsRetrieved() : failed " + e.getMessage(), e);
// }
// } else {
// Toast.makeText(activity, R.string.no_valid_google_play_services_apk, Toast.LENGTH_SHORT).show();
// Log.e(LOG_TAG, "No valid Google Play Services found. Cannot use FCM.");
// }
// }
// }
//
// /**
// * Check the device to make sure it has the Google Play Services APK. If
// * it doesn't, display a dialog that allows users to download the APK from
// * the Google Play Store or enable it in the device's system settings.
// */
// private static boolean checkPlayServices(Activity activity) {
// GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
// int resultCode = apiAvailability.isGooglePlayServicesAvailable(activity);
// if (resultCode != ConnectionResult.SUCCESS) {
// return false;
// }
// return true;
// }
// }
// Path: vector/src/main/java/im/vector/push/PushManager.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.core.Log;
import org.matrix.androidsdk.core.callback.ApiCallback;
import org.matrix.androidsdk.core.callback.SimpleApiCallback;
import org.matrix.androidsdk.core.listeners.IMXNetworkEventListener;
import org.matrix.androidsdk.core.model.MatrixError;
import org.matrix.androidsdk.data.Pusher;
import org.matrix.androidsdk.rest.model.PushersResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import im.vector.BuildConfig;
import im.vector.Matrix;
import im.vector.push.fcm.FcmHelper;
import im.vector.services.EventStreamServiceX;
import im.vector.util.PreferencesManager;
}
Matrix.getInstance(appContext).addNetworkEventListener(new IMXNetworkEventListener() {
@Override
public void onNetworkConnectionUpdate(boolean isConnected) {
if (isConnected) {
// test if the server registration / unregistration should be done
if (useFcm()) {
// test if the user expect having notifications on his device but it was not yet done
if (areDeviceNotificationsAllowed() && (mRegistrationState == RegistrationState.FCM_REGISTERED)) {
register(null);
} else if (!areDeviceNotificationsAllowed() && (mRegistrationState == RegistrationState.SERVER_REGISTERED)) {
unregister(null);
}
}
}
}
});
mRegistrationState = getStoredRegistrationState();
mRegistrationToken = getStoredRegistrationToken();
}
public void deepCheckRegistration(Context context) {
if (isFcmRegistered()) {
//Issue #2266 It might be possible that the FCMHelper saved token is different
//than the push manager saved token, and that the pushManager is not aware.
//And as per current code the pushMgr saved token is sent at each startup (resume?)
//So anyway, might be a good thing to check that it is synced?
//Very defensive code but, ya know :/ | String fcmToken = FcmHelper.getFcmToken(context); |
vector-im/riot-android | vector/src/main/java/im/vector/adapters/RoomDirectoryAdapter.java | // Path: vector/src/main/java/im/vector/util/RoomDirectoryData.java
// public class RoomDirectoryData implements Serializable {
//
// private static final String DEFAULT_HOME_SERVER_NAME = "Matrix";
//
// /**
// * The display name (the server description)
// */
// private final String mDisplayName;
//
// /**
// * The server name (might be null)
// */
// private final String mHomeServer;
//
// /**
// * The third party server identifier
// */
// private final String mThirdPartyInstanceId;
//
//
// /**
// * Tell if all the federated servers must be included
// */
// private final boolean mIncludeAllNetworks;
//
// /**
// * the avatar url
// */
// private final String mAvatarUrl;
//
// /**
// * Creator
// *
// * @param server the home server (optional). Set null when the server is the current user's home server.
// * @param serverDisplayName the home server displayname
// * @return a new instance
// */
// public static RoomDirectoryData createIncludingAllNetworks(String server, String serverDisplayName) {
// return new RoomDirectoryData(server, serverDisplayName, null, null, true);
// }
//
// /**
// * Provides the default value
// *
// * @return the default value
// */
// public static RoomDirectoryData getDefault() {
// return new RoomDirectoryData(null, DEFAULT_HOME_SERVER_NAME, null, null, false);
// }
//
// /**
// * Constructor
// *
// * @param homeServer the server (might be null)
// * @param displayName the displayName
// * @param avatarUrl the avatar URL (might be null)
// * @param thirdPartyInstanceId the third party instance id (might be null)
// * @param includeAllNetworks true to tell
// */
// public RoomDirectoryData(String homeServer, String displayName, String avatarUrl, String thirdPartyInstanceId, boolean includeAllNetworks) {
// mHomeServer = homeServer;
// mDisplayName = displayName;
// mAvatarUrl = avatarUrl;
// mThirdPartyInstanceId = thirdPartyInstanceId;
// mIncludeAllNetworks = includeAllNetworks;
// }
//
// public String getHomeServer() {
// return mHomeServer;
// }
//
// public String getDisplayName() {
// return mDisplayName;
// }
//
// public String getAvatarUrl() {
// return mAvatarUrl;
// }
//
// public String getThirdPartyInstanceId() {
// return mThirdPartyInstanceId;
// }
//
// public boolean isIncludedAllNetworks() {
// return mIncludeAllNetworks;
// }
// }
| import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import org.matrix.androidsdk.core.Log;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import im.vector.R;
import im.vector.util.RoomDirectoryData; | /*
* Copyright 2017 Vector Creations Ltd
* Copyright 2018 New Vector Ltd
*
* 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 im.vector.adapters;
public class RoomDirectoryAdapter extends RecyclerView.Adapter<RoomDirectoryAdapter.RoomDirectoryViewHolder> {
private static final String LOG_TAG = RoomDirectoryAdapter.class.getSimpleName();
| // Path: vector/src/main/java/im/vector/util/RoomDirectoryData.java
// public class RoomDirectoryData implements Serializable {
//
// private static final String DEFAULT_HOME_SERVER_NAME = "Matrix";
//
// /**
// * The display name (the server description)
// */
// private final String mDisplayName;
//
// /**
// * The server name (might be null)
// */
// private final String mHomeServer;
//
// /**
// * The third party server identifier
// */
// private final String mThirdPartyInstanceId;
//
//
// /**
// * Tell if all the federated servers must be included
// */
// private final boolean mIncludeAllNetworks;
//
// /**
// * the avatar url
// */
// private final String mAvatarUrl;
//
// /**
// * Creator
// *
// * @param server the home server (optional). Set null when the server is the current user's home server.
// * @param serverDisplayName the home server displayname
// * @return a new instance
// */
// public static RoomDirectoryData createIncludingAllNetworks(String server, String serverDisplayName) {
// return new RoomDirectoryData(server, serverDisplayName, null, null, true);
// }
//
// /**
// * Provides the default value
// *
// * @return the default value
// */
// public static RoomDirectoryData getDefault() {
// return new RoomDirectoryData(null, DEFAULT_HOME_SERVER_NAME, null, null, false);
// }
//
// /**
// * Constructor
// *
// * @param homeServer the server (might be null)
// * @param displayName the displayName
// * @param avatarUrl the avatar URL (might be null)
// * @param thirdPartyInstanceId the third party instance id (might be null)
// * @param includeAllNetworks true to tell
// */
// public RoomDirectoryData(String homeServer, String displayName, String avatarUrl, String thirdPartyInstanceId, boolean includeAllNetworks) {
// mHomeServer = homeServer;
// mDisplayName = displayName;
// mAvatarUrl = avatarUrl;
// mThirdPartyInstanceId = thirdPartyInstanceId;
// mIncludeAllNetworks = includeAllNetworks;
// }
//
// public String getHomeServer() {
// return mHomeServer;
// }
//
// public String getDisplayName() {
// return mDisplayName;
// }
//
// public String getAvatarUrl() {
// return mAvatarUrl;
// }
//
// public String getThirdPartyInstanceId() {
// return mThirdPartyInstanceId;
// }
//
// public boolean isIncludedAllNetworks() {
// return mIncludeAllNetworks;
// }
// }
// Path: vector/src/main/java/im/vector/adapters/RoomDirectoryAdapter.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import org.matrix.androidsdk.core.Log;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import im.vector.R;
import im.vector.util.RoomDirectoryData;
/*
* Copyright 2017 Vector Creations Ltd
* Copyright 2018 New Vector Ltd
*
* 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 im.vector.adapters;
public class RoomDirectoryAdapter extends RecyclerView.Adapter<RoomDirectoryAdapter.RoomDirectoryViewHolder> {
private static final String LOG_TAG = RoomDirectoryAdapter.class.getSimpleName();
| private final List<RoomDirectoryData> mList; |
vector-im/riot-android | vector/src/main/java/im/vector/adapters/VectorRoomSummaryAdapter.java | // Path: vector/src/main/java/im/vector/util/RiotEventDisplay.java
// public class RiotEventDisplay extends EventDisplay {
// private static final String LOG_TAG = RiotEventDisplay.class.getSimpleName();
//
// private static final Map<String, Event> mClosingWidgetEventByStateKey = new HashMap<>();
//
// // constructor
// public RiotEventDisplay(Context context, HtmlToolbox htmlToolbox) {
// super(context, htmlToolbox);
// }
//
// // constructor
// public RiotEventDisplay(Context context) {
// super(context);
// }
//
// /**
// * Stringify the linked event.
// *
// * @param displayNameColor the display name highlighted color.
// * @return The text or null if it isn't possible.
// */
// @Override
// public CharSequence getTextualDisplay(Integer displayNameColor, Event event, RoomState roomState) {
// CharSequence text = null;
//
// try {
// if (TextUtils.equals(event.getType(), WidgetsManager.WIDGET_EVENT_TYPE)) {
// JsonObject content = event.getContentAsJsonObject();
//
// EventContent eventContent = JsonUtils.toEventContent(event.getContentAsJsonObject());
// EventContent prevEventContent = event.getPrevContent();
// String senderDisplayName = senderDisplayNameForEvent(event, eventContent, prevEventContent, roomState);
//
// if (0 == content.entrySet().size()) {
// Event closingWidgetEvent = mClosingWidgetEventByStateKey.get(event.stateKey);
//
// if (null == closingWidgetEvent) {
// List<Event> widgetEvents = roomState.getStateEvents(new HashSet<>(Arrays.asList(WidgetsManager.WIDGET_EVENT_TYPE)));
//
// for (Event widgetEvent : widgetEvents) {
// if (TextUtils.equals(widgetEvent.stateKey, event.stateKey) && !widgetEvent.getContentAsJsonObject().entrySet().isEmpty()) {
// closingWidgetEvent = widgetEvent;
// break;
// }
// }
//
// if (null != closingWidgetEvent) {
// mClosingWidgetEventByStateKey.put(event.stateKey, closingWidgetEvent);
// }
// }
//
// String type = (null != closingWidgetEvent) ?
// WidgetContent.toWidgetContent(closingWidgetEvent.getContentAsJsonObject()).getHumanName() : "undefined";
// text = mContext.getString(R.string.event_formatter_widget_removed, type, senderDisplayName);
// } else {
// String type = WidgetContent.toWidgetContent(event.getContentAsJsonObject()).getHumanName();
// text = mContext.getString(R.string.event_formatter_widget_added, type, senderDisplayName);
// }
// } else {
// text = super.getTextualDisplay(displayNameColor, event, roomState);
// }
// if (event.getCryptoError() != null) {
// final MXSession session = Matrix.getInstance(mContext).getDefaultSession();
// VectorApp.getInstance()
// .getDecryptionFailureTracker()
// .reportUnableToDecryptError(event, roomState, session.getMyUserId());
// }
//
// } catch (Exception e) {
// Log.e(LOG_TAG, "getTextualDisplay() " + e.getMessage(), e);
// }
//
// return text;
// }
// }
| import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import org.matrix.androidsdk.MXDataHandler;
import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.core.EventDisplay;
import org.matrix.androidsdk.core.Log;
import org.matrix.androidsdk.data.Room;
import org.matrix.androidsdk.data.RoomState;
import org.matrix.androidsdk.data.RoomSummary;
import org.matrix.androidsdk.data.RoomTag;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.androidsdk.rest.model.User;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import im.vector.Matrix;
import im.vector.PublicRoomsManager;
import im.vector.R;
import im.vector.settings.VectorLocale;
import im.vector.ui.themes.ThemeUtils;
import im.vector.util.RiotEventDisplay;
import im.vector.util.RoomUtils;
import im.vector.util.VectorUtils;
import im.vector.util.ViewUtilKt; |
if ((null == aMatrixId) || (null == aUserId)) {
displayNameRetValue = null;
} else if ((null == (session = Matrix.getMXSession(mContext, aMatrixId))) || (!session.isAlive())) {
displayNameRetValue = null;
} else {
User user = session.getDataHandler().getStore().getUser(aUserId);
if ((null != user) && !TextUtils.isEmpty(user.displayname)) {
displayNameRetValue = user.displayname;
} else {
displayNameRetValue = aUserId;
}
}
return displayNameRetValue;
}
/**
* Retrieves the text to display for a RoomSummary.
*
* @param aChildRoomSummary the roomSummary.
* @return the text to display.
*/
private CharSequence getChildMessageToDisplay(RoomSummary aChildRoomSummary) {
CharSequence messageToDisplayRetValue = null;
EventDisplay eventDisplay;
if (null != aChildRoomSummary) {
if (aChildRoomSummary.getLatestReceivedEvent() != null) { | // Path: vector/src/main/java/im/vector/util/RiotEventDisplay.java
// public class RiotEventDisplay extends EventDisplay {
// private static final String LOG_TAG = RiotEventDisplay.class.getSimpleName();
//
// private static final Map<String, Event> mClosingWidgetEventByStateKey = new HashMap<>();
//
// // constructor
// public RiotEventDisplay(Context context, HtmlToolbox htmlToolbox) {
// super(context, htmlToolbox);
// }
//
// // constructor
// public RiotEventDisplay(Context context) {
// super(context);
// }
//
// /**
// * Stringify the linked event.
// *
// * @param displayNameColor the display name highlighted color.
// * @return The text or null if it isn't possible.
// */
// @Override
// public CharSequence getTextualDisplay(Integer displayNameColor, Event event, RoomState roomState) {
// CharSequence text = null;
//
// try {
// if (TextUtils.equals(event.getType(), WidgetsManager.WIDGET_EVENT_TYPE)) {
// JsonObject content = event.getContentAsJsonObject();
//
// EventContent eventContent = JsonUtils.toEventContent(event.getContentAsJsonObject());
// EventContent prevEventContent = event.getPrevContent();
// String senderDisplayName = senderDisplayNameForEvent(event, eventContent, prevEventContent, roomState);
//
// if (0 == content.entrySet().size()) {
// Event closingWidgetEvent = mClosingWidgetEventByStateKey.get(event.stateKey);
//
// if (null == closingWidgetEvent) {
// List<Event> widgetEvents = roomState.getStateEvents(new HashSet<>(Arrays.asList(WidgetsManager.WIDGET_EVENT_TYPE)));
//
// for (Event widgetEvent : widgetEvents) {
// if (TextUtils.equals(widgetEvent.stateKey, event.stateKey) && !widgetEvent.getContentAsJsonObject().entrySet().isEmpty()) {
// closingWidgetEvent = widgetEvent;
// break;
// }
// }
//
// if (null != closingWidgetEvent) {
// mClosingWidgetEventByStateKey.put(event.stateKey, closingWidgetEvent);
// }
// }
//
// String type = (null != closingWidgetEvent) ?
// WidgetContent.toWidgetContent(closingWidgetEvent.getContentAsJsonObject()).getHumanName() : "undefined";
// text = mContext.getString(R.string.event_formatter_widget_removed, type, senderDisplayName);
// } else {
// String type = WidgetContent.toWidgetContent(event.getContentAsJsonObject()).getHumanName();
// text = mContext.getString(R.string.event_formatter_widget_added, type, senderDisplayName);
// }
// } else {
// text = super.getTextualDisplay(displayNameColor, event, roomState);
// }
// if (event.getCryptoError() != null) {
// final MXSession session = Matrix.getInstance(mContext).getDefaultSession();
// VectorApp.getInstance()
// .getDecryptionFailureTracker()
// .reportUnableToDecryptError(event, roomState, session.getMyUserId());
// }
//
// } catch (Exception e) {
// Log.e(LOG_TAG, "getTextualDisplay() " + e.getMessage(), e);
// }
//
// return text;
// }
// }
// Path: vector/src/main/java/im/vector/adapters/VectorRoomSummaryAdapter.java
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import org.matrix.androidsdk.MXDataHandler;
import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.core.EventDisplay;
import org.matrix.androidsdk.core.Log;
import org.matrix.androidsdk.data.Room;
import org.matrix.androidsdk.data.RoomState;
import org.matrix.androidsdk.data.RoomSummary;
import org.matrix.androidsdk.data.RoomTag;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.androidsdk.rest.model.User;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import im.vector.Matrix;
import im.vector.PublicRoomsManager;
import im.vector.R;
import im.vector.settings.VectorLocale;
import im.vector.ui.themes.ThemeUtils;
import im.vector.util.RiotEventDisplay;
import im.vector.util.RoomUtils;
import im.vector.util.VectorUtils;
import im.vector.util.ViewUtilKt;
if ((null == aMatrixId) || (null == aUserId)) {
displayNameRetValue = null;
} else if ((null == (session = Matrix.getMXSession(mContext, aMatrixId))) || (!session.isAlive())) {
displayNameRetValue = null;
} else {
User user = session.getDataHandler().getStore().getUser(aUserId);
if ((null != user) && !TextUtils.isEmpty(user.displayname)) {
displayNameRetValue = user.displayname;
} else {
displayNameRetValue = aUserId;
}
}
return displayNameRetValue;
}
/**
* Retrieves the text to display for a RoomSummary.
*
* @param aChildRoomSummary the roomSummary.
* @return the text to display.
*/
private CharSequence getChildMessageToDisplay(RoomSummary aChildRoomSummary) {
CharSequence messageToDisplayRetValue = null;
EventDisplay eventDisplay;
if (null != aChildRoomSummary) {
if (aChildRoomSummary.getLatestReceivedEvent() != null) { | eventDisplay = new RiotEventDisplay(mContext); |
vector-im/riot-android | vector/src/main/java/im/vector/fragments/ImageSizeSelectionDialogFragment.java | // Path: vector/src/main/java/im/vector/adapters/ImageSizesAdapter.java
// public class ImageSizesAdapter extends ArrayAdapter<ImageCompressionDescription> {
// private final Context mContext;
// private final LayoutInflater mLayoutInflater;
// private final int mLayoutResourceId;
//
// /**
// * Construct an adapter which will display a list of image size
// *
// * @param context Activity context
// * @param layoutResourceId The resource ID of the layout for each item.
// */
// public ImageSizesAdapter(Context context, int layoutResourceId) {
// super(context, layoutResourceId);
// mContext = context;
// mLayoutResourceId = layoutResourceId;
// mLayoutInflater = LayoutInflater.from(mContext);
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
// convertView = mLayoutInflater.inflate(mLayoutResourceId, parent, false);
// }
//
// ImageCompressionDescription imageSizesDescription = getItem(position);
//
// TextView textView = convertView.findViewById(R.id.ImageSizesAdapter_format);
// textView.setText(imageSizesDescription.mCompressionText);
//
// textView = convertView.findViewById(R.id.ImageSizesAdapter_info);
// textView.setText(imageSizesDescription.mCompressionInfoText);
// return convertView;
// }
// }
| import im.vector.R;
import im.vector.adapters.ImageCompressionDescription;
import im.vector.adapters.ImageSizesAdapter;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import androidx.fragment.app.DialogFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; | @Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
if (null != mEntries) {
savedInstanceState.putSerializable(SELECTIONS_LIST, (ArrayList) mEntries);
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog d = super.onCreateDialog(savedInstanceState);
if (null != savedInstanceState) {
if (savedInstanceState.containsKey(SELECTIONS_LIST)) {
mEntries = (ArrayList<ImageCompressionDescription>) savedInstanceState.getSerializable(SELECTIONS_LIST);
}
}
d.setTitle(getString(R.string.compression_options));
return d;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.dialog_base_list_view, container, false);
ListView listView = v.findViewById(R.id.list_view);
| // Path: vector/src/main/java/im/vector/adapters/ImageSizesAdapter.java
// public class ImageSizesAdapter extends ArrayAdapter<ImageCompressionDescription> {
// private final Context mContext;
// private final LayoutInflater mLayoutInflater;
// private final int mLayoutResourceId;
//
// /**
// * Construct an adapter which will display a list of image size
// *
// * @param context Activity context
// * @param layoutResourceId The resource ID of the layout for each item.
// */
// public ImageSizesAdapter(Context context, int layoutResourceId) {
// super(context, layoutResourceId);
// mContext = context;
// mLayoutResourceId = layoutResourceId;
// mLayoutInflater = LayoutInflater.from(mContext);
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
// convertView = mLayoutInflater.inflate(mLayoutResourceId, parent, false);
// }
//
// ImageCompressionDescription imageSizesDescription = getItem(position);
//
// TextView textView = convertView.findViewById(R.id.ImageSizesAdapter_format);
// textView.setText(imageSizesDescription.mCompressionText);
//
// textView = convertView.findViewById(R.id.ImageSizesAdapter_info);
// textView.setText(imageSizesDescription.mCompressionInfoText);
// return convertView;
// }
// }
// Path: vector/src/main/java/im/vector/fragments/ImageSizeSelectionDialogFragment.java
import im.vector.R;
import im.vector.adapters.ImageCompressionDescription;
import im.vector.adapters.ImageSizesAdapter;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import androidx.fragment.app.DialogFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
if (null != mEntries) {
savedInstanceState.putSerializable(SELECTIONS_LIST, (ArrayList) mEntries);
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog d = super.onCreateDialog(savedInstanceState);
if (null != savedInstanceState) {
if (savedInstanceState.containsKey(SELECTIONS_LIST)) {
mEntries = (ArrayList<ImageCompressionDescription>) savedInstanceState.getSerializable(SELECTIONS_LIST);
}
}
d.setTitle(getString(R.string.compression_options));
return d;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.dialog_base_list_view, container, false);
ListView listView = v.findViewById(R.id.list_view);
| ImageSizesAdapter adapter = new ImageSizesAdapter(getActivity(), R.layout.adapter_item_image_size); |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/receiver/CommandReceiver.java | // Path: app/src/main/java/wseemann/media/romote/tasks/RequestCallback.java
// public abstract class RequestCallback {
// public abstract void requestResult(RokuRequestTypes rokuRequestType, RequestTask.Result result);
// public abstract void onErrorResponse(RequestTask.Result result);
// }
//
// Path: app/src/main/java/wseemann/media/romote/tasks/RequestTask.java
// public class RequestTask extends AsyncTask<RokuRequestTypes, Void, RequestTask.Result> {
//
// private RequestCallback mCallback;
//
// private JakuRequest request;
// private RokuRequestTypes rokuRequestType;
//
// public RequestTask(JakuRequest request, RequestCallback callback) {
// this.request = request;
// setCallback(callback);
// }
//
// void setCallback(RequestCallback callback) {
// mCallback = callback;
// }
//
// /**
// * Wrapper class that serves as a union of a result value and an exception. When the download
// * task has completed, either the result value or exception can be a non-null value.
// * This allows you to pass exceptions to the UI thread that were thrown during doInBackground().
// */
// public static class Result {
// public Object mResultValue;
// public Exception mException;
// public Result(Object resultValue) {
// mResultValue = resultValue;
// }
// public Result(Exception exception) {
// mException = exception;
// }
// }
//
// /**
// * Cancel background network operation if we do not have network connectivity.
// */
// @Override
// protected void onPreExecute() {
//
// }
//
// @Override
// protected RequestTask.Result doInBackground(RokuRequestTypes... requestTypes) {
// Result result = null;
// if (!isCancelled() && requestTypes != null && requestTypes.length > 0) {
// RokuRequestTypes requestType = requestTypes[0];
// try {
// if (requestType.equals(RokuRequestTypes.query_active_app)) {
// JakuResponse response = request.send();
// List<Channel> channels = (List<Channel>) response.getResponseData();
// result = new Result(channels);
// } else if (requestType.equals(RokuRequestTypes.query_device_info)) {
// JakuResponse response = request.send();
// Device device = Device.Companion.fromDevice((com.jaku.model.Device) response.getResponseData());
// result = new Result(device);
// } else if (requestType.equals(RokuRequestTypes.query_icon)) {
// JakuResponse response = request.send();
// byte [] data = ((ByteArrayOutputStream) response.getResponseData()).toByteArray();
// result = new Result(data);
// } else {
// request.send();
// }
// } catch(Exception e) {
// e.printStackTrace();
// result = new Result(e);
// }
// }
// return result;
// }
//
// /**
// * Updates the DownloadCallback with the result.
// */
// @Override
// protected void onPostExecute(Result result) {
// if (result != null && mCallback != null) {
// if (result.mException != null) {
// mCallback.onErrorResponse(result);
// } else if (result.mResultValue != null) {
// mCallback.requestResult(rokuRequestType, result);
// }
// }
// }
//
// /**
// * Override to add special behavior for cancelled AsyncTask.
// */
// @Override
// protected void onCancelled(Result result) {
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/CommandHelper.java
// public class CommandHelper {
//
// private CommandHelper() {
//
// }
//
// public static String getDeviceURL(Context context) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getIconURL(Context context, String channelId) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost() + "/query/icon/" + channelId;
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getDeviceInfoURL(Context context, String host) {
// String url = host;
//
// return url;
// }
//
// public static String getConnectedDeviceInfoURL(Context context, String host) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/RokuRequestTypes.java
// public enum RokuRequestTypes {
// query_active_app("query/active-app"),
// query_device_info("query/device-info"),
// launch("launch"),
// keypress("keypress"),
// query_icon("query/icon"),
// search("search/browse?");
//
// private final String method;
//
// RokuRequestTypes(String method) {
// this.method = method;
// }
//
// public String getValue() {
// return method;
// }
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import com.jaku.core.JakuRequest;
import com.jaku.core.KeypressKeyValues;
import com.jaku.request.KeypressRequest;
import wseemann.media.romote.tasks.RequestCallback;
import wseemann.media.romote.tasks.RequestTask;
import wseemann.media.romote.utils.CommandHelper;
import wseemann.media.romote.utils.RokuRequestTypes; | package wseemann.media.romote.receiver;
/**
* Created by wseemann on 4/14/18.
*/
public class CommandReceiver extends BroadcastReceiver {
private static final String TAG = CommandReceiver.class.getName();
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) { | // Path: app/src/main/java/wseemann/media/romote/tasks/RequestCallback.java
// public abstract class RequestCallback {
// public abstract void requestResult(RokuRequestTypes rokuRequestType, RequestTask.Result result);
// public abstract void onErrorResponse(RequestTask.Result result);
// }
//
// Path: app/src/main/java/wseemann/media/romote/tasks/RequestTask.java
// public class RequestTask extends AsyncTask<RokuRequestTypes, Void, RequestTask.Result> {
//
// private RequestCallback mCallback;
//
// private JakuRequest request;
// private RokuRequestTypes rokuRequestType;
//
// public RequestTask(JakuRequest request, RequestCallback callback) {
// this.request = request;
// setCallback(callback);
// }
//
// void setCallback(RequestCallback callback) {
// mCallback = callback;
// }
//
// /**
// * Wrapper class that serves as a union of a result value and an exception. When the download
// * task has completed, either the result value or exception can be a non-null value.
// * This allows you to pass exceptions to the UI thread that were thrown during doInBackground().
// */
// public static class Result {
// public Object mResultValue;
// public Exception mException;
// public Result(Object resultValue) {
// mResultValue = resultValue;
// }
// public Result(Exception exception) {
// mException = exception;
// }
// }
//
// /**
// * Cancel background network operation if we do not have network connectivity.
// */
// @Override
// protected void onPreExecute() {
//
// }
//
// @Override
// protected RequestTask.Result doInBackground(RokuRequestTypes... requestTypes) {
// Result result = null;
// if (!isCancelled() && requestTypes != null && requestTypes.length > 0) {
// RokuRequestTypes requestType = requestTypes[0];
// try {
// if (requestType.equals(RokuRequestTypes.query_active_app)) {
// JakuResponse response = request.send();
// List<Channel> channels = (List<Channel>) response.getResponseData();
// result = new Result(channels);
// } else if (requestType.equals(RokuRequestTypes.query_device_info)) {
// JakuResponse response = request.send();
// Device device = Device.Companion.fromDevice((com.jaku.model.Device) response.getResponseData());
// result = new Result(device);
// } else if (requestType.equals(RokuRequestTypes.query_icon)) {
// JakuResponse response = request.send();
// byte [] data = ((ByteArrayOutputStream) response.getResponseData()).toByteArray();
// result = new Result(data);
// } else {
// request.send();
// }
// } catch(Exception e) {
// e.printStackTrace();
// result = new Result(e);
// }
// }
// return result;
// }
//
// /**
// * Updates the DownloadCallback with the result.
// */
// @Override
// protected void onPostExecute(Result result) {
// if (result != null && mCallback != null) {
// if (result.mException != null) {
// mCallback.onErrorResponse(result);
// } else if (result.mResultValue != null) {
// mCallback.requestResult(rokuRequestType, result);
// }
// }
// }
//
// /**
// * Override to add special behavior for cancelled AsyncTask.
// */
// @Override
// protected void onCancelled(Result result) {
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/CommandHelper.java
// public class CommandHelper {
//
// private CommandHelper() {
//
// }
//
// public static String getDeviceURL(Context context) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getIconURL(Context context, String channelId) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost() + "/query/icon/" + channelId;
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getDeviceInfoURL(Context context, String host) {
// String url = host;
//
// return url;
// }
//
// public static String getConnectedDeviceInfoURL(Context context, String host) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/RokuRequestTypes.java
// public enum RokuRequestTypes {
// query_active_app("query/active-app"),
// query_device_info("query/device-info"),
// launch("launch"),
// keypress("keypress"),
// query_icon("query/icon"),
// search("search/browse?");
//
// private final String method;
//
// RokuRequestTypes(String method) {
// this.method = method;
// }
//
// public String getValue() {
// return method;
// }
// }
// Path: app/src/main/java/wseemann/media/romote/receiver/CommandReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import com.jaku.core.JakuRequest;
import com.jaku.core.KeypressKeyValues;
import com.jaku.request.KeypressRequest;
import wseemann.media.romote.tasks.RequestCallback;
import wseemann.media.romote.tasks.RequestTask;
import wseemann.media.romote.utils.CommandHelper;
import wseemann.media.romote.utils.RokuRequestTypes;
package wseemann.media.romote.receiver;
/**
* Created by wseemann on 4/14/18.
*/
public class CommandReceiver extends BroadcastReceiver {
private static final String TAG = CommandReceiver.class.getName();
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) { | String url = CommandHelper.getDeviceURL(context); |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/tasks/ChannelTask.java | // Path: app/src/main/java/wseemann/media/romote/utils/CommandHelper.java
// public class CommandHelper {
//
// private CommandHelper() {
//
// }
//
// public static String getDeviceURL(Context context) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getIconURL(Context context, String channelId) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost() + "/query/icon/" + channelId;
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getDeviceInfoURL(Context context, String host) {
// String url = host;
//
// return url;
// }
//
// public static String getConnectedDeviceInfoURL(Context context, String host) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
// }
| import android.content.Context;
import com.jaku.api.QueryRequests;
import com.jaku.model.Channel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import wseemann.media.romote.utils.CommandHelper; | package wseemann.media.romote.tasks;
public class ChannelTask implements Callable {
private Context context;
public ChannelTask(final Context context) {
this.context = context;
}
public List<Channel> call() {
// Retrieve all Channels.
List<Channel> channels;
try { | // Path: app/src/main/java/wseemann/media/romote/utils/CommandHelper.java
// public class CommandHelper {
//
// private CommandHelper() {
//
// }
//
// public static String getDeviceURL(Context context) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getIconURL(Context context, String channelId) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost() + "/query/icon/" + channelId;
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getDeviceInfoURL(Context context, String host) {
// String url = host;
//
// return url;
// }
//
// public static String getConnectedDeviceInfoURL(Context context, String host) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
// }
// Path: app/src/main/java/wseemann/media/romote/tasks/ChannelTask.java
import android.content.Context;
import com.jaku.api.QueryRequests;
import com.jaku.model.Channel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import wseemann.media.romote.utils.CommandHelper;
package wseemann.media.romote.tasks;
public class ChannelTask implements Callable {
private Context context;
public ChannelTask(final Context context) {
this.context = context;
}
public List<Channel> call() {
// Retrieve all Channels.
List<Channel> channels;
try { | channels = QueryRequests.queryAppsRequest(CommandHelper.getDeviceURL(context)); |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/view/RepeatingImageButton.java | // Path: app/src/main/java/wseemann/media/romote/utils/ViewUtils.java
// public class ViewUtils {
//
// private ViewUtils() {
//
// }
//
// public static void provideHapticFeedback(View view, int vibrateDurationMs) {
// if (PreferenceUtils.shouldProvideHapticFeedback(view.getContext())) {
// Vibrator vibe = (Vibrator) view.getContext().getSystemService(Context.VIBRATOR_SERVICE);
// vibe.vibrate(vibrateDurationMs);
// }
// }
// }
| import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import wseemann.media.romote.utils.ViewUtils; | /*
* ServeStream: A HTTP stream browser/player for Android
* Copyright 2010 William Seemann
*
* 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 wseemann.media.romote.view;
/**
* A button that will repeatedly call a 'listener' method
* as long as the button is pressed.
*/
public class RepeatingImageButton extends Button {
private static final int VIBRATE_DURATION_MS = 100;
private View.OnClickListener mClickListener;
private long mStartTime;
private int mRepeatCount;
private RepeatListener mListener;
private long mInterval = 500;
public RepeatingImageButton(Context context) {
this(context, null);
}
public RepeatingImageButton(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.buttonStyle);
}
public RepeatingImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
setLongClickable(true);
super.setOnClickListener((View view) -> { | // Path: app/src/main/java/wseemann/media/romote/utils/ViewUtils.java
// public class ViewUtils {
//
// private ViewUtils() {
//
// }
//
// public static void provideHapticFeedback(View view, int vibrateDurationMs) {
// if (PreferenceUtils.shouldProvideHapticFeedback(view.getContext())) {
// Vibrator vibe = (Vibrator) view.getContext().getSystemService(Context.VIBRATOR_SERVICE);
// vibe.vibrate(vibrateDurationMs);
// }
// }
// }
// Path: app/src/main/java/wseemann/media/romote/view/RepeatingImageButton.java
import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import wseemann.media.romote.utils.ViewUtils;
/*
* ServeStream: A HTTP stream browser/player for Android
* Copyright 2010 William Seemann
*
* 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 wseemann.media.romote.view;
/**
* A button that will repeatedly call a 'listener' method
* as long as the button is pressed.
*/
public class RepeatingImageButton extends Button {
private static final int VIBRATE_DURATION_MS = 100;
private View.OnClickListener mClickListener;
private long mStartTime;
private int mRepeatCount;
private RepeatListener mListener;
private long mInterval = 500;
public RepeatingImageButton(Context context) {
this(context, null);
}
public RepeatingImageButton(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.buttonStyle);
}
public RepeatingImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
setLongClickable(true);
super.setOnClickListener((View view) -> { | ViewUtils.provideHapticFeedback(view, VIBRATE_DURATION_MS); |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/utils/WifiApManager.java | // Path: app/src/main/java/wseemann/media/romote/model/ClientScanResult.java
// public class ClientScanResult {
// private String IpAddr;
// private String HWAddr;
// private String Device;
// private boolean isReachable;
//
// public ClientScanResult(String ipAddr, String hWAddr, String device, boolean isReachable) {
// super();
// this.IpAddr = ipAddr;
// this.HWAddr = hWAddr;
// this.Device = device;
// this.isReachable = isReachable;
// }
//
// public String getIpAddr() {
// return IpAddr;
// }
//
// public void setIpAddr(String ipAddr) {
// IpAddr = ipAddr;
// }
//
// public String getHWAddr() {
// return HWAddr;
// }
//
// public void setHWAddr(String hWAddr) {
// HWAddr = hWAddr;
// }
//
// public String getDevice() {
// return Device;
// }
//
// public void setDevice(String device) {
// Device = device;
// }
//
// public boolean isReachable() {
// return isReachable;
// }
//
// public void setReachable(boolean isReachable) {
// this.isReachable = isReachable;
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/Constants.java
// public enum WIFI_AP_STATE {
// WIFI_AP_STATE_DISABLING,
// WIFI_AP_STATE_DISABLED,
// WIFI_AP_STATE_ENABLING,
// WIFI_AP_STATE_ENABLED,
// WIFI_AP_STATE_FAILED
// }
| import android.util.Log;
import wseemann.media.romote.model.ClientScanResult;
import wseemann.media.romote.utils.Constants.WIFI_AP_STATE;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings; | /*
* Copyright 2013 WhiteByte (Nick Russler, Ahmet Yueksektepe).
*
* 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 wseemann.media.romote.utils;
public class WifiApManager {
private final WifiManager mWifiManager;
private Context context;
public WifiApManager(Context context) {
this.context = context;
mWifiManager = (WifiManager) this.context.getSystemService(Context.WIFI_SERVICE);
}
/**
* Show write permission settings page to user if necessary or forced
* @param force show settings page even when rights are already granted
*/
public void showWritePermissionSettings(boolean force) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (force || !Settings.System.canWrite(this.context)) {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + this.context.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.context.startActivity(intent);
}
}
}
/**
* Start AccessPoint mode with the specified
* configuration. If the radio is already running in
* AP mode, update the new configuration
* Note that starting in access point mode disables station
* mode operation
*
* @param wifiConfig SSID, security and channel details as part of WifiConfiguration
* @return {@code true} if the operation succeeds, {@code false} otherwise
*/
public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
try {
if (enabled) { // disable WiFi in any case
mWifiManager.setWifiEnabled(false);
}
Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
return (Boolean) method.invoke(mWifiManager, wifiConfig, enabled);
} catch (Exception e) {
Log.e(this.getClass().toString(), "", e);
return false;
}
}
/**
* Gets the Wi-Fi enabled state.
*
* @return {@link WIFI_AP_STATE}
* @see #isWifiApEnabled()
*/ | // Path: app/src/main/java/wseemann/media/romote/model/ClientScanResult.java
// public class ClientScanResult {
// private String IpAddr;
// private String HWAddr;
// private String Device;
// private boolean isReachable;
//
// public ClientScanResult(String ipAddr, String hWAddr, String device, boolean isReachable) {
// super();
// this.IpAddr = ipAddr;
// this.HWAddr = hWAddr;
// this.Device = device;
// this.isReachable = isReachable;
// }
//
// public String getIpAddr() {
// return IpAddr;
// }
//
// public void setIpAddr(String ipAddr) {
// IpAddr = ipAddr;
// }
//
// public String getHWAddr() {
// return HWAddr;
// }
//
// public void setHWAddr(String hWAddr) {
// HWAddr = hWAddr;
// }
//
// public String getDevice() {
// return Device;
// }
//
// public void setDevice(String device) {
// Device = device;
// }
//
// public boolean isReachable() {
// return isReachable;
// }
//
// public void setReachable(boolean isReachable) {
// this.isReachable = isReachable;
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/Constants.java
// public enum WIFI_AP_STATE {
// WIFI_AP_STATE_DISABLING,
// WIFI_AP_STATE_DISABLED,
// WIFI_AP_STATE_ENABLING,
// WIFI_AP_STATE_ENABLED,
// WIFI_AP_STATE_FAILED
// }
// Path: app/src/main/java/wseemann/media/romote/utils/WifiApManager.java
import android.util.Log;
import wseemann.media.romote.model.ClientScanResult;
import wseemann.media.romote.utils.Constants.WIFI_AP_STATE;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
/*
* Copyright 2013 WhiteByte (Nick Russler, Ahmet Yueksektepe).
*
* 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 wseemann.media.romote.utils;
public class WifiApManager {
private final WifiManager mWifiManager;
private Context context;
public WifiApManager(Context context) {
this.context = context;
mWifiManager = (WifiManager) this.context.getSystemService(Context.WIFI_SERVICE);
}
/**
* Show write permission settings page to user if necessary or forced
* @param force show settings page even when rights are already granted
*/
public void showWritePermissionSettings(boolean force) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (force || !Settings.System.canWrite(this.context)) {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + this.context.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.context.startActivity(intent);
}
}
}
/**
* Start AccessPoint mode with the specified
* configuration. If the radio is already running in
* AP mode, update the new configuration
* Note that starting in access point mode disables station
* mode operation
*
* @param wifiConfig SSID, security and channel details as part of WifiConfiguration
* @return {@code true} if the operation succeeds, {@code false} otherwise
*/
public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
try {
if (enabled) { // disable WiFi in any case
mWifiManager.setWifiEnabled(false);
}
Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
return (Boolean) method.invoke(mWifiManager, wifiConfig, enabled);
} catch (Exception e) {
Log.e(this.getClass().toString(), "", e);
return false;
}
}
/**
* Gets the Wi-Fi enabled state.
*
* @return {@link WIFI_AP_STATE}
* @see #isWifiApEnabled()
*/ | public WIFI_AP_STATE getWifiApState() { |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/utils/WifiApManager.java | // Path: app/src/main/java/wseemann/media/romote/model/ClientScanResult.java
// public class ClientScanResult {
// private String IpAddr;
// private String HWAddr;
// private String Device;
// private boolean isReachable;
//
// public ClientScanResult(String ipAddr, String hWAddr, String device, boolean isReachable) {
// super();
// this.IpAddr = ipAddr;
// this.HWAddr = hWAddr;
// this.Device = device;
// this.isReachable = isReachable;
// }
//
// public String getIpAddr() {
// return IpAddr;
// }
//
// public void setIpAddr(String ipAddr) {
// IpAddr = ipAddr;
// }
//
// public String getHWAddr() {
// return HWAddr;
// }
//
// public void setHWAddr(String hWAddr) {
// HWAddr = hWAddr;
// }
//
// public String getDevice() {
// return Device;
// }
//
// public void setDevice(String device) {
// Device = device;
// }
//
// public boolean isReachable() {
// return isReachable;
// }
//
// public void setReachable(boolean isReachable) {
// this.isReachable = isReachable;
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/Constants.java
// public enum WIFI_AP_STATE {
// WIFI_AP_STATE_DISABLING,
// WIFI_AP_STATE_DISABLED,
// WIFI_AP_STATE_ENABLING,
// WIFI_AP_STATE_ENABLED,
// WIFI_AP_STATE_FAILED
// }
| import android.util.Log;
import wseemann.media.romote.model.ClientScanResult;
import wseemann.media.romote.utils.Constants.WIFI_AP_STATE;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings; | try {
Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
return (WifiConfiguration) method.invoke(mWifiManager);
} catch (Exception e) {
Log.e(this.getClass().toString(), "", e);
return null;
}
}
/**
* Sets the Wi-Fi AP Configuration.
*
* @return {@code true} if the operation succeeded, {@code false} otherwise
*/
public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
try {
Method method = mWifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
return (Boolean) method.invoke(mWifiManager, wifiConfig);
} catch (Exception e) {
Log.e(this.getClass().toString(), "", e);
return false;
}
}
/**
* Gets a list of the clients connected to the Hotspot, reachable timeout is 300
*
* @param onlyReachables {@code false} if the list should contain unreachable (probably disconnected) clients, {@code true} otherwise
* @param finishListener, Interface called when the scan method finishes
*/ | // Path: app/src/main/java/wseemann/media/romote/model/ClientScanResult.java
// public class ClientScanResult {
// private String IpAddr;
// private String HWAddr;
// private String Device;
// private boolean isReachable;
//
// public ClientScanResult(String ipAddr, String hWAddr, String device, boolean isReachable) {
// super();
// this.IpAddr = ipAddr;
// this.HWAddr = hWAddr;
// this.Device = device;
// this.isReachable = isReachable;
// }
//
// public String getIpAddr() {
// return IpAddr;
// }
//
// public void setIpAddr(String ipAddr) {
// IpAddr = ipAddr;
// }
//
// public String getHWAddr() {
// return HWAddr;
// }
//
// public void setHWAddr(String hWAddr) {
// HWAddr = hWAddr;
// }
//
// public String getDevice() {
// return Device;
// }
//
// public void setDevice(String device) {
// Device = device;
// }
//
// public boolean isReachable() {
// return isReachable;
// }
//
// public void setReachable(boolean isReachable) {
// this.isReachable = isReachable;
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/Constants.java
// public enum WIFI_AP_STATE {
// WIFI_AP_STATE_DISABLING,
// WIFI_AP_STATE_DISABLED,
// WIFI_AP_STATE_ENABLING,
// WIFI_AP_STATE_ENABLED,
// WIFI_AP_STATE_FAILED
// }
// Path: app/src/main/java/wseemann/media/romote/utils/WifiApManager.java
import android.util.Log;
import wseemann.media.romote.model.ClientScanResult;
import wseemann.media.romote.utils.Constants.WIFI_AP_STATE;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
try {
Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
return (WifiConfiguration) method.invoke(mWifiManager);
} catch (Exception e) {
Log.e(this.getClass().toString(), "", e);
return null;
}
}
/**
* Sets the Wi-Fi AP Configuration.
*
* @return {@code true} if the operation succeeded, {@code false} otherwise
*/
public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
try {
Method method = mWifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
return (Boolean) method.invoke(mWifiManager, wifiConfig);
} catch (Exception e) {
Log.e(this.getClass().toString(), "", e);
return false;
}
}
/**
* Gets a list of the clients connected to the Hotspot, reachable timeout is 300
*
* @param onlyReachables {@code false} if the list should contain unreachable (probably disconnected) clients, {@code true} otherwise
* @param finishListener, Interface called when the scan method finishes
*/ | public ArrayList<ClientScanResult> getClientList(boolean onlyReachables) { |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/activity/DeviceInfoActivity.java | // Path: app/src/main/java/wseemann/media/romote/fragment/DeviceInfoFragment.java
// public class DeviceInfoFragment extends ListFragment {
//
// private static final String TAG = DeviceInfoFragment.class.getName();
//
// private DeviceInfoAdapter mAdapter;
//
// public static DeviceInfoFragment getInstance(String serialNumber, String host) {
// DeviceInfoFragment fragment = new DeviceInfoFragment();
//
// Bundle bundle = new Bundle();
// bundle.putString("serial_number", serialNumber);
// bundle.putString("host", host);
//
// fragment.setArguments(bundle);
//
// return fragment;
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// }
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
//
// setEmptyText(getString(R.string.no_device_info));
//
// Bundle bundle = getArguments();
// String serialNumber = bundle.getString("serial_number");
// String host = bundle.getString("host");
//
// Device device = DBUtils.getDevice(getActivity(), serialNumber);
//
// List<Entry> entries = new ArrayList<Entry>();
//
// if (device != null) {
// entries = parseDevice(device);
// }
//
// mAdapter = new DeviceInfoAdapter(DeviceInfoFragment.this.getActivity(), entries);
// setListAdapter(mAdapter);
//
// setListShown(false);
//
// if (host == null) {
// sendCommand(CommandHelper.getConnectedDeviceInfoURL(getActivity(), device.getHost()));
// } else {
// sendCommand(CommandHelper.getDeviceInfoURL(getActivity(), host));
// }
// }
//
// private void sendCommand(String command) {
// String url = command;
//
// QueryDeviceInfoRequest queryActiveAppRequest = new QueryDeviceInfoRequest(url);
// JakuRequest request = new JakuRequest(queryActiveAppRequest, new DeviceParser());
//
// new RequestTask(request, new RequestCallback() {
// @Override
// public void requestResult(RokuRequestTypes rokuRequestType, RequestTask.Result result) {
// Device device = (Device) result.mResultValue;
//
// List<Entry> entries = parseDevice(device);
//
// mAdapter.addAll(entries);
// mAdapter.notifyDataSetChanged();
// DeviceInfoFragment.this.setListShown(true);
// }
//
// @Override
// public void onErrorResponse(RequestTask.Result result) {
// DeviceInfoFragment.this.setListShown(true);
// }
// }).execute(RokuRequestTypes.query_device_info);
// }
//
// private List<Entry> parseDevice(Device device) {
// List<Entry> entries = new ArrayList<Entry>();
//
// entries.add(new Entry("udn", device.getUdn()));
// entries.add(new Entry("serial-number", device.getSerialNumber()));
// entries.add(new Entry("device-id", device.getDeviceId()));
// entries.add(new Entry("vendor-name", device.getVendorName()));
// entries.add(new Entry("model-number", device.getModelNumber()));
// entries.add(new Entry("model-name", device.getModelName()));
// entries.add(new Entry("wifi-mac", device.getWifiMac()));
// entries.add(new Entry("ethernet-mac", device.getEthernetMac()));
// entries.add(new Entry("network-type", device.getNetworkType()));
// entries.add(new Entry("user-device-name", device.getUserDeviceName()));
// entries.add(new Entry("software-version", device.getSoftwareVersion()));
// entries.add(new Entry("software-build", device.getSoftwareBuild()));
// entries.add(new Entry("secure-device", device.getSecureDevice()));
// entries.add(new Entry("language", device.getLanguage()));
// entries.add(new Entry("country", device.getCountry()));
// entries.add(new Entry("locale", device.getLocale()));
// entries.add(new Entry("time-zone", device.getTimeZone()));
// entries.add(new Entry("time-zone-offset", device.getTimeZoneOffset()));
// entries.add(new Entry("power-mode", device.getPowerMode()));
// entries.add(new Entry("supports-suspend", device.getSupportsSuspend()));
// entries.add(new Entry("supports-find-remote", device.getSupportsFindRemote()));
// entries.add(new Entry("supports-audio-guide", device.getSupportsAudioGuide()));
// entries.add(new Entry("developer-enabled", device.getDeveloperEnabled()));
// entries.add(new Entry("keyed-developer-id", device.getKeyedDeveloperId()));
// entries.add(new Entry("search-enabled", device.getSearchEnabled()));
// entries.add(new Entry("voice-search-enabled", device.getVoiceSearchEnabled()));
// entries.add(new Entry("notifications-enabled", device.getNotificationsEnabled()));
// entries.add(new Entry("notifications-first-use", device.getNotificationsFirstUse()));
// entries.add(new Entry("supports-private-listening", device.getSupportsPrivateListening()));
// entries.add(new Entry("headphones-connected", device.getHeadphonesConnected()));
//
// return entries;
// }
// }
| import android.os.Bundle;
import android.view.MenuItem;
import androidx.fragment.app.FragmentTransaction;
import wseemann.media.romote.R;
import wseemann.media.romote.fragment.DeviceInfoFragment; | package wseemann.media.romote.activity;
/**
* Created by wseemann on 6/19/16.
*/
public class DeviceInfoActivity extends ConnectivityActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deviceinfo);
String serialNumber = getIntent().getStringExtra("serial_number");
String host = getIntent().getStringExtra("host");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); | // Path: app/src/main/java/wseemann/media/romote/fragment/DeviceInfoFragment.java
// public class DeviceInfoFragment extends ListFragment {
//
// private static final String TAG = DeviceInfoFragment.class.getName();
//
// private DeviceInfoAdapter mAdapter;
//
// public static DeviceInfoFragment getInstance(String serialNumber, String host) {
// DeviceInfoFragment fragment = new DeviceInfoFragment();
//
// Bundle bundle = new Bundle();
// bundle.putString("serial_number", serialNumber);
// bundle.putString("host", host);
//
// fragment.setArguments(bundle);
//
// return fragment;
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// }
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
//
// setEmptyText(getString(R.string.no_device_info));
//
// Bundle bundle = getArguments();
// String serialNumber = bundle.getString("serial_number");
// String host = bundle.getString("host");
//
// Device device = DBUtils.getDevice(getActivity(), serialNumber);
//
// List<Entry> entries = new ArrayList<Entry>();
//
// if (device != null) {
// entries = parseDevice(device);
// }
//
// mAdapter = new DeviceInfoAdapter(DeviceInfoFragment.this.getActivity(), entries);
// setListAdapter(mAdapter);
//
// setListShown(false);
//
// if (host == null) {
// sendCommand(CommandHelper.getConnectedDeviceInfoURL(getActivity(), device.getHost()));
// } else {
// sendCommand(CommandHelper.getDeviceInfoURL(getActivity(), host));
// }
// }
//
// private void sendCommand(String command) {
// String url = command;
//
// QueryDeviceInfoRequest queryActiveAppRequest = new QueryDeviceInfoRequest(url);
// JakuRequest request = new JakuRequest(queryActiveAppRequest, new DeviceParser());
//
// new RequestTask(request, new RequestCallback() {
// @Override
// public void requestResult(RokuRequestTypes rokuRequestType, RequestTask.Result result) {
// Device device = (Device) result.mResultValue;
//
// List<Entry> entries = parseDevice(device);
//
// mAdapter.addAll(entries);
// mAdapter.notifyDataSetChanged();
// DeviceInfoFragment.this.setListShown(true);
// }
//
// @Override
// public void onErrorResponse(RequestTask.Result result) {
// DeviceInfoFragment.this.setListShown(true);
// }
// }).execute(RokuRequestTypes.query_device_info);
// }
//
// private List<Entry> parseDevice(Device device) {
// List<Entry> entries = new ArrayList<Entry>();
//
// entries.add(new Entry("udn", device.getUdn()));
// entries.add(new Entry("serial-number", device.getSerialNumber()));
// entries.add(new Entry("device-id", device.getDeviceId()));
// entries.add(new Entry("vendor-name", device.getVendorName()));
// entries.add(new Entry("model-number", device.getModelNumber()));
// entries.add(new Entry("model-name", device.getModelName()));
// entries.add(new Entry("wifi-mac", device.getWifiMac()));
// entries.add(new Entry("ethernet-mac", device.getEthernetMac()));
// entries.add(new Entry("network-type", device.getNetworkType()));
// entries.add(new Entry("user-device-name", device.getUserDeviceName()));
// entries.add(new Entry("software-version", device.getSoftwareVersion()));
// entries.add(new Entry("software-build", device.getSoftwareBuild()));
// entries.add(new Entry("secure-device", device.getSecureDevice()));
// entries.add(new Entry("language", device.getLanguage()));
// entries.add(new Entry("country", device.getCountry()));
// entries.add(new Entry("locale", device.getLocale()));
// entries.add(new Entry("time-zone", device.getTimeZone()));
// entries.add(new Entry("time-zone-offset", device.getTimeZoneOffset()));
// entries.add(new Entry("power-mode", device.getPowerMode()));
// entries.add(new Entry("supports-suspend", device.getSupportsSuspend()));
// entries.add(new Entry("supports-find-remote", device.getSupportsFindRemote()));
// entries.add(new Entry("supports-audio-guide", device.getSupportsAudioGuide()));
// entries.add(new Entry("developer-enabled", device.getDeveloperEnabled()));
// entries.add(new Entry("keyed-developer-id", device.getKeyedDeveloperId()));
// entries.add(new Entry("search-enabled", device.getSearchEnabled()));
// entries.add(new Entry("voice-search-enabled", device.getVoiceSearchEnabled()));
// entries.add(new Entry("notifications-enabled", device.getNotificationsEnabled()));
// entries.add(new Entry("notifications-first-use", device.getNotificationsFirstUse()));
// entries.add(new Entry("supports-private-listening", device.getSupportsPrivateListening()));
// entries.add(new Entry("headphones-connected", device.getHeadphonesConnected()));
//
// return entries;
// }
// }
// Path: app/src/main/java/wseemann/media/romote/activity/DeviceInfoActivity.java
import android.os.Bundle;
import android.view.MenuItem;
import androidx.fragment.app.FragmentTransaction;
import wseemann.media.romote.R;
import wseemann.media.romote.fragment.DeviceInfoFragment;
package wseemann.media.romote.activity;
/**
* Created by wseemann on 6/19/16.
*/
public class DeviceInfoActivity extends ConnectivityActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deviceinfo);
String serialNumber = getIntent().getStringExtra("serial_number");
String host = getIntent().getStringExtra("host");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); | transaction.add(android.R.id.content, DeviceInfoFragment.getInstance(serialNumber, host)).commit(); |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/adapter/DeviceAdapter.java | // Path: app/src/main/java/wseemann/media/romote/utils/PreferenceUtils.java
// public class PreferenceUtils {
//
// private PreferenceUtils() {
//
// }
//
// public static void setConnectedDevice(Context context, String serialNumber) {
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
//
// SharedPreferences.Editor editor = prefs.edit();
// editor.putString("serial_number", serialNumber);
// editor.commit();
// }
//
// public static Device getConnectedDevice(Context context) throws Exception {
// Device device;
//
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// String serialNumber = prefs.getString("serial_number", null);
//
// device = DBUtils.getDevice(context, serialNumber);
//
// if (device == null) {
// throw new Exception("Device not connected");
// }
//
// return device;
// }
//
// public static boolean shouldProvideHapticFeedback(Context context) {
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// return prefs.getBoolean("haptic_feedback_preference", false);
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import java.util.List;
import wseemann.media.romote.R;
import wseemann.media.romote.model.Device;
import wseemann.media.romote.utils.PreferenceUtils; | ImageView mIcon;
TextView mText1;
TextView mText2;
TextView mText3;
ImageView mImageButton;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.device, null);
holder = new ViewHolder();
holder.mIcon = (ImageView) convertView.findViewById(android.R.id.icon);
holder.mText1 = (TextView) convertView.findViewById(android.R.id.text1);
holder.mText2 = (TextView) convertView.findViewById(android.R.id.text2);
holder.mText3 = (TextView) convertView.findViewById(R.id.text3);
holder.mImageButton = (ImageView) convertView.findViewById(R.id.overflow_button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Device device = (Device) getItem(position);
Device connectedDevice = null;
try { | // Path: app/src/main/java/wseemann/media/romote/utils/PreferenceUtils.java
// public class PreferenceUtils {
//
// private PreferenceUtils() {
//
// }
//
// public static void setConnectedDevice(Context context, String serialNumber) {
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
//
// SharedPreferences.Editor editor = prefs.edit();
// editor.putString("serial_number", serialNumber);
// editor.commit();
// }
//
// public static Device getConnectedDevice(Context context) throws Exception {
// Device device;
//
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// String serialNumber = prefs.getString("serial_number", null);
//
// device = DBUtils.getDevice(context, serialNumber);
//
// if (device == null) {
// throw new Exception("Device not connected");
// }
//
// return device;
// }
//
// public static boolean shouldProvideHapticFeedback(Context context) {
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// return prefs.getBoolean("haptic_feedback_preference", false);
// }
// }
// Path: app/src/main/java/wseemann/media/romote/adapter/DeviceAdapter.java
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import java.util.List;
import wseemann.media.romote.R;
import wseemann.media.romote.model.Device;
import wseemann.media.romote.utils.PreferenceUtils;
ImageView mIcon;
TextView mText1;
TextView mText2;
TextView mText3;
ImageView mImageButton;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.device, null);
holder = new ViewHolder();
holder.mIcon = (ImageView) convertView.findViewById(android.R.id.icon);
holder.mText1 = (TextView) convertView.findViewById(android.R.id.text1);
holder.mText2 = (TextView) convertView.findViewById(android.R.id.text2);
holder.mText3 = (TextView) convertView.findViewById(R.id.text3);
holder.mImageButton = (ImageView) convertView.findViewById(R.id.overflow_button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Device device = (Device) getItem(position);
Device connectedDevice = null;
try { | connectedDevice = PreferenceUtils.getConnectedDevice(mContext); |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/fragment/InstallChannelDialog.java | // Path: app/src/main/java/wseemann/media/romote/utils/CommandHelper.java
// public class CommandHelper {
//
// private CommandHelper() {
//
// }
//
// public static String getDeviceURL(Context context) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getIconURL(Context context, String channelId) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost() + "/query/icon/" + channelId;
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getDeviceInfoURL(Context context, String host) {
// String url = host;
//
// return url;
// }
//
// public static String getConnectedDeviceInfoURL(Context context, String host) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
// }
| import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import wseemann.media.romote.R;
import wseemann.media.romote.utils.CommandHelper; | package wseemann.media.romote.fragment;
/**
* Created by wseemann on 6/20/16.
*/
public class InstallChannelDialog extends DialogFragment {
private String mChannelCode;
private static InstallChannelListener mListener;
public static InstallChannelDialog getInstance(Activity activity, String channelCode) {
try {
// Instantiate the InstallChannelListener so we can send events with it
mListener = (InstallChannelListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement InstallChannelListener");
}
InstallChannelDialog fragment = new InstallChannelDialog();
Bundle args = new Bundle();
args.putString("channel_code", channelCode);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCancelable(false);
mChannelCode = getArguments().getString("channel_code");
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.fragment_install_channel, null);
ImageView imageView = (ImageView) view.findViewById(android.R.id.icon);
Picasso.with(getActivity()) | // Path: app/src/main/java/wseemann/media/romote/utils/CommandHelper.java
// public class CommandHelper {
//
// private CommandHelper() {
//
// }
//
// public static String getDeviceURL(Context context) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getIconURL(Context context, String channelId) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost() + "/query/icon/" + channelId;
// } catch (Exception ex) {
// }
//
// return url;
// }
//
// public static String getDeviceInfoURL(Context context, String host) {
// String url = host;
//
// return url;
// }
//
// public static String getConnectedDeviceInfoURL(Context context, String host) {
// String url = "";
//
// try {
// Device device = PreferenceUtils.getConnectedDevice(context);
//
// url = device.getHost();
// } catch (Exception ex) {
// }
//
// return url;
// }
// }
// Path: app/src/main/java/wseemann/media/romote/fragment/InstallChannelDialog.java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import wseemann.media.romote.R;
import wseemann.media.romote.utils.CommandHelper;
package wseemann.media.romote.fragment;
/**
* Created by wseemann on 6/20/16.
*/
public class InstallChannelDialog extends DialogFragment {
private String mChannelCode;
private static InstallChannelListener mListener;
public static InstallChannelDialog getInstance(Activity activity, String channelCode) {
try {
// Instantiate the InstallChannelListener so we can send events with it
mListener = (InstallChannelListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement InstallChannelListener");
}
InstallChannelDialog fragment = new InstallChannelDialog();
Bundle args = new Bundle();
args.putString("channel_code", channelCode);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCancelable(false);
mChannelCode = getArguments().getString("channel_code");
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.fragment_install_channel, null);
ImageView imageView = (ImageView) view.findViewById(android.R.id.icon);
Picasso.with(getActivity()) | .load(CommandHelper.getIconURL(getActivity(), mChannelCode)) |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/activity/ConnectivityActivity.java | // Path: app/src/main/java/wseemann/media/romote/fragment/ConnectivityDialog.java
// public class ConnectivityDialog extends DialogFragment {
//
// private static ConnectivityFragmentListener mListener;
//
// public static ConnectivityDialog getInstance(Activity activity) {
// /*try {
// // Instantiate the ConnectivityFragmentListener so we can send events with it
// mListener = (ConnectivityFragmentListener) activity;
// } catch (ClassCastException e) {
// // The activity doesn't implement the interface, throw exception
// throw new ClassCastException(activity.toString()
// + " must implement ConnectivityFragmentListener");
// }*/
//
// return new ConnectivityDialog();
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setCancelable(false);
// }
//
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// builder.setTitle(getString(R.string.connectivity_dialog_title));
// builder.setMessage(getString(R.string.connectivity_dialog_message));
// builder.setNeutralButton(R.string.connectivity_dialog_button, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int id) {
// try {
// // In some cases, a matching Activity may not exist,so ensure you safeguard against this.
// startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
// } catch (ActivityNotFoundException ex) {
// startActivity(new Intent(Settings.ACTION_SETTINGS));
// }
// }
// });
//
// return builder.create();
// }
//
// public interface ConnectivityFragmentListener {
// public void onDialogCancelled();
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/NetworkMonitor.java
// public class NetworkMonitor {
//
// private ConnectivityManager mCm;
// private WifiApManager mWifiApManager;
//
// public NetworkMonitor(Activity activity, int requestCode) {
// // Here, thisActivity is the current activity
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)
// != PackageManager.PERMISSION_GRANTED) {
// requestPermission(activity, requestCode);
// } else {
// mCm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
// mWifiApManager = new WifiApManager(activity);
// }
// }
//
// public boolean isConnectedToiWiFi() {
// if (mCm == null) {
// return false;
// }
//
// NetworkInfo activeNetwork = mCm.getActiveNetworkInfo();
//
// boolean isConnected = activeNetwork != null &&
// activeNetwork.isConnectedOrConnecting();
//
// if (isConnected) {
// return activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
// }
//
// return false;
// }
//
// public boolean isMobileAccessPointOn() {
// if (mWifiApManager == null) {
// return false;
// }
//
// return mWifiApManager.isWifiApEnabled();
// }
//
// private void requestPermission(Activity activity, int requestCode) {
// // Here, thisActivity is the current activity
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)
// != PackageManager.PERMISSION_GRANTED) {
//
// // Should we show an explanation?
// if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)) {
//
// // Show an expanation to the user *asynchronously* -- don't block
// // this thread waiting for the user's response! After the user
// // sees the explanation, try again to request the permission.
//
// } else {
//
// // No explanation needed, we can request the permission.
//
// ActivityCompat.requestPermissions(activity,
// new String[]{Manifest.permission.ACCESS_NETWORK_STATE},
// requestCode);
//
// // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// // app-defined int constant. The callback method gets the
// // result of the request.
// }
// }
// }
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import wseemann.media.romote.fragment.ConnectivityDialog;
import wseemann.media.romote.utils.NetworkMonitor; | package wseemann.media.romote.activity;
/**
* Created by wseemann on 6/19/16.
*/
public class ConnectivityActivity extends ShakeActivity {
private static final int MY_PERMISSIONS_ACCESS_NETWORK_STATE = 100;
| // Path: app/src/main/java/wseemann/media/romote/fragment/ConnectivityDialog.java
// public class ConnectivityDialog extends DialogFragment {
//
// private static ConnectivityFragmentListener mListener;
//
// public static ConnectivityDialog getInstance(Activity activity) {
// /*try {
// // Instantiate the ConnectivityFragmentListener so we can send events with it
// mListener = (ConnectivityFragmentListener) activity;
// } catch (ClassCastException e) {
// // The activity doesn't implement the interface, throw exception
// throw new ClassCastException(activity.toString()
// + " must implement ConnectivityFragmentListener");
// }*/
//
// return new ConnectivityDialog();
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setCancelable(false);
// }
//
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// builder.setTitle(getString(R.string.connectivity_dialog_title));
// builder.setMessage(getString(R.string.connectivity_dialog_message));
// builder.setNeutralButton(R.string.connectivity_dialog_button, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int id) {
// try {
// // In some cases, a matching Activity may not exist,so ensure you safeguard against this.
// startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
// } catch (ActivityNotFoundException ex) {
// startActivity(new Intent(Settings.ACTION_SETTINGS));
// }
// }
// });
//
// return builder.create();
// }
//
// public interface ConnectivityFragmentListener {
// public void onDialogCancelled();
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/NetworkMonitor.java
// public class NetworkMonitor {
//
// private ConnectivityManager mCm;
// private WifiApManager mWifiApManager;
//
// public NetworkMonitor(Activity activity, int requestCode) {
// // Here, thisActivity is the current activity
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)
// != PackageManager.PERMISSION_GRANTED) {
// requestPermission(activity, requestCode);
// } else {
// mCm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
// mWifiApManager = new WifiApManager(activity);
// }
// }
//
// public boolean isConnectedToiWiFi() {
// if (mCm == null) {
// return false;
// }
//
// NetworkInfo activeNetwork = mCm.getActiveNetworkInfo();
//
// boolean isConnected = activeNetwork != null &&
// activeNetwork.isConnectedOrConnecting();
//
// if (isConnected) {
// return activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
// }
//
// return false;
// }
//
// public boolean isMobileAccessPointOn() {
// if (mWifiApManager == null) {
// return false;
// }
//
// return mWifiApManager.isWifiApEnabled();
// }
//
// private void requestPermission(Activity activity, int requestCode) {
// // Here, thisActivity is the current activity
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)
// != PackageManager.PERMISSION_GRANTED) {
//
// // Should we show an explanation?
// if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)) {
//
// // Show an expanation to the user *asynchronously* -- don't block
// // this thread waiting for the user's response! After the user
// // sees the explanation, try again to request the permission.
//
// } else {
//
// // No explanation needed, we can request the permission.
//
// ActivityCompat.requestPermissions(activity,
// new String[]{Manifest.permission.ACCESS_NETWORK_STATE},
// requestCode);
//
// // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// // app-defined int constant. The callback method gets the
// // result of the request.
// }
// }
// }
// }
// Path: app/src/main/java/wseemann/media/romote/activity/ConnectivityActivity.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import wseemann.media.romote.fragment.ConnectivityDialog;
import wseemann.media.romote.utils.NetworkMonitor;
package wseemann.media.romote.activity;
/**
* Created by wseemann on 6/19/16.
*/
public class ConnectivityActivity extends ShakeActivity {
private static final int MY_PERMISSIONS_ACCESS_NETWORK_STATE = 100;
| private ConnectivityDialog mDialog; |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/activity/ConnectivityActivity.java | // Path: app/src/main/java/wseemann/media/romote/fragment/ConnectivityDialog.java
// public class ConnectivityDialog extends DialogFragment {
//
// private static ConnectivityFragmentListener mListener;
//
// public static ConnectivityDialog getInstance(Activity activity) {
// /*try {
// // Instantiate the ConnectivityFragmentListener so we can send events with it
// mListener = (ConnectivityFragmentListener) activity;
// } catch (ClassCastException e) {
// // The activity doesn't implement the interface, throw exception
// throw new ClassCastException(activity.toString()
// + " must implement ConnectivityFragmentListener");
// }*/
//
// return new ConnectivityDialog();
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setCancelable(false);
// }
//
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// builder.setTitle(getString(R.string.connectivity_dialog_title));
// builder.setMessage(getString(R.string.connectivity_dialog_message));
// builder.setNeutralButton(R.string.connectivity_dialog_button, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int id) {
// try {
// // In some cases, a matching Activity may not exist,so ensure you safeguard against this.
// startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
// } catch (ActivityNotFoundException ex) {
// startActivity(new Intent(Settings.ACTION_SETTINGS));
// }
// }
// });
//
// return builder.create();
// }
//
// public interface ConnectivityFragmentListener {
// public void onDialogCancelled();
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/NetworkMonitor.java
// public class NetworkMonitor {
//
// private ConnectivityManager mCm;
// private WifiApManager mWifiApManager;
//
// public NetworkMonitor(Activity activity, int requestCode) {
// // Here, thisActivity is the current activity
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)
// != PackageManager.PERMISSION_GRANTED) {
// requestPermission(activity, requestCode);
// } else {
// mCm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
// mWifiApManager = new WifiApManager(activity);
// }
// }
//
// public boolean isConnectedToiWiFi() {
// if (mCm == null) {
// return false;
// }
//
// NetworkInfo activeNetwork = mCm.getActiveNetworkInfo();
//
// boolean isConnected = activeNetwork != null &&
// activeNetwork.isConnectedOrConnecting();
//
// if (isConnected) {
// return activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
// }
//
// return false;
// }
//
// public boolean isMobileAccessPointOn() {
// if (mWifiApManager == null) {
// return false;
// }
//
// return mWifiApManager.isWifiApEnabled();
// }
//
// private void requestPermission(Activity activity, int requestCode) {
// // Here, thisActivity is the current activity
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)
// != PackageManager.PERMISSION_GRANTED) {
//
// // Should we show an explanation?
// if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)) {
//
// // Show an expanation to the user *asynchronously* -- don't block
// // this thread waiting for the user's response! After the user
// // sees the explanation, try again to request the permission.
//
// } else {
//
// // No explanation needed, we can request the permission.
//
// ActivityCompat.requestPermissions(activity,
// new String[]{Manifest.permission.ACCESS_NETWORK_STATE},
// requestCode);
//
// // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// // app-defined int constant. The callback method gets the
// // result of the request.
// }
// }
// }
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import wseemann.media.romote.fragment.ConnectivityDialog;
import wseemann.media.romote.utils.NetworkMonitor; | package wseemann.media.romote.activity;
/**
* Created by wseemann on 6/19/16.
*/
public class ConnectivityActivity extends ShakeActivity {
private static final int MY_PERMISSIONS_ACCESS_NETWORK_STATE = 100;
private ConnectivityDialog mDialog;
| // Path: app/src/main/java/wseemann/media/romote/fragment/ConnectivityDialog.java
// public class ConnectivityDialog extends DialogFragment {
//
// private static ConnectivityFragmentListener mListener;
//
// public static ConnectivityDialog getInstance(Activity activity) {
// /*try {
// // Instantiate the ConnectivityFragmentListener so we can send events with it
// mListener = (ConnectivityFragmentListener) activity;
// } catch (ClassCastException e) {
// // The activity doesn't implement the interface, throw exception
// throw new ClassCastException(activity.toString()
// + " must implement ConnectivityFragmentListener");
// }*/
//
// return new ConnectivityDialog();
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setCancelable(false);
// }
//
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// builder.setTitle(getString(R.string.connectivity_dialog_title));
// builder.setMessage(getString(R.string.connectivity_dialog_message));
// builder.setNeutralButton(R.string.connectivity_dialog_button, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int id) {
// try {
// // In some cases, a matching Activity may not exist,so ensure you safeguard against this.
// startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
// } catch (ActivityNotFoundException ex) {
// startActivity(new Intent(Settings.ACTION_SETTINGS));
// }
// }
// });
//
// return builder.create();
// }
//
// public interface ConnectivityFragmentListener {
// public void onDialogCancelled();
// }
// }
//
// Path: app/src/main/java/wseemann/media/romote/utils/NetworkMonitor.java
// public class NetworkMonitor {
//
// private ConnectivityManager mCm;
// private WifiApManager mWifiApManager;
//
// public NetworkMonitor(Activity activity, int requestCode) {
// // Here, thisActivity is the current activity
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)
// != PackageManager.PERMISSION_GRANTED) {
// requestPermission(activity, requestCode);
// } else {
// mCm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
// mWifiApManager = new WifiApManager(activity);
// }
// }
//
// public boolean isConnectedToiWiFi() {
// if (mCm == null) {
// return false;
// }
//
// NetworkInfo activeNetwork = mCm.getActiveNetworkInfo();
//
// boolean isConnected = activeNetwork != null &&
// activeNetwork.isConnectedOrConnecting();
//
// if (isConnected) {
// return activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
// }
//
// return false;
// }
//
// public boolean isMobileAccessPointOn() {
// if (mWifiApManager == null) {
// return false;
// }
//
// return mWifiApManager.isWifiApEnabled();
// }
//
// private void requestPermission(Activity activity, int requestCode) {
// // Here, thisActivity is the current activity
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)
// != PackageManager.PERMISSION_GRANTED) {
//
// // Should we show an explanation?
// if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
// Manifest.permission.ACCESS_NETWORK_STATE)) {
//
// // Show an expanation to the user *asynchronously* -- don't block
// // this thread waiting for the user's response! After the user
// // sees the explanation, try again to request the permission.
//
// } else {
//
// // No explanation needed, we can request the permission.
//
// ActivityCompat.requestPermissions(activity,
// new String[]{Manifest.permission.ACCESS_NETWORK_STATE},
// requestCode);
//
// // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// // app-defined int constant. The callback method gets the
// // result of the request.
// }
// }
// }
// }
// Path: app/src/main/java/wseemann/media/romote/activity/ConnectivityActivity.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import wseemann.media.romote.fragment.ConnectivityDialog;
import wseemann.media.romote.utils.NetworkMonitor;
package wseemann.media.romote.activity;
/**
* Created by wseemann on 6/19/16.
*/
public class ConnectivityActivity extends ShakeActivity {
private static final int MY_PERMISSIONS_ACCESS_NETWORK_STATE = 100;
private ConnectivityDialog mDialog;
| private NetworkMonitor mNetworkMonitor; |
wseemann/RoMote | app/src/main/java/wseemann/media/romote/view/VibratingImageButton.java | // Path: app/src/main/java/wseemann/media/romote/utils/ViewUtils.java
// public class ViewUtils {
//
// private ViewUtils() {
//
// }
//
// public static void provideHapticFeedback(View view, int vibrateDurationMs) {
// if (PreferenceUtils.shouldProvideHapticFeedback(view.getContext())) {
// Vibrator vibe = (Vibrator) view.getContext().getSystemService(Context.VIBRATOR_SERVICE);
// vibe.vibrate(vibrateDurationMs);
// }
// }
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.appcompat.widget.AppCompatImageButton;
import wseemann.media.romote.utils.ViewUtils; | package wseemann.media.romote.view;
public class VibratingImageButton extends AppCompatImageButton {
private static final int VIBRATE_DURATION_MS = 100;
private View.OnClickListener mListener;
public VibratingImageButton(Context context) {
this(context, null);
}
public VibratingImageButton(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.buttonStyle);
}
public VibratingImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
super.setOnClickListener((View view) -> { | // Path: app/src/main/java/wseemann/media/romote/utils/ViewUtils.java
// public class ViewUtils {
//
// private ViewUtils() {
//
// }
//
// public static void provideHapticFeedback(View view, int vibrateDurationMs) {
// if (PreferenceUtils.shouldProvideHapticFeedback(view.getContext())) {
// Vibrator vibe = (Vibrator) view.getContext().getSystemService(Context.VIBRATOR_SERVICE);
// vibe.vibrate(vibrateDurationMs);
// }
// }
// }
// Path: app/src/main/java/wseemann/media/romote/view/VibratingImageButton.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.appcompat.widget.AppCompatImageButton;
import wseemann.media.romote.utils.ViewUtils;
package wseemann.media.romote.view;
public class VibratingImageButton extends AppCompatImageButton {
private static final int VIBRATE_DURATION_MS = 100;
private View.OnClickListener mListener;
public VibratingImageButton(Context context) {
this(context, null);
}
public VibratingImageButton(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.buttonStyle);
}
public VibratingImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
super.setOnClickListener((View view) -> { | ViewUtils.provideHapticFeedback(view, VIBRATE_DURATION_MS); |
dnbn/smbtv | app/src/main/java/com/smbtv/delegate/SMBConfigDelegate.java | // Path: app/src/main/java/com/smbtv/delegate/base/SMBConfigDAO.java
// public class SMBConfigDAO extends DAOBase {
//
// private static final String TAG = SMBConfigDAO.class.getSimpleName();
//
// private static Map<String, String> queries = XMLQueryLoader.load(R.xml.db_query_config);
//
// public SMBConfigDAO(Context pContext) {
// super(pContext);
// }
//
// public SMBConfig find() {
//
// Log.d(TAG, "find");
//
// SMBConfig config = null;
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("get_config");
// Cursor c = db.rawQuery(query);
//
// if (c.moveToFirst()) {
//
// config = new SMBConfig();
// config.setHostname(c.getString(0));
// config.setSharename(c.getString(1));
// config.setDomain(c.getString(2));
// config.setServerPort(c.getInt(3));
// config.setSessionPort(c.getInt(4));
// config.setDatagramPort(c.getInt(5));
// config.setTcpIpSmbPort(c.getInt(6));
//
// } else {
//
// throw new SMBConfigException("Cannot load the actual configuration.");
// }
// }
//
// return config;
// }
//
// public void update(SMBConfig config) {
//
//
// Log.d(TAG, "update");
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("update_config");
//
// db.addBinding("hostname", config.getHostname());
// db.addBinding("hostname", config.getHostname());
// db.addBinding("sharename", config.getSharename());
// db.addBinding("domain", config.getDomain());
// db.addBinding("serverport", Integer.toString(config.getServerPort()));
// db.addBinding("sessionport", Integer.toString(config.getSessionPort()));
// db.addBinding("datagramport", Integer.toString(config.getDatagramPort()));
// db.addBinding("smbport", Integer.toString(config.getTcpIpSmbPort()));
//
// db.execSQL(query);
// }
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/model/SMBConfig.java
// public class SMBConfig {
//
// private String hostname;
// private String sharename;
// private String domain;
// private int sessionPort;
// private int tcpIpSmbPort;
// private int serverPort;
// private int datagramPort;
//
// public String getHostname() {
// return hostname;
// }
//
// public void setHostname(String hostname) {
// this.hostname = hostname;
// }
//
// public String getSharename() {
// return sharename;
// }
//
// public void setSharename(String sharename) {
// this.sharename = sharename;
// }
//
// public String getDomain() {
// return domain;
// }
//
// public void setDomain(String domain) {
// this.domain = domain;
// }
//
// public int getSessionPort() {
// return sessionPort;
// }
//
// public void setSessionPort(int sessionPort) {
// this.sessionPort = sessionPort;
// }
//
// public int getTcpIpSmbPort() {
// return tcpIpSmbPort;
// }
//
// public void setTcpIpSmbPort(int tcpIpSmbPort) {
// this.tcpIpSmbPort = tcpIpSmbPort;
// }
//
// public int getServerPort() {
// return serverPort;
// }
//
// public void setServerPort(int serverPort) {
// this.serverPort = serverPort;
// }
//
// public int getDatagramPort() {
// return datagramPort;
// }
//
// public void setDatagramPort(int datagramPort) {
// this.datagramPort = datagramPort;
// }
//
// @Override
// public String toString() {
// return "SMBConfig{" +
// "hostname='" + hostname + '\'' +
// ", sharename='" + sharename + '\'' +
// ", domain='" + domain + '\'' +
// ", sessionPort=" + sessionPort +
// ", tcpIpSmbPort=" + tcpIpSmbPort +
// ", serverPort=" + serverPort +
// ", datagramPort=" + datagramPort +
// '}';
// }
//
// @Override
// public boolean equals(Object other) {
//
// SMBConfig c = (SMBConfig) other;
//
// return hostname.equals(c.hostname)
// && sharename.equals(c.sharename)
// && domain.equals(c.domain)
// && sessionPort == c.sessionPort
// && tcpIpSmbPort == c.tcpIpSmbPort
// && serverPort == c.serverPort
// && datagramPort == c.datagramPort;
// }
//
// }
| import android.content.Context;
import com.smbtv.delegate.base.SMBConfigDAO;
import com.smbtv.model.SMBConfig; | package com.smbtv.delegate;
public class SMBConfigDelegate {
private SMBConfigDAO mDao;
public SMBConfigDelegate() {
Context context = ApplicationDelegate.getContext();
this.mDao = new SMBConfigDAO(context);
}
| // Path: app/src/main/java/com/smbtv/delegate/base/SMBConfigDAO.java
// public class SMBConfigDAO extends DAOBase {
//
// private static final String TAG = SMBConfigDAO.class.getSimpleName();
//
// private static Map<String, String> queries = XMLQueryLoader.load(R.xml.db_query_config);
//
// public SMBConfigDAO(Context pContext) {
// super(pContext);
// }
//
// public SMBConfig find() {
//
// Log.d(TAG, "find");
//
// SMBConfig config = null;
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("get_config");
// Cursor c = db.rawQuery(query);
//
// if (c.moveToFirst()) {
//
// config = new SMBConfig();
// config.setHostname(c.getString(0));
// config.setSharename(c.getString(1));
// config.setDomain(c.getString(2));
// config.setServerPort(c.getInt(3));
// config.setSessionPort(c.getInt(4));
// config.setDatagramPort(c.getInt(5));
// config.setTcpIpSmbPort(c.getInt(6));
//
// } else {
//
// throw new SMBConfigException("Cannot load the actual configuration.");
// }
// }
//
// return config;
// }
//
// public void update(SMBConfig config) {
//
//
// Log.d(TAG, "update");
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("update_config");
//
// db.addBinding("hostname", config.getHostname());
// db.addBinding("hostname", config.getHostname());
// db.addBinding("sharename", config.getSharename());
// db.addBinding("domain", config.getDomain());
// db.addBinding("serverport", Integer.toString(config.getServerPort()));
// db.addBinding("sessionport", Integer.toString(config.getSessionPort()));
// db.addBinding("datagramport", Integer.toString(config.getDatagramPort()));
// db.addBinding("smbport", Integer.toString(config.getTcpIpSmbPort()));
//
// db.execSQL(query);
// }
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/model/SMBConfig.java
// public class SMBConfig {
//
// private String hostname;
// private String sharename;
// private String domain;
// private int sessionPort;
// private int tcpIpSmbPort;
// private int serverPort;
// private int datagramPort;
//
// public String getHostname() {
// return hostname;
// }
//
// public void setHostname(String hostname) {
// this.hostname = hostname;
// }
//
// public String getSharename() {
// return sharename;
// }
//
// public void setSharename(String sharename) {
// this.sharename = sharename;
// }
//
// public String getDomain() {
// return domain;
// }
//
// public void setDomain(String domain) {
// this.domain = domain;
// }
//
// public int getSessionPort() {
// return sessionPort;
// }
//
// public void setSessionPort(int sessionPort) {
// this.sessionPort = sessionPort;
// }
//
// public int getTcpIpSmbPort() {
// return tcpIpSmbPort;
// }
//
// public void setTcpIpSmbPort(int tcpIpSmbPort) {
// this.tcpIpSmbPort = tcpIpSmbPort;
// }
//
// public int getServerPort() {
// return serverPort;
// }
//
// public void setServerPort(int serverPort) {
// this.serverPort = serverPort;
// }
//
// public int getDatagramPort() {
// return datagramPort;
// }
//
// public void setDatagramPort(int datagramPort) {
// this.datagramPort = datagramPort;
// }
//
// @Override
// public String toString() {
// return "SMBConfig{" +
// "hostname='" + hostname + '\'' +
// ", sharename='" + sharename + '\'' +
// ", domain='" + domain + '\'' +
// ", sessionPort=" + sessionPort +
// ", tcpIpSmbPort=" + tcpIpSmbPort +
// ", serverPort=" + serverPort +
// ", datagramPort=" + datagramPort +
// '}';
// }
//
// @Override
// public boolean equals(Object other) {
//
// SMBConfig c = (SMBConfig) other;
//
// return hostname.equals(c.hostname)
// && sharename.equals(c.sharename)
// && domain.equals(c.domain)
// && sessionPort == c.sessionPort
// && tcpIpSmbPort == c.tcpIpSmbPort
// && serverPort == c.serverPort
// && datagramPort == c.datagramPort;
// }
//
// }
// Path: app/src/main/java/com/smbtv/delegate/SMBConfigDelegate.java
import android.content.Context;
import com.smbtv.delegate.base.SMBConfigDAO;
import com.smbtv.model.SMBConfig;
package com.smbtv.delegate;
public class SMBConfigDelegate {
private SMBConfigDAO mDao;
public SMBConfigDelegate() {
Context context = ApplicationDelegate.getContext();
this.mDao = new SMBConfigDAO(context);
}
| public SMBConfig get() { |
dnbn/smbtv | app/src/main/java/com/smbtv/service/SMBTVService.java | // Path: app/src/main/java/com/smbtv/delegate/SMBServerDelegate.java
// public class SMBServerDelegate {
//
// private static final String TAG = SMBServerDelegate.class.getName();
// private static SMBServerDelegate INSTANCE = null;
//
// private PersistentServerConfiguration mCfg;
// private SMBServer mSmbServer;
// private InternalServerListener mSMBListener;
// private int mSMBServerState = -1;
//
// private SMBServerDelegate() {
//
// try {
// mCfg = new PersistentServerConfiguration();
// } catch (Exception e) {
//
// Log.e(TAG, Log.getStackTraceString(e));
// throw new ServiceInstancationException(e);
// }
// }
//
// public static SMBServerDelegate getInstance() {
//
// if (INSTANCE == null) {
// INSTANCE = new SMBServerDelegate();
// }
// return INSTANCE;
// }
//
// public void startServer(ServerListener listener) {
//
// try {
// mSMBListener = new InternalServerListener(listener);
//
// NetBIOSNameServer netBIOSNameServer = new NetBIOSNameServer(mCfg);
//
// mCfg.addServer(netBIOSNameServer);
// mSmbServer = new SMBServer(mCfg);
// mCfg.addServer(mSmbServer);
//
// mSmbServer.addServerListener(mSMBListener);
//
// for (int i = 0; i < mCfg.numberOfServers(); i++) {
// NetworkServer server = mCfg.getServer(i);
// server.startServer();
// }
//
// } catch (Exception e) {
//
// Log.e(TAG, Log.getStackTraceString(e));
// throw new ServiceInstancationException(e);
// }
// }
//
// public ServerInfo getServerInfo() {
//
// ServerInfo serverInfo = new ServerInfo();
//
// serverInfo.setName(mSmbServer.getServerName());
// serverInfo.setPort(mSmbServer.getCIFSConfiguration().getTcpipSMBPort());
// serverInfo.setDomain(mSmbServer.getCIFSConfiguration().getDomainName());
// serverInfo.setAddresses(mSmbServer.getServerAddresses());
//
// return serverInfo;
// }
//
// public boolean isServerStarting() {
//
// return mSMBServerState == ServerListener.ServerStartup;
// }
//
// public boolean isServerActive() {
//
// return mSmbServer != null && mSmbServer.isActive();
// }
//
// public void restartServer() {
//
// ServerListener listener = null;
//
// if (isServerActive()) {
// stopServer();
// listener = mSMBListener;
// }
//
// startServer(listener);
// }
//
// public void stopServer() {
//
// for (int i = 0; i < mCfg.numberOfServers(); i++) {
// NetworkServer server = mCfg.getServer(i);
// server.shutdownServer(true);
// }
// }
//
// public void registerShare(SMBShare share) {
//
// mCfg.registerShare(share);
// }
//
// public void removeShare(SMBShare share) {
//
// mCfg.unregisterShare(share);
// }
//
// public void renameShare(int id, String newName) {
//
// mCfg.renameShare(id, newName);
// }
//
// private class InternalServerListener implements ServerListener {
//
// private ServerListener mDelegate;
//
// public InternalServerListener(ServerListener listener) {
//
// this.mDelegate = listener;
// }
//
// @Override
// public void serverStatusEvent(NetworkServer networkServer, int state) {
//
// mSMBServerState = state;
//
// if (this.mDelegate != null) {
// this.mDelegate.serverStatusEvent(networkServer, state);
// }
// }
// }
// }
| import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import com.smbtv.delegate.SMBServerDelegate; | package com.smbtv.service;
public class SMBTVService extends Service {
private static final String TAG = SMBTVService.class.getName();
private IBinder mBinder; | // Path: app/src/main/java/com/smbtv/delegate/SMBServerDelegate.java
// public class SMBServerDelegate {
//
// private static final String TAG = SMBServerDelegate.class.getName();
// private static SMBServerDelegate INSTANCE = null;
//
// private PersistentServerConfiguration mCfg;
// private SMBServer mSmbServer;
// private InternalServerListener mSMBListener;
// private int mSMBServerState = -1;
//
// private SMBServerDelegate() {
//
// try {
// mCfg = new PersistentServerConfiguration();
// } catch (Exception e) {
//
// Log.e(TAG, Log.getStackTraceString(e));
// throw new ServiceInstancationException(e);
// }
// }
//
// public static SMBServerDelegate getInstance() {
//
// if (INSTANCE == null) {
// INSTANCE = new SMBServerDelegate();
// }
// return INSTANCE;
// }
//
// public void startServer(ServerListener listener) {
//
// try {
// mSMBListener = new InternalServerListener(listener);
//
// NetBIOSNameServer netBIOSNameServer = new NetBIOSNameServer(mCfg);
//
// mCfg.addServer(netBIOSNameServer);
// mSmbServer = new SMBServer(mCfg);
// mCfg.addServer(mSmbServer);
//
// mSmbServer.addServerListener(mSMBListener);
//
// for (int i = 0; i < mCfg.numberOfServers(); i++) {
// NetworkServer server = mCfg.getServer(i);
// server.startServer();
// }
//
// } catch (Exception e) {
//
// Log.e(TAG, Log.getStackTraceString(e));
// throw new ServiceInstancationException(e);
// }
// }
//
// public ServerInfo getServerInfo() {
//
// ServerInfo serverInfo = new ServerInfo();
//
// serverInfo.setName(mSmbServer.getServerName());
// serverInfo.setPort(mSmbServer.getCIFSConfiguration().getTcpipSMBPort());
// serverInfo.setDomain(mSmbServer.getCIFSConfiguration().getDomainName());
// serverInfo.setAddresses(mSmbServer.getServerAddresses());
//
// return serverInfo;
// }
//
// public boolean isServerStarting() {
//
// return mSMBServerState == ServerListener.ServerStartup;
// }
//
// public boolean isServerActive() {
//
// return mSmbServer != null && mSmbServer.isActive();
// }
//
// public void restartServer() {
//
// ServerListener listener = null;
//
// if (isServerActive()) {
// stopServer();
// listener = mSMBListener;
// }
//
// startServer(listener);
// }
//
// public void stopServer() {
//
// for (int i = 0; i < mCfg.numberOfServers(); i++) {
// NetworkServer server = mCfg.getServer(i);
// server.shutdownServer(true);
// }
// }
//
// public void registerShare(SMBShare share) {
//
// mCfg.registerShare(share);
// }
//
// public void removeShare(SMBShare share) {
//
// mCfg.unregisterShare(share);
// }
//
// public void renameShare(int id, String newName) {
//
// mCfg.renameShare(id, newName);
// }
//
// private class InternalServerListener implements ServerListener {
//
// private ServerListener mDelegate;
//
// public InternalServerListener(ServerListener listener) {
//
// this.mDelegate = listener;
// }
//
// @Override
// public void serverStatusEvent(NetworkServer networkServer, int state) {
//
// mSMBServerState = state;
//
// if (this.mDelegate != null) {
// this.mDelegate.serverStatusEvent(networkServer, state);
// }
// }
// }
// }
// Path: app/src/main/java/com/smbtv/service/SMBTVService.java
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import com.smbtv.delegate.SMBServerDelegate;
package com.smbtv.service;
public class SMBTVService extends Service {
private static final String TAG = SMBTVService.class.getName();
private IBinder mBinder; | private SMBServerDelegate mSmbService; |
dnbn/smbtv | app/src/main/java/com/smbtv/ui/activity/RestartServerDialogActivity.java | // Path: app/src/main/java/com/smbtv/delegate/SMBServerDelegate.java
// public class SMBServerDelegate {
//
// private static final String TAG = SMBServerDelegate.class.getName();
// private static SMBServerDelegate INSTANCE = null;
//
// private PersistentServerConfiguration mCfg;
// private SMBServer mSmbServer;
// private InternalServerListener mSMBListener;
// private int mSMBServerState = -1;
//
// private SMBServerDelegate() {
//
// try {
// mCfg = new PersistentServerConfiguration();
// } catch (Exception e) {
//
// Log.e(TAG, Log.getStackTraceString(e));
// throw new ServiceInstancationException(e);
// }
// }
//
// public static SMBServerDelegate getInstance() {
//
// if (INSTANCE == null) {
// INSTANCE = new SMBServerDelegate();
// }
// return INSTANCE;
// }
//
// public void startServer(ServerListener listener) {
//
// try {
// mSMBListener = new InternalServerListener(listener);
//
// NetBIOSNameServer netBIOSNameServer = new NetBIOSNameServer(mCfg);
//
// mCfg.addServer(netBIOSNameServer);
// mSmbServer = new SMBServer(mCfg);
// mCfg.addServer(mSmbServer);
//
// mSmbServer.addServerListener(mSMBListener);
//
// for (int i = 0; i < mCfg.numberOfServers(); i++) {
// NetworkServer server = mCfg.getServer(i);
// server.startServer();
// }
//
// } catch (Exception e) {
//
// Log.e(TAG, Log.getStackTraceString(e));
// throw new ServiceInstancationException(e);
// }
// }
//
// public ServerInfo getServerInfo() {
//
// ServerInfo serverInfo = new ServerInfo();
//
// serverInfo.setName(mSmbServer.getServerName());
// serverInfo.setPort(mSmbServer.getCIFSConfiguration().getTcpipSMBPort());
// serverInfo.setDomain(mSmbServer.getCIFSConfiguration().getDomainName());
// serverInfo.setAddresses(mSmbServer.getServerAddresses());
//
// return serverInfo;
// }
//
// public boolean isServerStarting() {
//
// return mSMBServerState == ServerListener.ServerStartup;
// }
//
// public boolean isServerActive() {
//
// return mSmbServer != null && mSmbServer.isActive();
// }
//
// public void restartServer() {
//
// ServerListener listener = null;
//
// if (isServerActive()) {
// stopServer();
// listener = mSMBListener;
// }
//
// startServer(listener);
// }
//
// public void stopServer() {
//
// for (int i = 0; i < mCfg.numberOfServers(); i++) {
// NetworkServer server = mCfg.getServer(i);
// server.shutdownServer(true);
// }
// }
//
// public void registerShare(SMBShare share) {
//
// mCfg.registerShare(share);
// }
//
// public void removeShare(SMBShare share) {
//
// mCfg.unregisterShare(share);
// }
//
// public void renameShare(int id, String newName) {
//
// mCfg.renameShare(id, newName);
// }
//
// private class InternalServerListener implements ServerListener {
//
// private ServerListener mDelegate;
//
// public InternalServerListener(ServerListener listener) {
//
// this.mDelegate = listener;
// }
//
// @Override
// public void serverStatusEvent(NetworkServer networkServer, int state) {
//
// mSMBServerState = state;
//
// if (this.mDelegate != null) {
// this.mDelegate.serverStatusEvent(networkServer, state);
// }
// }
// }
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
| import android.util.Log;
import com.smbtv.R;
import com.smbtv.delegate.SMBServerDelegate;
import com.smbtv.ui.components.DialogConfig; | package com.smbtv.ui.activity;
public class RestartServerDialogActivity extends GenericDialogActivity {
private static final String TAG = RestartServerDialogActivity.class.getName();
| // Path: app/src/main/java/com/smbtv/delegate/SMBServerDelegate.java
// public class SMBServerDelegate {
//
// private static final String TAG = SMBServerDelegate.class.getName();
// private static SMBServerDelegate INSTANCE = null;
//
// private PersistentServerConfiguration mCfg;
// private SMBServer mSmbServer;
// private InternalServerListener mSMBListener;
// private int mSMBServerState = -1;
//
// private SMBServerDelegate() {
//
// try {
// mCfg = new PersistentServerConfiguration();
// } catch (Exception e) {
//
// Log.e(TAG, Log.getStackTraceString(e));
// throw new ServiceInstancationException(e);
// }
// }
//
// public static SMBServerDelegate getInstance() {
//
// if (INSTANCE == null) {
// INSTANCE = new SMBServerDelegate();
// }
// return INSTANCE;
// }
//
// public void startServer(ServerListener listener) {
//
// try {
// mSMBListener = new InternalServerListener(listener);
//
// NetBIOSNameServer netBIOSNameServer = new NetBIOSNameServer(mCfg);
//
// mCfg.addServer(netBIOSNameServer);
// mSmbServer = new SMBServer(mCfg);
// mCfg.addServer(mSmbServer);
//
// mSmbServer.addServerListener(mSMBListener);
//
// for (int i = 0; i < mCfg.numberOfServers(); i++) {
// NetworkServer server = mCfg.getServer(i);
// server.startServer();
// }
//
// } catch (Exception e) {
//
// Log.e(TAG, Log.getStackTraceString(e));
// throw new ServiceInstancationException(e);
// }
// }
//
// public ServerInfo getServerInfo() {
//
// ServerInfo serverInfo = new ServerInfo();
//
// serverInfo.setName(mSmbServer.getServerName());
// serverInfo.setPort(mSmbServer.getCIFSConfiguration().getTcpipSMBPort());
// serverInfo.setDomain(mSmbServer.getCIFSConfiguration().getDomainName());
// serverInfo.setAddresses(mSmbServer.getServerAddresses());
//
// return serverInfo;
// }
//
// public boolean isServerStarting() {
//
// return mSMBServerState == ServerListener.ServerStartup;
// }
//
// public boolean isServerActive() {
//
// return mSmbServer != null && mSmbServer.isActive();
// }
//
// public void restartServer() {
//
// ServerListener listener = null;
//
// if (isServerActive()) {
// stopServer();
// listener = mSMBListener;
// }
//
// startServer(listener);
// }
//
// public void stopServer() {
//
// for (int i = 0; i < mCfg.numberOfServers(); i++) {
// NetworkServer server = mCfg.getServer(i);
// server.shutdownServer(true);
// }
// }
//
// public void registerShare(SMBShare share) {
//
// mCfg.registerShare(share);
// }
//
// public void removeShare(SMBShare share) {
//
// mCfg.unregisterShare(share);
// }
//
// public void renameShare(int id, String newName) {
//
// mCfg.renameShare(id, newName);
// }
//
// private class InternalServerListener implements ServerListener {
//
// private ServerListener mDelegate;
//
// public InternalServerListener(ServerListener listener) {
//
// this.mDelegate = listener;
// }
//
// @Override
// public void serverStatusEvent(NetworkServer networkServer, int state) {
//
// mSMBServerState = state;
//
// if (this.mDelegate != null) {
// this.mDelegate.serverStatusEvent(networkServer, state);
// }
// }
// }
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
// Path: app/src/main/java/com/smbtv/ui/activity/RestartServerDialogActivity.java
import android.util.Log;
import com.smbtv.R;
import com.smbtv.delegate.SMBServerDelegate;
import com.smbtv.ui.components.DialogConfig;
package com.smbtv.ui.activity;
public class RestartServerDialogActivity extends GenericDialogActivity {
private static final String TAG = RestartServerDialogActivity.class.getName();
| private DialogConfig.DialogItem mItemRestart; |
dnbn/smbtv | app/src/main/java/com/smbtv/delegate/base/SMBConfigDAO.java | // Path: app/src/main/java/com/smbtv/delegate/exception/SMBConfigException.java
// public class SMBConfigException extends RuntimeException {
//
// public SMBConfigException(String message) {
// super(message);
// }
// }
//
// Path: app/src/main/java/com/smbtv/model/SMBConfig.java
// public class SMBConfig {
//
// private String hostname;
// private String sharename;
// private String domain;
// private int sessionPort;
// private int tcpIpSmbPort;
// private int serverPort;
// private int datagramPort;
//
// public String getHostname() {
// return hostname;
// }
//
// public void setHostname(String hostname) {
// this.hostname = hostname;
// }
//
// public String getSharename() {
// return sharename;
// }
//
// public void setSharename(String sharename) {
// this.sharename = sharename;
// }
//
// public String getDomain() {
// return domain;
// }
//
// public void setDomain(String domain) {
// this.domain = domain;
// }
//
// public int getSessionPort() {
// return sessionPort;
// }
//
// public void setSessionPort(int sessionPort) {
// this.sessionPort = sessionPort;
// }
//
// public int getTcpIpSmbPort() {
// return tcpIpSmbPort;
// }
//
// public void setTcpIpSmbPort(int tcpIpSmbPort) {
// this.tcpIpSmbPort = tcpIpSmbPort;
// }
//
// public int getServerPort() {
// return serverPort;
// }
//
// public void setServerPort(int serverPort) {
// this.serverPort = serverPort;
// }
//
// public int getDatagramPort() {
// return datagramPort;
// }
//
// public void setDatagramPort(int datagramPort) {
// this.datagramPort = datagramPort;
// }
//
// @Override
// public String toString() {
// return "SMBConfig{" +
// "hostname='" + hostname + '\'' +
// ", sharename='" + sharename + '\'' +
// ", domain='" + domain + '\'' +
// ", sessionPort=" + sessionPort +
// ", tcpIpSmbPort=" + tcpIpSmbPort +
// ", serverPort=" + serverPort +
// ", datagramPort=" + datagramPort +
// '}';
// }
//
// @Override
// public boolean equals(Object other) {
//
// SMBConfig c = (SMBConfig) other;
//
// return hostname.equals(c.hostname)
// && sharename.equals(c.sharename)
// && domain.equals(c.domain)
// && sessionPort == c.sessionPort
// && tcpIpSmbPort == c.tcpIpSmbPort
// && serverPort == c.serverPort
// && datagramPort == c.datagramPort;
// }
//
// }
| import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.delegate.exception.SMBConfigException;
import com.smbtv.model.SMBConfig;
import java.util.Map; | package com.smbtv.delegate.base;
public class SMBConfigDAO extends DAOBase {
private static final String TAG = SMBConfigDAO.class.getSimpleName();
private static Map<String, String> queries = XMLQueryLoader.load(R.xml.db_query_config);
public SMBConfigDAO(Context pContext) {
super(pContext);
}
| // Path: app/src/main/java/com/smbtv/delegate/exception/SMBConfigException.java
// public class SMBConfigException extends RuntimeException {
//
// public SMBConfigException(String message) {
// super(message);
// }
// }
//
// Path: app/src/main/java/com/smbtv/model/SMBConfig.java
// public class SMBConfig {
//
// private String hostname;
// private String sharename;
// private String domain;
// private int sessionPort;
// private int tcpIpSmbPort;
// private int serverPort;
// private int datagramPort;
//
// public String getHostname() {
// return hostname;
// }
//
// public void setHostname(String hostname) {
// this.hostname = hostname;
// }
//
// public String getSharename() {
// return sharename;
// }
//
// public void setSharename(String sharename) {
// this.sharename = sharename;
// }
//
// public String getDomain() {
// return domain;
// }
//
// public void setDomain(String domain) {
// this.domain = domain;
// }
//
// public int getSessionPort() {
// return sessionPort;
// }
//
// public void setSessionPort(int sessionPort) {
// this.sessionPort = sessionPort;
// }
//
// public int getTcpIpSmbPort() {
// return tcpIpSmbPort;
// }
//
// public void setTcpIpSmbPort(int tcpIpSmbPort) {
// this.tcpIpSmbPort = tcpIpSmbPort;
// }
//
// public int getServerPort() {
// return serverPort;
// }
//
// public void setServerPort(int serverPort) {
// this.serverPort = serverPort;
// }
//
// public int getDatagramPort() {
// return datagramPort;
// }
//
// public void setDatagramPort(int datagramPort) {
// this.datagramPort = datagramPort;
// }
//
// @Override
// public String toString() {
// return "SMBConfig{" +
// "hostname='" + hostname + '\'' +
// ", sharename='" + sharename + '\'' +
// ", domain='" + domain + '\'' +
// ", sessionPort=" + sessionPort +
// ", tcpIpSmbPort=" + tcpIpSmbPort +
// ", serverPort=" + serverPort +
// ", datagramPort=" + datagramPort +
// '}';
// }
//
// @Override
// public boolean equals(Object other) {
//
// SMBConfig c = (SMBConfig) other;
//
// return hostname.equals(c.hostname)
// && sharename.equals(c.sharename)
// && domain.equals(c.domain)
// && sessionPort == c.sessionPort
// && tcpIpSmbPort == c.tcpIpSmbPort
// && serverPort == c.serverPort
// && datagramPort == c.datagramPort;
// }
//
// }
// Path: app/src/main/java/com/smbtv/delegate/base/SMBConfigDAO.java
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.delegate.exception.SMBConfigException;
import com.smbtv.model.SMBConfig;
import java.util.Map;
package com.smbtv.delegate.base;
public class SMBConfigDAO extends DAOBase {
private static final String TAG = SMBConfigDAO.class.getSimpleName();
private static Map<String, String> queries = XMLQueryLoader.load(R.xml.db_query_config);
public SMBConfigDAO(Context pContext) {
super(pContext);
}
| public SMBConfig find() { |
dnbn/smbtv | app/src/main/java/com/smbtv/delegate/base/SMBConfigDAO.java | // Path: app/src/main/java/com/smbtv/delegate/exception/SMBConfigException.java
// public class SMBConfigException extends RuntimeException {
//
// public SMBConfigException(String message) {
// super(message);
// }
// }
//
// Path: app/src/main/java/com/smbtv/model/SMBConfig.java
// public class SMBConfig {
//
// private String hostname;
// private String sharename;
// private String domain;
// private int sessionPort;
// private int tcpIpSmbPort;
// private int serverPort;
// private int datagramPort;
//
// public String getHostname() {
// return hostname;
// }
//
// public void setHostname(String hostname) {
// this.hostname = hostname;
// }
//
// public String getSharename() {
// return sharename;
// }
//
// public void setSharename(String sharename) {
// this.sharename = sharename;
// }
//
// public String getDomain() {
// return domain;
// }
//
// public void setDomain(String domain) {
// this.domain = domain;
// }
//
// public int getSessionPort() {
// return sessionPort;
// }
//
// public void setSessionPort(int sessionPort) {
// this.sessionPort = sessionPort;
// }
//
// public int getTcpIpSmbPort() {
// return tcpIpSmbPort;
// }
//
// public void setTcpIpSmbPort(int tcpIpSmbPort) {
// this.tcpIpSmbPort = tcpIpSmbPort;
// }
//
// public int getServerPort() {
// return serverPort;
// }
//
// public void setServerPort(int serverPort) {
// this.serverPort = serverPort;
// }
//
// public int getDatagramPort() {
// return datagramPort;
// }
//
// public void setDatagramPort(int datagramPort) {
// this.datagramPort = datagramPort;
// }
//
// @Override
// public String toString() {
// return "SMBConfig{" +
// "hostname='" + hostname + '\'' +
// ", sharename='" + sharename + '\'' +
// ", domain='" + domain + '\'' +
// ", sessionPort=" + sessionPort +
// ", tcpIpSmbPort=" + tcpIpSmbPort +
// ", serverPort=" + serverPort +
// ", datagramPort=" + datagramPort +
// '}';
// }
//
// @Override
// public boolean equals(Object other) {
//
// SMBConfig c = (SMBConfig) other;
//
// return hostname.equals(c.hostname)
// && sharename.equals(c.sharename)
// && domain.equals(c.domain)
// && sessionPort == c.sessionPort
// && tcpIpSmbPort == c.tcpIpSmbPort
// && serverPort == c.serverPort
// && datagramPort == c.datagramPort;
// }
//
// }
| import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.delegate.exception.SMBConfigException;
import com.smbtv.model.SMBConfig;
import java.util.Map; | package com.smbtv.delegate.base;
public class SMBConfigDAO extends DAOBase {
private static final String TAG = SMBConfigDAO.class.getSimpleName();
private static Map<String, String> queries = XMLQueryLoader.load(R.xml.db_query_config);
public SMBConfigDAO(Context pContext) {
super(pContext);
}
public SMBConfig find() {
Log.d(TAG, "find");
SMBConfig config = null;
try (DBWrapper db = instanceDB()) {
String query = queries.get("get_config");
Cursor c = db.rawQuery(query);
if (c.moveToFirst()) {
config = new SMBConfig();
config.setHostname(c.getString(0));
config.setSharename(c.getString(1));
config.setDomain(c.getString(2));
config.setServerPort(c.getInt(3));
config.setSessionPort(c.getInt(4));
config.setDatagramPort(c.getInt(5));
config.setTcpIpSmbPort(c.getInt(6));
} else {
| // Path: app/src/main/java/com/smbtv/delegate/exception/SMBConfigException.java
// public class SMBConfigException extends RuntimeException {
//
// public SMBConfigException(String message) {
// super(message);
// }
// }
//
// Path: app/src/main/java/com/smbtv/model/SMBConfig.java
// public class SMBConfig {
//
// private String hostname;
// private String sharename;
// private String domain;
// private int sessionPort;
// private int tcpIpSmbPort;
// private int serverPort;
// private int datagramPort;
//
// public String getHostname() {
// return hostname;
// }
//
// public void setHostname(String hostname) {
// this.hostname = hostname;
// }
//
// public String getSharename() {
// return sharename;
// }
//
// public void setSharename(String sharename) {
// this.sharename = sharename;
// }
//
// public String getDomain() {
// return domain;
// }
//
// public void setDomain(String domain) {
// this.domain = domain;
// }
//
// public int getSessionPort() {
// return sessionPort;
// }
//
// public void setSessionPort(int sessionPort) {
// this.sessionPort = sessionPort;
// }
//
// public int getTcpIpSmbPort() {
// return tcpIpSmbPort;
// }
//
// public void setTcpIpSmbPort(int tcpIpSmbPort) {
// this.tcpIpSmbPort = tcpIpSmbPort;
// }
//
// public int getServerPort() {
// return serverPort;
// }
//
// public void setServerPort(int serverPort) {
// this.serverPort = serverPort;
// }
//
// public int getDatagramPort() {
// return datagramPort;
// }
//
// public void setDatagramPort(int datagramPort) {
// this.datagramPort = datagramPort;
// }
//
// @Override
// public String toString() {
// return "SMBConfig{" +
// "hostname='" + hostname + '\'' +
// ", sharename='" + sharename + '\'' +
// ", domain='" + domain + '\'' +
// ", sessionPort=" + sessionPort +
// ", tcpIpSmbPort=" + tcpIpSmbPort +
// ", serverPort=" + serverPort +
// ", datagramPort=" + datagramPort +
// '}';
// }
//
// @Override
// public boolean equals(Object other) {
//
// SMBConfig c = (SMBConfig) other;
//
// return hostname.equals(c.hostname)
// && sharename.equals(c.sharename)
// && domain.equals(c.domain)
// && sessionPort == c.sessionPort
// && tcpIpSmbPort == c.tcpIpSmbPort
// && serverPort == c.serverPort
// && datagramPort == c.datagramPort;
// }
//
// }
// Path: app/src/main/java/com/smbtv/delegate/base/SMBConfigDAO.java
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.delegate.exception.SMBConfigException;
import com.smbtv.model.SMBConfig;
import java.util.Map;
package com.smbtv.delegate.base;
public class SMBConfigDAO extends DAOBase {
private static final String TAG = SMBConfigDAO.class.getSimpleName();
private static Map<String, String> queries = XMLQueryLoader.load(R.xml.db_query_config);
public SMBConfigDAO(Context pContext) {
super(pContext);
}
public SMBConfig find() {
Log.d(TAG, "find");
SMBConfig config = null;
try (DBWrapper db = instanceDB()) {
String query = queries.get("get_config");
Cursor c = db.rawQuery(query);
if (c.moveToFirst()) {
config = new SMBConfig();
config.setHostname(c.getString(0));
config.setSharename(c.getString(1));
config.setDomain(c.getString(2));
config.setServerPort(c.getInt(3));
config.setSessionPort(c.getInt(4));
config.setDatagramPort(c.getInt(5));
config.setTcpIpSmbPort(c.getInt(6));
} else {
| throw new SMBConfigException("Cannot load the actual configuration."); |
dnbn/smbtv | app/src/main/java/com/smbtv/ui/activity/GenericDialogActivity.java | // Path: app/src/main/java/com/smbtv/ui/activity/fragment/DialogFragment.java
// public class DialogFragment extends GuidedStepFragment {
//
// private static final String TAG = DialogFragment.class.getName();
//
// private DialogConfig mConfig;
// private DialogHandler mHandler;
//
// public void setConfig(DialogConfig config) {
// this.mConfig = config;
// }
//
// public void setHandler(DialogHandler mHandler) {
// this.mHandler = mHandler;
// }
//
// @NonNull
// @Override
// public GuidanceStylist.Guidance onCreateGuidance(Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateGuidance");
//
// Drawable icon = getActivity().getDrawable(R.drawable.ic_warning);
// return new GuidanceStylist.Guidance(mConfig.getTitle(), mConfig.getDescription(), mConfig.getBeatcrumb(), icon);
// }
//
// @Override
// public void onCreateActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateActions");
//
// for (DialogConfig.DialogItem item : mConfig.getItems()) {
// actions.add(GuidedActionBuilder.text(item.getId(), item.getTitle(), item.getDescription()));
// }
// }
//
// @Override
// public void onGuidedActionClicked(GuidedAction action) {
//
// Log.d(TAG, "onGuidedActionClicked");
//
// for (DialogConfig.DialogItem item : mConfig.getItems()) {
// if (item.getId() == action.getId()) {
// mHandler.onSelection(item);
// break;
// }
// }
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/ui/activity/handler/DialogHandler.java
// public interface DialogHandler {
//
// void onSelection(DialogConfig.DialogItem itemSelected);
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import android.support.v17.leanback.app.GuidedStepFragment;
import com.smbtv.R;
import com.smbtv.ui.activity.fragment.DialogFragment;
import com.smbtv.ui.activity.handler.DialogHandler;
import com.smbtv.ui.components.DialogConfig; | package com.smbtv.ui.activity;
public abstract class GenericDialogActivity extends Activity implements DialogHandler {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
if (null == savedInstanceState) {
| // Path: app/src/main/java/com/smbtv/ui/activity/fragment/DialogFragment.java
// public class DialogFragment extends GuidedStepFragment {
//
// private static final String TAG = DialogFragment.class.getName();
//
// private DialogConfig mConfig;
// private DialogHandler mHandler;
//
// public void setConfig(DialogConfig config) {
// this.mConfig = config;
// }
//
// public void setHandler(DialogHandler mHandler) {
// this.mHandler = mHandler;
// }
//
// @NonNull
// @Override
// public GuidanceStylist.Guidance onCreateGuidance(Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateGuidance");
//
// Drawable icon = getActivity().getDrawable(R.drawable.ic_warning);
// return new GuidanceStylist.Guidance(mConfig.getTitle(), mConfig.getDescription(), mConfig.getBeatcrumb(), icon);
// }
//
// @Override
// public void onCreateActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateActions");
//
// for (DialogConfig.DialogItem item : mConfig.getItems()) {
// actions.add(GuidedActionBuilder.text(item.getId(), item.getTitle(), item.getDescription()));
// }
// }
//
// @Override
// public void onGuidedActionClicked(GuidedAction action) {
//
// Log.d(TAG, "onGuidedActionClicked");
//
// for (DialogConfig.DialogItem item : mConfig.getItems()) {
// if (item.getId() == action.getId()) {
// mHandler.onSelection(item);
// break;
// }
// }
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/ui/activity/handler/DialogHandler.java
// public interface DialogHandler {
//
// void onSelection(DialogConfig.DialogItem itemSelected);
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
// Path: app/src/main/java/com/smbtv/ui/activity/GenericDialogActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v17.leanback.app.GuidedStepFragment;
import com.smbtv.R;
import com.smbtv.ui.activity.fragment.DialogFragment;
import com.smbtv.ui.activity.handler.DialogHandler;
import com.smbtv.ui.components.DialogConfig;
package com.smbtv.ui.activity;
public abstract class GenericDialogActivity extends Activity implements DialogHandler {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
if (null == savedInstanceState) {
| DialogFragment fragment = new DialogFragment(); |
dnbn/smbtv | app/src/main/java/com/smbtv/ui/activity/GenericDialogActivity.java | // Path: app/src/main/java/com/smbtv/ui/activity/fragment/DialogFragment.java
// public class DialogFragment extends GuidedStepFragment {
//
// private static final String TAG = DialogFragment.class.getName();
//
// private DialogConfig mConfig;
// private DialogHandler mHandler;
//
// public void setConfig(DialogConfig config) {
// this.mConfig = config;
// }
//
// public void setHandler(DialogHandler mHandler) {
// this.mHandler = mHandler;
// }
//
// @NonNull
// @Override
// public GuidanceStylist.Guidance onCreateGuidance(Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateGuidance");
//
// Drawable icon = getActivity().getDrawable(R.drawable.ic_warning);
// return new GuidanceStylist.Guidance(mConfig.getTitle(), mConfig.getDescription(), mConfig.getBeatcrumb(), icon);
// }
//
// @Override
// public void onCreateActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateActions");
//
// for (DialogConfig.DialogItem item : mConfig.getItems()) {
// actions.add(GuidedActionBuilder.text(item.getId(), item.getTitle(), item.getDescription()));
// }
// }
//
// @Override
// public void onGuidedActionClicked(GuidedAction action) {
//
// Log.d(TAG, "onGuidedActionClicked");
//
// for (DialogConfig.DialogItem item : mConfig.getItems()) {
// if (item.getId() == action.getId()) {
// mHandler.onSelection(item);
// break;
// }
// }
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/ui/activity/handler/DialogHandler.java
// public interface DialogHandler {
//
// void onSelection(DialogConfig.DialogItem itemSelected);
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import android.support.v17.leanback.app.GuidedStepFragment;
import com.smbtv.R;
import com.smbtv.ui.activity.fragment.DialogFragment;
import com.smbtv.ui.activity.handler.DialogHandler;
import com.smbtv.ui.components.DialogConfig; | package com.smbtv.ui.activity;
public abstract class GenericDialogActivity extends Activity implements DialogHandler {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
if (null == savedInstanceState) {
DialogFragment fragment = new DialogFragment();
fragment.setConfig(createDialog());
fragment.setHandler(this);
GuidedStepFragment.add(getFragmentManager(), fragment);
}
}
| // Path: app/src/main/java/com/smbtv/ui/activity/fragment/DialogFragment.java
// public class DialogFragment extends GuidedStepFragment {
//
// private static final String TAG = DialogFragment.class.getName();
//
// private DialogConfig mConfig;
// private DialogHandler mHandler;
//
// public void setConfig(DialogConfig config) {
// this.mConfig = config;
// }
//
// public void setHandler(DialogHandler mHandler) {
// this.mHandler = mHandler;
// }
//
// @NonNull
// @Override
// public GuidanceStylist.Guidance onCreateGuidance(Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateGuidance");
//
// Drawable icon = getActivity().getDrawable(R.drawable.ic_warning);
// return new GuidanceStylist.Guidance(mConfig.getTitle(), mConfig.getDescription(), mConfig.getBeatcrumb(), icon);
// }
//
// @Override
// public void onCreateActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateActions");
//
// for (DialogConfig.DialogItem item : mConfig.getItems()) {
// actions.add(GuidedActionBuilder.text(item.getId(), item.getTitle(), item.getDescription()));
// }
// }
//
// @Override
// public void onGuidedActionClicked(GuidedAction action) {
//
// Log.d(TAG, "onGuidedActionClicked");
//
// for (DialogConfig.DialogItem item : mConfig.getItems()) {
// if (item.getId() == action.getId()) {
// mHandler.onSelection(item);
// break;
// }
// }
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/ui/activity/handler/DialogHandler.java
// public interface DialogHandler {
//
// void onSelection(DialogConfig.DialogItem itemSelected);
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
// Path: app/src/main/java/com/smbtv/ui/activity/GenericDialogActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v17.leanback.app.GuidedStepFragment;
import com.smbtv.R;
import com.smbtv.ui.activity.fragment.DialogFragment;
import com.smbtv.ui.activity.handler.DialogHandler;
import com.smbtv.ui.components.DialogConfig;
package com.smbtv.ui.activity;
public abstract class GenericDialogActivity extends Activity implements DialogHandler {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
if (null == savedInstanceState) {
DialogFragment fragment = new DialogFragment();
fragment.setConfig(createDialog());
fragment.setHandler(this);
GuidedStepFragment.add(getFragmentManager(), fragment);
}
}
| protected abstract DialogConfig createDialog(); |
dnbn/smbtv | app/src/main/java/com/smbtv/delegate/base/SMBShareDAO.java | // Path: app/src/main/java/com/smbtv/model/SMBShare.java
// public class SMBShare {
//
// public enum AccessMode {
// READ_ONLY(0),
// WRITEABLE(1);
//
// private final int value;
//
// AccessMode(int value) {
//
// this.value = value;
// }
//
// public String toStringValue() {
//
// return Integer.toString(this.value);
// }
// }
//
// private int id;
// private String path;
// private String name;
// private AccessMode accessMode;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPath() {
// return path;
// }
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public AccessMode getAccessMode() {
// return accessMode;
// }
//
// public void setAccessMode(AccessMode accessMode) {
// this.accessMode = accessMode;
// }
// }
| import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.model.SMBShare;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | package com.smbtv.delegate.base;
public class SMBShareDAO extends DAOBase {
private static final String TAG = SMBShareDAO.class.getSimpleName();
private static Map<String, String> queries = XMLQueryLoader.load(R.xml.db_query_shares);
public SMBShareDAO(Context context) {
super(context);
}
| // Path: app/src/main/java/com/smbtv/model/SMBShare.java
// public class SMBShare {
//
// public enum AccessMode {
// READ_ONLY(0),
// WRITEABLE(1);
//
// private final int value;
//
// AccessMode(int value) {
//
// this.value = value;
// }
//
// public String toStringValue() {
//
// return Integer.toString(this.value);
// }
// }
//
// private int id;
// private String path;
// private String name;
// private AccessMode accessMode;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPath() {
// return path;
// }
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public AccessMode getAccessMode() {
// return accessMode;
// }
//
// public void setAccessMode(AccessMode accessMode) {
// this.accessMode = accessMode;
// }
// }
// Path: app/src/main/java/com/smbtv/delegate/base/SMBShareDAO.java
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.model.SMBShare;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
package com.smbtv.delegate.base;
public class SMBShareDAO extends DAOBase {
private static final String TAG = SMBShareDAO.class.getSimpleName();
private static Map<String, String> queries = XMLQueryLoader.load(R.xml.db_query_shares);
public SMBShareDAO(Context context) {
super(context);
}
| public SMBShare findById(int idShare) { |
dnbn/smbtv | app/src/main/java/com/smbtv/ui/activity/ShareActivity.java | // Path: app/src/main/java/com/smbtv/ui/activity/fragment/ShareFragment.java
// public class ShareFragment extends GuidedStepFragment {
//
// private static final String TAG = ShareFragment.class.getName();
//
// private final int ACTION_NAME = 0;
// private final int ACTION_REMOVE = 1;
// private final int ACTION_CONTINUE = 2;
//
// private final SMBServerDelegate mSmbService;
// private final SMBShareDelegate mShareDelegate;
// private SMBShare mShare;
// private String editedName;
//
// public ShareFragment() {
//
// mSmbService = SMBServerDelegate.getInstance();
// mShareDelegate = new SMBShareDelegate();
// }
//
// public void defineShare(int idShare) {
//
// mShare = mShareDelegate.findById(idShare);
// }
//
// @NonNull
// @Override
// public GuidanceStylist.Guidance onCreateGuidance(Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateGuidance");
//
// Drawable icon = getActivity().getDrawable(R.drawable.ic_folder);
// return new GuidanceStylist.Guidance(getString(R.string.share_title) + " " + mShare.getName(), mShare.getPath(), null, icon);
// }
//
// @Override
// public void onCreateActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateActions");
//
// actions.add(GuidedActionBuilder.editText(ACTION_NAME, getString(R.string.share_name), mShare.getName()));
// actions.add(GuidedActionBuilder.text(ACTION_REMOVE, getString(R.string.share_remove), ""));
// }
//
// @Override
// public void onCreateButtonActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateButtonActions");
// super.onCreateButtonActions(actions, savedInstanceState);
//
// actions.add(new GuidedAction.Builder()
// .id(ACTION_CONTINUE)
// .title(getString(R.string.settings_validate))
// .description("")
// .build());
// }
//
// @Override
// public void onGuidedActionClicked(GuidedAction action) {
//
// Log.d(TAG, "onGuidedActionClicked");
//
// if (ACTION_REMOVE == action.getId()) {
//
// mSmbService.removeShare(mShare);
// getActivity().setResult(Activity.RESULT_OK);
// getActivity().finish();
//
// } else if (ACTION_CONTINUE == action.getId()) {
//
// if (!StringUtils.isEmpty(editedName) && !editedName.equals(mShare.getName())) {
// mSmbService.renameShare(mShare.getId(), editedName);
// }
// getActivity().setResult(Activity.RESULT_OK);
// getActivity().finish();
// }
// }
//
// @Override
// public long onGuidedActionEditedAndProceed(GuidedAction action) {
//
// Log.d(TAG, "onGuidedActionEditedAndProceed : " + action.getTitle());
//
// onActionEdited(action);
//
// return GuidedAction.ACTION_ID_CURRENT;
// }
//
// public void onGuidedActionEditCanceled(GuidedAction action) {
//
// Log.d(TAG, "onGuidedActionEditCanceled : " + action.getTitle());
//
// onActionEdited(action);
// }
//
// private void onActionEdited(GuidedAction action) {
//
// String value = action.getDescription().toString();
//
// if (ACTION_NAME == action.getId()) {
//
// if (!StringUtils.isEmpty(value)) {
// editedName = value;
// }
// }
// }
//
// }
| import android.app.Activity;
import android.os.Bundle;
import android.support.v17.leanback.app.GuidedStepFragment;
import com.smbtv.R;
import com.smbtv.ui.activity.fragment.ShareFragment; | package com.smbtv.ui.activity;
public class ShareActivity extends Activity {
public static String ID_SHARE = "element";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share);
if (null == savedInstanceState) {
int idShare = getIntent().getIntExtra(ID_SHARE, Integer.MIN_VALUE); | // Path: app/src/main/java/com/smbtv/ui/activity/fragment/ShareFragment.java
// public class ShareFragment extends GuidedStepFragment {
//
// private static final String TAG = ShareFragment.class.getName();
//
// private final int ACTION_NAME = 0;
// private final int ACTION_REMOVE = 1;
// private final int ACTION_CONTINUE = 2;
//
// private final SMBServerDelegate mSmbService;
// private final SMBShareDelegate mShareDelegate;
// private SMBShare mShare;
// private String editedName;
//
// public ShareFragment() {
//
// mSmbService = SMBServerDelegate.getInstance();
// mShareDelegate = new SMBShareDelegate();
// }
//
// public void defineShare(int idShare) {
//
// mShare = mShareDelegate.findById(idShare);
// }
//
// @NonNull
// @Override
// public GuidanceStylist.Guidance onCreateGuidance(Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateGuidance");
//
// Drawable icon = getActivity().getDrawable(R.drawable.ic_folder);
// return new GuidanceStylist.Guidance(getString(R.string.share_title) + " " + mShare.getName(), mShare.getPath(), null, icon);
// }
//
// @Override
// public void onCreateActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateActions");
//
// actions.add(GuidedActionBuilder.editText(ACTION_NAME, getString(R.string.share_name), mShare.getName()));
// actions.add(GuidedActionBuilder.text(ACTION_REMOVE, getString(R.string.share_remove), ""));
// }
//
// @Override
// public void onCreateButtonActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) {
//
// Log.d(TAG, "onCreateButtonActions");
// super.onCreateButtonActions(actions, savedInstanceState);
//
// actions.add(new GuidedAction.Builder()
// .id(ACTION_CONTINUE)
// .title(getString(R.string.settings_validate))
// .description("")
// .build());
// }
//
// @Override
// public void onGuidedActionClicked(GuidedAction action) {
//
// Log.d(TAG, "onGuidedActionClicked");
//
// if (ACTION_REMOVE == action.getId()) {
//
// mSmbService.removeShare(mShare);
// getActivity().setResult(Activity.RESULT_OK);
// getActivity().finish();
//
// } else if (ACTION_CONTINUE == action.getId()) {
//
// if (!StringUtils.isEmpty(editedName) && !editedName.equals(mShare.getName())) {
// mSmbService.renameShare(mShare.getId(), editedName);
// }
// getActivity().setResult(Activity.RESULT_OK);
// getActivity().finish();
// }
// }
//
// @Override
// public long onGuidedActionEditedAndProceed(GuidedAction action) {
//
// Log.d(TAG, "onGuidedActionEditedAndProceed : " + action.getTitle());
//
// onActionEdited(action);
//
// return GuidedAction.ACTION_ID_CURRENT;
// }
//
// public void onGuidedActionEditCanceled(GuidedAction action) {
//
// Log.d(TAG, "onGuidedActionEditCanceled : " + action.getTitle());
//
// onActionEdited(action);
// }
//
// private void onActionEdited(GuidedAction action) {
//
// String value = action.getDescription().toString();
//
// if (ACTION_NAME == action.getId()) {
//
// if (!StringUtils.isEmpty(value)) {
// editedName = value;
// }
// }
// }
//
// }
// Path: app/src/main/java/com/smbtv/ui/activity/ShareActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v17.leanback.app.GuidedStepFragment;
import com.smbtv.R;
import com.smbtv.ui.activity.fragment.ShareFragment;
package com.smbtv.ui.activity;
public class ShareActivity extends Activity {
public static String ID_SHARE = "element";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share);
if (null == savedInstanceState) {
int idShare = getIntent().getIntExtra(ID_SHARE, Integer.MIN_VALUE); | ShareFragment shareFragment = new ShareFragment(); |
dnbn/smbtv | app/src/main/java/com/smbtv/ui/activity/fragment/DialogFragment.java | // Path: app/src/main/java/com/smbtv/ui/activity/handler/DialogHandler.java
// public interface DialogHandler {
//
// void onSelection(DialogConfig.DialogItem itemSelected);
// }
//
// Path: app/src/main/java/com/smbtv/ui/activity/tools/GuidedActionBuilder.java
// public class GuidedActionBuilder {
//
// public static GuidedAction editText(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .inputType(InputType.TYPE_CLASS_TEXT)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction editNumber(long id, String title, int desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(Integer.toString(desc))
// .inputType(InputType.TYPE_CLASS_NUMBER)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction text(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .descriptionEditable(false)
// .build();
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
| import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v17.leanback.app.GuidedStepFragment;
import android.support.v17.leanback.widget.GuidanceStylist;
import android.support.v17.leanback.widget.GuidedAction;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.ui.activity.handler.DialogHandler;
import com.smbtv.ui.activity.tools.GuidedActionBuilder;
import com.smbtv.ui.components.DialogConfig;
import java.util.List; | package com.smbtv.ui.activity.fragment;
public class DialogFragment extends GuidedStepFragment {
private static final String TAG = DialogFragment.class.getName();
| // Path: app/src/main/java/com/smbtv/ui/activity/handler/DialogHandler.java
// public interface DialogHandler {
//
// void onSelection(DialogConfig.DialogItem itemSelected);
// }
//
// Path: app/src/main/java/com/smbtv/ui/activity/tools/GuidedActionBuilder.java
// public class GuidedActionBuilder {
//
// public static GuidedAction editText(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .inputType(InputType.TYPE_CLASS_TEXT)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction editNumber(long id, String title, int desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(Integer.toString(desc))
// .inputType(InputType.TYPE_CLASS_NUMBER)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction text(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .descriptionEditable(false)
// .build();
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
// Path: app/src/main/java/com/smbtv/ui/activity/fragment/DialogFragment.java
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v17.leanback.app.GuidedStepFragment;
import android.support.v17.leanback.widget.GuidanceStylist;
import android.support.v17.leanback.widget.GuidedAction;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.ui.activity.handler.DialogHandler;
import com.smbtv.ui.activity.tools.GuidedActionBuilder;
import com.smbtv.ui.components.DialogConfig;
import java.util.List;
package com.smbtv.ui.activity.fragment;
public class DialogFragment extends GuidedStepFragment {
private static final String TAG = DialogFragment.class.getName();
| private DialogConfig mConfig; |
dnbn/smbtv | app/src/main/java/com/smbtv/ui/activity/fragment/DialogFragment.java | // Path: app/src/main/java/com/smbtv/ui/activity/handler/DialogHandler.java
// public interface DialogHandler {
//
// void onSelection(DialogConfig.DialogItem itemSelected);
// }
//
// Path: app/src/main/java/com/smbtv/ui/activity/tools/GuidedActionBuilder.java
// public class GuidedActionBuilder {
//
// public static GuidedAction editText(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .inputType(InputType.TYPE_CLASS_TEXT)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction editNumber(long id, String title, int desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(Integer.toString(desc))
// .inputType(InputType.TYPE_CLASS_NUMBER)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction text(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .descriptionEditable(false)
// .build();
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
| import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v17.leanback.app.GuidedStepFragment;
import android.support.v17.leanback.widget.GuidanceStylist;
import android.support.v17.leanback.widget.GuidedAction;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.ui.activity.handler.DialogHandler;
import com.smbtv.ui.activity.tools.GuidedActionBuilder;
import com.smbtv.ui.components.DialogConfig;
import java.util.List; | package com.smbtv.ui.activity.fragment;
public class DialogFragment extends GuidedStepFragment {
private static final String TAG = DialogFragment.class.getName();
private DialogConfig mConfig; | // Path: app/src/main/java/com/smbtv/ui/activity/handler/DialogHandler.java
// public interface DialogHandler {
//
// void onSelection(DialogConfig.DialogItem itemSelected);
// }
//
// Path: app/src/main/java/com/smbtv/ui/activity/tools/GuidedActionBuilder.java
// public class GuidedActionBuilder {
//
// public static GuidedAction editText(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .inputType(InputType.TYPE_CLASS_TEXT)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction editNumber(long id, String title, int desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(Integer.toString(desc))
// .inputType(InputType.TYPE_CLASS_NUMBER)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction text(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .descriptionEditable(false)
// .build();
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
// Path: app/src/main/java/com/smbtv/ui/activity/fragment/DialogFragment.java
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v17.leanback.app.GuidedStepFragment;
import android.support.v17.leanback.widget.GuidanceStylist;
import android.support.v17.leanback.widget.GuidedAction;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.ui.activity.handler.DialogHandler;
import com.smbtv.ui.activity.tools.GuidedActionBuilder;
import com.smbtv.ui.components.DialogConfig;
import java.util.List;
package com.smbtv.ui.activity.fragment;
public class DialogFragment extends GuidedStepFragment {
private static final String TAG = DialogFragment.class.getName();
private DialogConfig mConfig; | private DialogHandler mHandler; |
dnbn/smbtv | app/src/main/java/com/smbtv/ui/activity/fragment/DialogFragment.java | // Path: app/src/main/java/com/smbtv/ui/activity/handler/DialogHandler.java
// public interface DialogHandler {
//
// void onSelection(DialogConfig.DialogItem itemSelected);
// }
//
// Path: app/src/main/java/com/smbtv/ui/activity/tools/GuidedActionBuilder.java
// public class GuidedActionBuilder {
//
// public static GuidedAction editText(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .inputType(InputType.TYPE_CLASS_TEXT)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction editNumber(long id, String title, int desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(Integer.toString(desc))
// .inputType(InputType.TYPE_CLASS_NUMBER)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction text(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .descriptionEditable(false)
// .build();
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
| import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v17.leanback.app.GuidedStepFragment;
import android.support.v17.leanback.widget.GuidanceStylist;
import android.support.v17.leanback.widget.GuidedAction;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.ui.activity.handler.DialogHandler;
import com.smbtv.ui.activity.tools.GuidedActionBuilder;
import com.smbtv.ui.components.DialogConfig;
import java.util.List; | package com.smbtv.ui.activity.fragment;
public class DialogFragment extends GuidedStepFragment {
private static final String TAG = DialogFragment.class.getName();
private DialogConfig mConfig;
private DialogHandler mHandler;
public void setConfig(DialogConfig config) {
this.mConfig = config;
}
public void setHandler(DialogHandler mHandler) {
this.mHandler = mHandler;
}
@NonNull
@Override
public GuidanceStylist.Guidance onCreateGuidance(Bundle savedInstanceState) {
Log.d(TAG, "onCreateGuidance");
Drawable icon = getActivity().getDrawable(R.drawable.ic_warning);
return new GuidanceStylist.Guidance(mConfig.getTitle(), mConfig.getDescription(), mConfig.getBeatcrumb(), icon);
}
@Override
public void onCreateActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) {
Log.d(TAG, "onCreateActions");
for (DialogConfig.DialogItem item : mConfig.getItems()) { | // Path: app/src/main/java/com/smbtv/ui/activity/handler/DialogHandler.java
// public interface DialogHandler {
//
// void onSelection(DialogConfig.DialogItem itemSelected);
// }
//
// Path: app/src/main/java/com/smbtv/ui/activity/tools/GuidedActionBuilder.java
// public class GuidedActionBuilder {
//
// public static GuidedAction editText(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .inputType(InputType.TYPE_CLASS_TEXT)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction editNumber(long id, String title, int desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(Integer.toString(desc))
// .inputType(InputType.TYPE_CLASS_NUMBER)
// .descriptionEditable(true)
// .build();
// }
//
// public static GuidedAction text(long id, String title, String desc) {
//
// return new GuidedAction.Builder()
// .id(id)
// .title(title)
// .description(desc)
// .descriptionEditable(false)
// .build();
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/ui/components/DialogConfig.java
// public class DialogConfig {
//
// private String title;
// private String description;
// private String beatcrumb;
// private List<DialogItem> items = new ArrayList<>();
//
// public DialogConfig() {
// super();
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<DialogItem> getItems() {
// return items;
// }
//
// public String getBeatcrumb() {
// return beatcrumb;
// }
//
// public void setBeatcrumb(String beatcrumb) {
// this.beatcrumb = beatcrumb;
// }
//
// public void addItem(DialogItem item) {
// this.items.add(item);
// }
//
//
// public static class DialogItem {
//
// private int id;
// private String title;
// private String description;
//
// public DialogItem(int id, String title) {
//
// this.id = id;
// this.title = title;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// }
// Path: app/src/main/java/com/smbtv/ui/activity/fragment/DialogFragment.java
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v17.leanback.app.GuidedStepFragment;
import android.support.v17.leanback.widget.GuidanceStylist;
import android.support.v17.leanback.widget.GuidedAction;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.ui.activity.handler.DialogHandler;
import com.smbtv.ui.activity.tools.GuidedActionBuilder;
import com.smbtv.ui.components.DialogConfig;
import java.util.List;
package com.smbtv.ui.activity.fragment;
public class DialogFragment extends GuidedStepFragment {
private static final String TAG = DialogFragment.class.getName();
private DialogConfig mConfig;
private DialogHandler mHandler;
public void setConfig(DialogConfig config) {
this.mConfig = config;
}
public void setHandler(DialogHandler mHandler) {
this.mHandler = mHandler;
}
@NonNull
@Override
public GuidanceStylist.Guidance onCreateGuidance(Bundle savedInstanceState) {
Log.d(TAG, "onCreateGuidance");
Drawable icon = getActivity().getDrawable(R.drawable.ic_warning);
return new GuidanceStylist.Guidance(mConfig.getTitle(), mConfig.getDescription(), mConfig.getBeatcrumb(), icon);
}
@Override
public void onCreateActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) {
Log.d(TAG, "onCreateActions");
for (DialogConfig.DialogItem item : mConfig.getItems()) { | actions.add(GuidedActionBuilder.text(item.getId(), item.getTitle(), item.getDescription())); |
dnbn/smbtv | app/src/main/java/com/smbtv/delegate/SMBShareDelegate.java | // Path: app/src/main/java/com/smbtv/delegate/base/SMBShareDAO.java
// public class SMBShareDAO extends DAOBase {
//
// private static final String TAG = SMBShareDAO.class.getSimpleName();
//
// private static Map<String, String> queries = XMLQueryLoader.load(R.xml.db_query_shares);
//
// public SMBShareDAO(Context context) {
//
// super(context);
// }
//
//
// public SMBShare findById(int idShare) {
//
// Log.d(TAG, "findById");
//
// SMBShare share = null;
//
// try (DBWrapper db = instanceDB()) {
//
// db.addBinding("id", Integer.toString(idShare));
//
// String query = queries.get("getById_share");
// Cursor c = db.rawQuery(query);
//
// if (c.moveToFirst()) {
// share = new SMBShare();
// share.setId(c.getInt(0));
// share.setPath(c.getString(1));
// share.setName(c.getString(2));
// share.setAccessMode(SMBShare.AccessMode.values()[c.getInt(3)]);
// }
// }
//
// return share;
// }
//
// public List<SMBShare> findAll() {
//
// Log.d(TAG, "findAll");
//
// List<SMBShare> shares = new ArrayList<>();
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("getAll_shares");
// Cursor c = db.rawQuery(query);
//
// while (c.moveToNext()) {
// SMBShare share = new SMBShare();
// share.setId(c.getInt(0));
// share.setPath(c.getString(1));
// share.setName(c.getString(2));
// share.setAccessMode(SMBShare.AccessMode.values()[c.getInt(3)]);
// shares.add(share);
// }
// }
//
// return shares;
// }
//
// public void insert(SMBShare share) {
//
// Log.d(TAG, "insert");
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("insert_share");
//
// db.addBinding("path", share.getPath());
// db.addBinding("name", share.getName());
// db.addBinding("access", share.getAccessMode().toStringValue());
// db.execSQL(query);
// }
// }
//
// public void delete(SMBShare share) {
//
// Log.d(TAG, "delete");
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("delete_share");
// db.addBinding("id", Integer.toString(share.getId()));
// db.execSQL(query);
// }
// }
//
// public void update(SMBShare share) {
//
// Log.d(TAG, "update");
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("update_share");
//
// db.addBinding("id", Integer.toString(share.getId()));
// db.addBinding("path", share.getPath());
// db.addBinding("name", share.getName());
// db.addBinding("access", share.getAccessMode().toStringValue());
//
// db.execSQL(query);
// }
// }
// }
//
// Path: app/src/main/java/com/smbtv/model/SMBShare.java
// public class SMBShare {
//
// public enum AccessMode {
// READ_ONLY(0),
// WRITEABLE(1);
//
// private final int value;
//
// AccessMode(int value) {
//
// this.value = value;
// }
//
// public String toStringValue() {
//
// return Integer.toString(this.value);
// }
// }
//
// private int id;
// private String path;
// private String name;
// private AccessMode accessMode;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPath() {
// return path;
// }
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public AccessMode getAccessMode() {
// return accessMode;
// }
//
// public void setAccessMode(AccessMode accessMode) {
// this.accessMode = accessMode;
// }
// }
| import android.content.Context;
import com.smbtv.delegate.base.SMBShareDAO;
import com.smbtv.model.SMBShare;
import java.util.List; | package com.smbtv.delegate;
public class SMBShareDelegate {
private SMBShareDAO mDao;
public SMBShareDelegate() {
Context context = ApplicationDelegate.getContext();
this.mDao = new SMBShareDAO(context);
}
| // Path: app/src/main/java/com/smbtv/delegate/base/SMBShareDAO.java
// public class SMBShareDAO extends DAOBase {
//
// private static final String TAG = SMBShareDAO.class.getSimpleName();
//
// private static Map<String, String> queries = XMLQueryLoader.load(R.xml.db_query_shares);
//
// public SMBShareDAO(Context context) {
//
// super(context);
// }
//
//
// public SMBShare findById(int idShare) {
//
// Log.d(TAG, "findById");
//
// SMBShare share = null;
//
// try (DBWrapper db = instanceDB()) {
//
// db.addBinding("id", Integer.toString(idShare));
//
// String query = queries.get("getById_share");
// Cursor c = db.rawQuery(query);
//
// if (c.moveToFirst()) {
// share = new SMBShare();
// share.setId(c.getInt(0));
// share.setPath(c.getString(1));
// share.setName(c.getString(2));
// share.setAccessMode(SMBShare.AccessMode.values()[c.getInt(3)]);
// }
// }
//
// return share;
// }
//
// public List<SMBShare> findAll() {
//
// Log.d(TAG, "findAll");
//
// List<SMBShare> shares = new ArrayList<>();
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("getAll_shares");
// Cursor c = db.rawQuery(query);
//
// while (c.moveToNext()) {
// SMBShare share = new SMBShare();
// share.setId(c.getInt(0));
// share.setPath(c.getString(1));
// share.setName(c.getString(2));
// share.setAccessMode(SMBShare.AccessMode.values()[c.getInt(3)]);
// shares.add(share);
// }
// }
//
// return shares;
// }
//
// public void insert(SMBShare share) {
//
// Log.d(TAG, "insert");
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("insert_share");
//
// db.addBinding("path", share.getPath());
// db.addBinding("name", share.getName());
// db.addBinding("access", share.getAccessMode().toStringValue());
// db.execSQL(query);
// }
// }
//
// public void delete(SMBShare share) {
//
// Log.d(TAG, "delete");
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("delete_share");
// db.addBinding("id", Integer.toString(share.getId()));
// db.execSQL(query);
// }
// }
//
// public void update(SMBShare share) {
//
// Log.d(TAG, "update");
//
// try (DBWrapper db = instanceDB()) {
//
// String query = queries.get("update_share");
//
// db.addBinding("id", Integer.toString(share.getId()));
// db.addBinding("path", share.getPath());
// db.addBinding("name", share.getName());
// db.addBinding("access", share.getAccessMode().toStringValue());
//
// db.execSQL(query);
// }
// }
// }
//
// Path: app/src/main/java/com/smbtv/model/SMBShare.java
// public class SMBShare {
//
// public enum AccessMode {
// READ_ONLY(0),
// WRITEABLE(1);
//
// private final int value;
//
// AccessMode(int value) {
//
// this.value = value;
// }
//
// public String toStringValue() {
//
// return Integer.toString(this.value);
// }
// }
//
// private int id;
// private String path;
// private String name;
// private AccessMode accessMode;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPath() {
// return path;
// }
//
// public void setPath(String path) {
// this.path = path;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public AccessMode getAccessMode() {
// return accessMode;
// }
//
// public void setAccessMode(AccessMode accessMode) {
// this.accessMode = accessMode;
// }
// }
// Path: app/src/main/java/com/smbtv/delegate/SMBShareDelegate.java
import android.content.Context;
import com.smbtv.delegate.base.SMBShareDAO;
import com.smbtv.model.SMBShare;
import java.util.List;
package com.smbtv.delegate;
public class SMBShareDelegate {
private SMBShareDAO mDao;
public SMBShareDelegate() {
Context context = ApplicationDelegate.getContext();
this.mDao = new SMBShareDAO(context);
}
| public void delete(SMBShare share) { |
dnbn/smbtv | app/src/main/java/com/smbtv/delegate/base/XMLQueryLoader.java | // Path: app/src/main/java/com/smbtv/delegate/ApplicationDelegate.java
// public class ApplicationDelegate extends Application {
//
// private static Context mContext;
//
// @Override
// public void onCreate() {
//
// super.onCreate();
// mContext = this;
// }
//
// public static Context getContext(){
//
// return mContext;
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/delegate/exception/LoadQueryFromXMLException.java
// public class LoadQueryFromXMLException extends RuntimeException {
//
// public LoadQueryFromXMLException(Throwable cause) {
// super(cause);
// }
// }
| import android.content.res.Resources;
import android.util.Log;
import com.smbtv.delegate.ApplicationDelegate;
import com.smbtv.delegate.exception.LoadQueryFromXMLException;
import org.xmlpull.v1.XmlPullParser;
import java.util.HashMap;
import java.util.Map; | package com.smbtv.delegate.base;
public class XMLQueryLoader {
private static final String TAG = XMLQueryLoader.class.getSimpleName();
private static final String ROOT = "queries";
public static Map<String, String> load(int resourceFile) {
Map<String, String> queries = new HashMap<>();
| // Path: app/src/main/java/com/smbtv/delegate/ApplicationDelegate.java
// public class ApplicationDelegate extends Application {
//
// private static Context mContext;
//
// @Override
// public void onCreate() {
//
// super.onCreate();
// mContext = this;
// }
//
// public static Context getContext(){
//
// return mContext;
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/delegate/exception/LoadQueryFromXMLException.java
// public class LoadQueryFromXMLException extends RuntimeException {
//
// public LoadQueryFromXMLException(Throwable cause) {
// super(cause);
// }
// }
// Path: app/src/main/java/com/smbtv/delegate/base/XMLQueryLoader.java
import android.content.res.Resources;
import android.util.Log;
import com.smbtv.delegate.ApplicationDelegate;
import com.smbtv.delegate.exception.LoadQueryFromXMLException;
import org.xmlpull.v1.XmlPullParser;
import java.util.HashMap;
import java.util.Map;
package com.smbtv.delegate.base;
public class XMLQueryLoader {
private static final String TAG = XMLQueryLoader.class.getSimpleName();
private static final String ROOT = "queries";
public static Map<String, String> load(int resourceFile) {
Map<String, String> queries = new HashMap<>();
| Resources res = ApplicationDelegate.getContext().getResources(); |
dnbn/smbtv | app/src/main/java/com/smbtv/delegate/base/XMLQueryLoader.java | // Path: app/src/main/java/com/smbtv/delegate/ApplicationDelegate.java
// public class ApplicationDelegate extends Application {
//
// private static Context mContext;
//
// @Override
// public void onCreate() {
//
// super.onCreate();
// mContext = this;
// }
//
// public static Context getContext(){
//
// return mContext;
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/delegate/exception/LoadQueryFromXMLException.java
// public class LoadQueryFromXMLException extends RuntimeException {
//
// public LoadQueryFromXMLException(Throwable cause) {
// super(cause);
// }
// }
| import android.content.res.Resources;
import android.util.Log;
import com.smbtv.delegate.ApplicationDelegate;
import com.smbtv.delegate.exception.LoadQueryFromXMLException;
import org.xmlpull.v1.XmlPullParser;
import java.util.HashMap;
import java.util.Map; | package com.smbtv.delegate.base;
public class XMLQueryLoader {
private static final String TAG = XMLQueryLoader.class.getSimpleName();
private static final String ROOT = "queries";
public static Map<String, String> load(int resourceFile) {
Map<String, String> queries = new HashMap<>();
Resources res = ApplicationDelegate.getContext().getResources();
XmlPullParser xpp = res.getXml(resourceFile);
try {
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (!xpp.getName().equals(ROOT)) {
String key = xpp.getAttributeValue(0);
String value = xpp.nextText();
queries.put(key, value);
}
}
xpp.next();
}
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e)); | // Path: app/src/main/java/com/smbtv/delegate/ApplicationDelegate.java
// public class ApplicationDelegate extends Application {
//
// private static Context mContext;
//
// @Override
// public void onCreate() {
//
// super.onCreate();
// mContext = this;
// }
//
// public static Context getContext(){
//
// return mContext;
// }
//
// }
//
// Path: app/src/main/java/com/smbtv/delegate/exception/LoadQueryFromXMLException.java
// public class LoadQueryFromXMLException extends RuntimeException {
//
// public LoadQueryFromXMLException(Throwable cause) {
// super(cause);
// }
// }
// Path: app/src/main/java/com/smbtv/delegate/base/XMLQueryLoader.java
import android.content.res.Resources;
import android.util.Log;
import com.smbtv.delegate.ApplicationDelegate;
import com.smbtv.delegate.exception.LoadQueryFromXMLException;
import org.xmlpull.v1.XmlPullParser;
import java.util.HashMap;
import java.util.Map;
package com.smbtv.delegate.base;
public class XMLQueryLoader {
private static final String TAG = XMLQueryLoader.class.getSimpleName();
private static final String ROOT = "queries";
public static Map<String, String> load(int resourceFile) {
Map<String, String> queries = new HashMap<>();
Resources res = ApplicationDelegate.getContext().getResources();
XmlPullParser xpp = res.getXml(resourceFile);
try {
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (!xpp.getName().equals(ROOT)) {
String key = xpp.getAttributeValue(0);
String value = xpp.nextText();
queries.put(key, value);
}
}
xpp.next();
}
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e)); | throw new LoadQueryFromXMLException(e); |
Bombe/jSite | src/main/java/de/todesbaum/util/freenet/fcp2/Connection.java | // Path: src/main/java/de/todesbaum/util/io/LineInputStream.java
// public class LineInputStream extends FilterInputStream {
//
// private boolean skipLinefeed = false;
// private StringBuffer lineBuffer = new StringBuffer();
//
// /**
// * @param in
// */
// public LineInputStream(InputStream in) {
// super(in);
// }
//
// public synchronized String readLine() throws IOException {
// lineBuffer.setLength(0);
// int c = 0;
// while (c != -1) {
// c = read();
// if ((c == -1) && lineBuffer.length() == 0)
// return null;
// if (skipLinefeed && (c == '\n')) {
// skipLinefeed = false;
// continue;
// }
// skipLinefeed = (c == '\r');
// if ((c == '\r') || (c == '\n')) {
// c = -1;
// } else {
// lineBuffer.append((char) c);
// }
// }
// return lineBuffer.toString();
// }
//
// }
//
// Path: src/main/java/de/todesbaum/util/io/TempFileInputStream.java
// public class TempFileInputStream extends FileInputStream {
//
// private File tempFile;
//
// /**
// * @param name
// * @throws FileNotFoundException
// */
// public TempFileInputStream(String name) throws FileNotFoundException {
// this(new File(name));
// }
//
// /**
// * @param file
// * @throws FileNotFoundException
// */
// public TempFileInputStream(File file) throws FileNotFoundException {
// super(file);
// tempFile = file;
// }
//
// @Override
// public void close() throws IOException {
// super.close();
// tempFile.delete();
// }
//
// }
| import net.pterodactylus.util.io.Closer;
import net.pterodactylus.util.io.StreamCopier;
import net.pterodactylus.util.io.StreamCopier.ProgressListener;
import de.todesbaum.util.io.LineInputStream;
import de.todesbaum.util.io.TempFileInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List; | /**
* The reader thread for this connection. This is essentially a thread that
* reads lines from the node, creates messages from them and notifies
* listeners about the messages.
*
* @author David Roden <droden@gmail.com>
* @version $Id$
*/
private class NodeReader implements Runnable {
/** The input stream to read from. */
@SuppressWarnings("hiding")
private InputStream nodeInputStream;
/**
* Creates a new reader that reads from the specified input stream.
*
* @param nodeInputStream
* The input stream to read from
*/
public NodeReader(InputStream nodeInputStream) {
this.nodeInputStream = nodeInputStream;
}
/**
* Main loop of the reader. Lines are read and converted into
* {@link Message} objects.
*/
@SuppressWarnings("synthetic-access")
public void run() { | // Path: src/main/java/de/todesbaum/util/io/LineInputStream.java
// public class LineInputStream extends FilterInputStream {
//
// private boolean skipLinefeed = false;
// private StringBuffer lineBuffer = new StringBuffer();
//
// /**
// * @param in
// */
// public LineInputStream(InputStream in) {
// super(in);
// }
//
// public synchronized String readLine() throws IOException {
// lineBuffer.setLength(0);
// int c = 0;
// while (c != -1) {
// c = read();
// if ((c == -1) && lineBuffer.length() == 0)
// return null;
// if (skipLinefeed && (c == '\n')) {
// skipLinefeed = false;
// continue;
// }
// skipLinefeed = (c == '\r');
// if ((c == '\r') || (c == '\n')) {
// c = -1;
// } else {
// lineBuffer.append((char) c);
// }
// }
// return lineBuffer.toString();
// }
//
// }
//
// Path: src/main/java/de/todesbaum/util/io/TempFileInputStream.java
// public class TempFileInputStream extends FileInputStream {
//
// private File tempFile;
//
// /**
// * @param name
// * @throws FileNotFoundException
// */
// public TempFileInputStream(String name) throws FileNotFoundException {
// this(new File(name));
// }
//
// /**
// * @param file
// * @throws FileNotFoundException
// */
// public TempFileInputStream(File file) throws FileNotFoundException {
// super(file);
// tempFile = file;
// }
//
// @Override
// public void close() throws IOException {
// super.close();
// tempFile.delete();
// }
//
// }
// Path: src/main/java/de/todesbaum/util/freenet/fcp2/Connection.java
import net.pterodactylus.util.io.Closer;
import net.pterodactylus.util.io.StreamCopier;
import net.pterodactylus.util.io.StreamCopier.ProgressListener;
import de.todesbaum.util.io.LineInputStream;
import de.todesbaum.util.io.TempFileInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* The reader thread for this connection. This is essentially a thread that
* reads lines from the node, creates messages from them and notifies
* listeners about the messages.
*
* @author David Roden <droden@gmail.com>
* @version $Id$
*/
private class NodeReader implements Runnable {
/** The input stream to read from. */
@SuppressWarnings("hiding")
private InputStream nodeInputStream;
/**
* Creates a new reader that reads from the specified input stream.
*
* @param nodeInputStream
* The input stream to read from
*/
public NodeReader(InputStream nodeInputStream) {
this.nodeInputStream = nodeInputStream;
}
/**
* Main loop of the reader. Lines are read and converted into
* {@link Message} objects.
*/
@SuppressWarnings("synthetic-access")
public void run() { | LineInputStream nodeReader = null; |
Bombe/jSite | src/main/java/de/todesbaum/util/freenet/fcp2/Connection.java | // Path: src/main/java/de/todesbaum/util/io/LineInputStream.java
// public class LineInputStream extends FilterInputStream {
//
// private boolean skipLinefeed = false;
// private StringBuffer lineBuffer = new StringBuffer();
//
// /**
// * @param in
// */
// public LineInputStream(InputStream in) {
// super(in);
// }
//
// public synchronized String readLine() throws IOException {
// lineBuffer.setLength(0);
// int c = 0;
// while (c != -1) {
// c = read();
// if ((c == -1) && lineBuffer.length() == 0)
// return null;
// if (skipLinefeed && (c == '\n')) {
// skipLinefeed = false;
// continue;
// }
// skipLinefeed = (c == '\r');
// if ((c == '\r') || (c == '\n')) {
// c = -1;
// } else {
// lineBuffer.append((char) c);
// }
// }
// return lineBuffer.toString();
// }
//
// }
//
// Path: src/main/java/de/todesbaum/util/io/TempFileInputStream.java
// public class TempFileInputStream extends FileInputStream {
//
// private File tempFile;
//
// /**
// * @param name
// * @throws FileNotFoundException
// */
// public TempFileInputStream(String name) throws FileNotFoundException {
// this(new File(name));
// }
//
// /**
// * @param file
// * @throws FileNotFoundException
// */
// public TempFileInputStream(File file) throws FileNotFoundException {
// super(file);
// tempFile = file;
// }
//
// @Override
// public void close() throws IOException {
// super.close();
// tempFile.delete();
// }
//
// }
| import net.pterodactylus.util.io.Closer;
import net.pterodactylus.util.io.StreamCopier;
import net.pterodactylus.util.io.StreamCopier.ProgressListener;
import de.todesbaum.util.io.LineInputStream;
import de.todesbaum.util.io.TempFileInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List; | * Main loop of the reader. Lines are read and converted into
* {@link Message} objects.
*/
@SuppressWarnings("synthetic-access")
public void run() {
LineInputStream nodeReader = null;
try {
nodeReader = new LineInputStream(nodeInputStream);
String line = "";
Message message = null;
while (line != null) {
line = nodeReader.readLine();
// System.err.println("> " + line);
if (line == null) {
break;
}
if (message == null) {
message = new Message(line);
continue;
}
if ("Data".equals(line)) {
/* need to read message from stream now */
File tempFile = null;
try {
tempFile = File.createTempFile("fcpv2", "data", (tempDirectory != null) ? new File(tempDirectory) : null);
tempFile.deleteOnExit();
FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile);
long dataLength = Long.parseLong(message.get("DataLength"));
StreamCopier.copy(nodeInputStream, tempFileOutputStream, dataLength);
tempFileOutputStream.close(); | // Path: src/main/java/de/todesbaum/util/io/LineInputStream.java
// public class LineInputStream extends FilterInputStream {
//
// private boolean skipLinefeed = false;
// private StringBuffer lineBuffer = new StringBuffer();
//
// /**
// * @param in
// */
// public LineInputStream(InputStream in) {
// super(in);
// }
//
// public synchronized String readLine() throws IOException {
// lineBuffer.setLength(0);
// int c = 0;
// while (c != -1) {
// c = read();
// if ((c == -1) && lineBuffer.length() == 0)
// return null;
// if (skipLinefeed && (c == '\n')) {
// skipLinefeed = false;
// continue;
// }
// skipLinefeed = (c == '\r');
// if ((c == '\r') || (c == '\n')) {
// c = -1;
// } else {
// lineBuffer.append((char) c);
// }
// }
// return lineBuffer.toString();
// }
//
// }
//
// Path: src/main/java/de/todesbaum/util/io/TempFileInputStream.java
// public class TempFileInputStream extends FileInputStream {
//
// private File tempFile;
//
// /**
// * @param name
// * @throws FileNotFoundException
// */
// public TempFileInputStream(String name) throws FileNotFoundException {
// this(new File(name));
// }
//
// /**
// * @param file
// * @throws FileNotFoundException
// */
// public TempFileInputStream(File file) throws FileNotFoundException {
// super(file);
// tempFile = file;
// }
//
// @Override
// public void close() throws IOException {
// super.close();
// tempFile.delete();
// }
//
// }
// Path: src/main/java/de/todesbaum/util/freenet/fcp2/Connection.java
import net.pterodactylus.util.io.Closer;
import net.pterodactylus.util.io.StreamCopier;
import net.pterodactylus.util.io.StreamCopier.ProgressListener;
import de.todesbaum.util.io.LineInputStream;
import de.todesbaum.util.io.TempFileInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
* Main loop of the reader. Lines are read and converted into
* {@link Message} objects.
*/
@SuppressWarnings("synthetic-access")
public void run() {
LineInputStream nodeReader = null;
try {
nodeReader = new LineInputStream(nodeInputStream);
String line = "";
Message message = null;
while (line != null) {
line = nodeReader.readLine();
// System.err.println("> " + line);
if (line == null) {
break;
}
if (message == null) {
message = new Message(line);
continue;
}
if ("Data".equals(line)) {
/* need to read message from stream now */
File tempFile = null;
try {
tempFile = File.createTempFile("fcpv2", "data", (tempDirectory != null) ? new File(tempDirectory) : null);
tempFile.deleteOnExit();
FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile);
long dataLength = Long.parseLong(message.get("DataLength"));
StreamCopier.copy(nodeInputStream, tempFileOutputStream, dataLength);
tempFileOutputStream.close(); | message.setPayloadInputStream(new TempFileInputStream(tempFile)); |
Bombe/jSite | src/test/java/de/todesbaum/jsite/main/JarFileLocatorTest.java | // Path: src/main/java/de/todesbaum/jsite/main/JarFileLocator.java
// class DefaultJarFileLocator implements JarFileLocator {
//
// private final ClassLoader classLoader;
//
// public DefaultJarFileLocator(ClassLoader classLoader) {
// this.classLoader = classLoader;
// }
//
// @Override
// public Optional<File> locateJarFile() {
// URL resourceUrl = classLoader.getResource(Main.class.getName().replace(".", "/") + ".class");
// if (resourceUrl == null) {
// return empty();
// }
// String resource = resourceUrl.toString();
// if (resource.startsWith("jar:")) {
// try {
// String jarFileLocation = URLDecoder.decode(resource.substring(9, resource.indexOf(".jar!") + 4), "UTF-8");
// return Optional.of(new File(jarFileLocation));
// } catch (UnsupportedEncodingException e) {
// /* location is not available, ignore. */
// }
// }
// return empty();
// }
// }
| import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Optional;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import net.pterodactylus.util.io.StreamCopier;
import de.todesbaum.jsite.main.JarFileLocator.DefaultJarFileLocator;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder; | package de.todesbaum.jsite.main;
/**
* Unit test for {@link JarFileLocator}.
*/
public class JarFileLocatorTest {
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
private static final Class<?> CLASS_TO_LOAD = Main.class;
private static final String RESOURCE_TO_COPY = CLASS_TO_LOAD.getName().replace('.', '/') + ".class";
private static final String PACKAGE_NAME = CLASS_TO_LOAD.getPackage().getName();
private static final String CLASS_FILENAME = CLASS_TO_LOAD.getSimpleName() + ".class";
@Test
public void jarFileCanBeLocatedOnPathWithNonUsAsciiCharacters() throws Exception {
File jarFilePath = temporaryFolder.newFolder("Фото café");
File jarFile = createJarFile(jarFilePath);
URLClassLoader urlClassLoader = createClassLoader(jarFile.toURI().toURL()); | // Path: src/main/java/de/todesbaum/jsite/main/JarFileLocator.java
// class DefaultJarFileLocator implements JarFileLocator {
//
// private final ClassLoader classLoader;
//
// public DefaultJarFileLocator(ClassLoader classLoader) {
// this.classLoader = classLoader;
// }
//
// @Override
// public Optional<File> locateJarFile() {
// URL resourceUrl = classLoader.getResource(Main.class.getName().replace(".", "/") + ".class");
// if (resourceUrl == null) {
// return empty();
// }
// String resource = resourceUrl.toString();
// if (resource.startsWith("jar:")) {
// try {
// String jarFileLocation = URLDecoder.decode(resource.substring(9, resource.indexOf(".jar!") + 4), "UTF-8");
// return Optional.of(new File(jarFileLocation));
// } catch (UnsupportedEncodingException e) {
// /* location is not available, ignore. */
// }
// }
// return empty();
// }
// }
// Path: src/test/java/de/todesbaum/jsite/main/JarFileLocatorTest.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Optional;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import net.pterodactylus.util.io.StreamCopier;
import de.todesbaum.jsite.main.JarFileLocator.DefaultJarFileLocator;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
package de.todesbaum.jsite.main;
/**
* Unit test for {@link JarFileLocator}.
*/
public class JarFileLocatorTest {
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
private static final Class<?> CLASS_TO_LOAD = Main.class;
private static final String RESOURCE_TO_COPY = CLASS_TO_LOAD.getName().replace('.', '/') + ".class";
private static final String PACKAGE_NAME = CLASS_TO_LOAD.getPackage().getName();
private static final String CLASS_FILENAME = CLASS_TO_LOAD.getSimpleName() + ".class";
@Test
public void jarFileCanBeLocatedOnPathWithNonUsAsciiCharacters() throws Exception {
File jarFilePath = temporaryFolder.newFolder("Фото café");
File jarFile = createJarFile(jarFilePath);
URLClassLoader urlClassLoader = createClassLoader(jarFile.toURI().toURL()); | JarFileLocator jarFileLocator = new DefaultJarFileLocator(urlClassLoader); |
usb4java/usb4java-javax | src/test/java/org/usb4java/javax/ScanExceptionTest.java | // Path: src/main/java/org/usb4java/javax/ScanException.java
// public final class ScanException extends RuntimeException
// {
// /** Serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor.
// *
// * @param message
// * The error message.
// * @param cause
// * The root cause.
// */
// ScanException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
// }
| import org.junit.Test;
import org.usb4java.javax.ScanException;
import static org.junit.Assert.assertEquals; | /*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link ScanException} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class ScanExceptionTest
{
/**
* Tests the constructor.
*/
@Test
public void testConstructor()
{
final Throwable cause = new RuntimeException("");
final String message = "Bang"; | // Path: src/main/java/org/usb4java/javax/ScanException.java
// public final class ScanException extends RuntimeException
// {
// /** Serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor.
// *
// * @param message
// * The error message.
// * @param cause
// * The root cause.
// */
// ScanException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
// }
// Path: src/test/java/org/usb4java/javax/ScanExceptionTest.java
import org.junit.Test;
import org.usb4java.javax.ScanException;
import static org.junit.Assert.assertEquals;
/*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link ScanException} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class ScanExceptionTest
{
/**
* Tests the constructor.
*/
@Test
public void testConstructor()
{
final Throwable cause = new RuntimeException("");
final String message = "Bang"; | final ScanException exception = new ScanException(message, cause); |
usb4java/usb4java-javax | src/test/java/org/usb4java/javax/DeviceListenerListTest.java | // Path: src/main/java/org/usb4java/javax/DeviceListenerList.java
// final class DeviceListenerList extends
// EventListenerList<UsbDeviceListener> implements UsbDeviceListener
// {
// /**
// * Constructs a new USB device listener list.
// */
// DeviceListenerList()
// {
// super();
// }
//
// @Override
// public UsbDeviceListener[] toArray()
// {
// return getListeners().toArray(
// new UsbDeviceListener[getListeners().size()]);
// }
//
// @Override
// public void usbDeviceDetached(final UsbDeviceEvent event)
// {
// for (final UsbDeviceListener listener: toArray())
// {
// listener.usbDeviceDetached(event);
// }
// }
//
// @Override
// public void errorEventOccurred(final UsbDeviceErrorEvent event)
// {
// for (final UsbDeviceListener listener: toArray())
// {
// listener.errorEventOccurred(event);
// }
// }
//
// @Override
// public void dataEventOccurred(final UsbDeviceDataEvent event)
// {
// for (final UsbDeviceListener listener: toArray())
// {
// listener.dataEventOccurred(event);
// }
// }
// }
| import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.usb.UsbControlIrp;
import javax.usb.UsbDevice;
import javax.usb.event.UsbDeviceDataEvent;
import javax.usb.event.UsbDeviceErrorEvent;
import javax.usb.event.UsbDeviceListener;
import org.junit.Before;
import org.junit.Test;
import org.usb4java.javax.DeviceListenerList; | /*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link DeviceListenerList} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class DeviceListenerListTest
{
/** The test subject. */ | // Path: src/main/java/org/usb4java/javax/DeviceListenerList.java
// final class DeviceListenerList extends
// EventListenerList<UsbDeviceListener> implements UsbDeviceListener
// {
// /**
// * Constructs a new USB device listener list.
// */
// DeviceListenerList()
// {
// super();
// }
//
// @Override
// public UsbDeviceListener[] toArray()
// {
// return getListeners().toArray(
// new UsbDeviceListener[getListeners().size()]);
// }
//
// @Override
// public void usbDeviceDetached(final UsbDeviceEvent event)
// {
// for (final UsbDeviceListener listener: toArray())
// {
// listener.usbDeviceDetached(event);
// }
// }
//
// @Override
// public void errorEventOccurred(final UsbDeviceErrorEvent event)
// {
// for (final UsbDeviceListener listener: toArray())
// {
// listener.errorEventOccurred(event);
// }
// }
//
// @Override
// public void dataEventOccurred(final UsbDeviceDataEvent event)
// {
// for (final UsbDeviceListener listener: toArray())
// {
// listener.dataEventOccurred(event);
// }
// }
// }
// Path: src/test/java/org/usb4java/javax/DeviceListenerListTest.java
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.usb.UsbControlIrp;
import javax.usb.UsbDevice;
import javax.usb.event.UsbDeviceDataEvent;
import javax.usb.event.UsbDeviceErrorEvent;
import javax.usb.event.UsbDeviceListener;
import org.junit.Before;
import org.junit.Test;
import org.usb4java.javax.DeviceListenerList;
/*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link DeviceListenerList} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class DeviceListenerListTest
{
/** The test subject. */ | private DeviceListenerList list; |
usb4java/usb4java-javax | src/test/java/org/usb4java/javax/adapter/UsbDeviceAdapterTest.java | // Path: src/main/java/org/usb4java/javax/adapter/UsbDeviceAdapter.java
// public abstract class UsbDeviceAdapter implements UsbDeviceListener
// {
// @Override
// public void usbDeviceDetached(final UsbDeviceEvent event)
// {
// // Empty
// }
//
// @Override
// public void errorEventOccurred(final UsbDeviceErrorEvent event)
// {
// // Empty
// }
//
// @Override
// public void dataEventOccurred(final UsbDeviceDataEvent event)
// {
// // Empty
// }
// }
| import javax.usb.event.UsbDeviceDataEvent;
import javax.usb.event.UsbDeviceErrorEvent;
import javax.usb.event.UsbDeviceEvent;
import javax.usb.event.UsbDeviceListener;
import org.junit.Test;
import org.usb4java.javax.adapter.UsbDeviceAdapter; | /*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax.adapter;
/**
* Test the {@link UsbDeviceAdapter} class. There is not really anything to
* test there. This class just ensures that the class exists and provides
* the needed methods.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class UsbDeviceAdapterTest
{
/**
* Ensure the existence of the needed methods.
*/
@Test
public void testAbstractMethods()
{ | // Path: src/main/java/org/usb4java/javax/adapter/UsbDeviceAdapter.java
// public abstract class UsbDeviceAdapter implements UsbDeviceListener
// {
// @Override
// public void usbDeviceDetached(final UsbDeviceEvent event)
// {
// // Empty
// }
//
// @Override
// public void errorEventOccurred(final UsbDeviceErrorEvent event)
// {
// // Empty
// }
//
// @Override
// public void dataEventOccurred(final UsbDeviceDataEvent event)
// {
// // Empty
// }
// }
// Path: src/test/java/org/usb4java/javax/adapter/UsbDeviceAdapterTest.java
import javax.usb.event.UsbDeviceDataEvent;
import javax.usb.event.UsbDeviceErrorEvent;
import javax.usb.event.UsbDeviceEvent;
import javax.usb.event.UsbDeviceListener;
import org.junit.Test;
import org.usb4java.javax.adapter.UsbDeviceAdapter;
/*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax.adapter;
/**
* Test the {@link UsbDeviceAdapter} class. There is not really anything to
* test there. This class just ensures that the class exists and provides
* the needed methods.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class UsbDeviceAdapterTest
{
/**
* Ensure the existence of the needed methods.
*/
@Test
public void testAbstractMethods()
{ | final UsbDeviceListener adapter = new UsbDeviceAdapter() |
usb4java/usb4java-javax | src/test/java/org/usb4java/javax/adapter/UsbPipeAdapterTest.java | // Path: src/main/java/org/usb4java/javax/adapter/UsbPipeAdapter.java
// public abstract class UsbPipeAdapter implements UsbPipeListener
// {
// @Override
// public void errorEventOccurred(final UsbPipeErrorEvent event)
// {
// // Empty
// }
//
// @Override
// public void dataEventOccurred(final UsbPipeDataEvent event)
// {
// // Empty
// }
// }
| import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;
import org.junit.Test;
import org.usb4java.javax.adapter.UsbPipeAdapter; | /*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax.adapter;
/**
* Test the {@link UsbPipeAdapter} class. There is not really anything to
* test there. This class just ensures that the class exists and provides
* the needed methods.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class UsbPipeAdapterTest
{
/**
* Ensure the existence of the needed methods.
*/
@Test
public void testAbstractMethods()
{ | // Path: src/main/java/org/usb4java/javax/adapter/UsbPipeAdapter.java
// public abstract class UsbPipeAdapter implements UsbPipeListener
// {
// @Override
// public void errorEventOccurred(final UsbPipeErrorEvent event)
// {
// // Empty
// }
//
// @Override
// public void dataEventOccurred(final UsbPipeDataEvent event)
// {
// // Empty
// }
// }
// Path: src/test/java/org/usb4java/javax/adapter/UsbPipeAdapterTest.java
import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;
import org.junit.Test;
import org.usb4java.javax.adapter.UsbPipeAdapter;
/*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax.adapter;
/**
* Test the {@link UsbPipeAdapter} class. There is not really anything to
* test there. This class just ensures that the class exists and provides
* the needed methods.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class UsbPipeAdapterTest
{
/**
* Ensure the existence of the needed methods.
*/
@Test
public void testAbstractMethods()
{ | final UsbPipeListener adapter = new UsbPipeAdapter() |
usb4java/usb4java-javax | src/test/java/org/usb4java/javax/ConfigTest.java | // Path: src/main/java/org/usb4java/javax/Config.java
// final class Config
// {
// /** Base key name for properties. */
// private static final String KEY_BASE = "org.usb4java.javax.";
//
// /** The default USB communication timeout in milliseconds. */
// private static final int DEFAULT_TIMEOUT = 5000;
//
// /** The default scan interval in milliseconds. */
// private static final int DEFAULT_SCAN_INTERVAL = 500;
//
// /** Key name for USB communication timeout. */
// private static final String TIMEOUT_KEY = KEY_BASE + "timeout";
//
// /** Key name for USB communication timeout. */
// private static final String SCAN_INTERVAL_KEY = KEY_BASE + "scanInterval";
//
// /** Key name for the USBDK usage flag. */
// private static final String USE_USBDK_KEY = KEY_BASE + "useUSBDK";
//
// /** The timeout for USB communication in milliseconds. */
// private int timeout = DEFAULT_TIMEOUT;
//
// /** The scan interval in milliseconds. */
// private int scanInterval = DEFAULT_SCAN_INTERVAL;
//
// /** If USBDK is to be used on Windows. */
// private boolean useUSBDK = false;
//
// /**
// * Constructs new configuration from the specified properties.
// *
// * @param properties
// * The properties to read the configuration from.
// */
// Config(final Properties properties)
// {
// // Read the USB communication timeout
// if (properties.containsKey(TIMEOUT_KEY))
// {
// this.timeout = Integer.valueOf(properties.getProperty(TIMEOUT_KEY));
// }
//
// // Read the USB device scan interval
// if (properties.containsKey(SCAN_INTERVAL_KEY))
// {
// this.scanInterval = Integer.valueOf(properties.getProperty(
// SCAN_INTERVAL_KEY));
// }
//
// // Read the USBDK usage flag
// if (properties.containsKey(USE_USBDK_KEY))
// {
// this.useUSBDK = Boolean.valueOf(properties.getProperty(USE_USBDK_KEY));
// }
// }
//
// /**
// * Returns the USB communication timeout in milliseconds.
// *
// * @return The USB communication timeout in milliseconds.
// */
// public int getTimeout()
// {
// return this.timeout;
// }
//
// /**
// * Returns the scan interval in milliseconds.
// *
// * @return The scan interval in milliseconds.
// */
// public int getScanInterval()
// {
// return this.scanInterval;
// }
//
// /**
// * Check if USBDK is to be used on Windows.
// *
// * @return True if USBDK is to be used, false if not.
// */
// public boolean isUseUSBDK()
// {
// return this.useUSBDK;
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Properties;
import org.junit.Test;
import org.usb4java.javax.Config; | /*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link Config} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class ConfigTest
{
/**
* Tests the default configuration
*/
@Test
public void testDefaultConfiguration()
{
final Properties properties = new Properties(); | // Path: src/main/java/org/usb4java/javax/Config.java
// final class Config
// {
// /** Base key name for properties. */
// private static final String KEY_BASE = "org.usb4java.javax.";
//
// /** The default USB communication timeout in milliseconds. */
// private static final int DEFAULT_TIMEOUT = 5000;
//
// /** The default scan interval in milliseconds. */
// private static final int DEFAULT_SCAN_INTERVAL = 500;
//
// /** Key name for USB communication timeout. */
// private static final String TIMEOUT_KEY = KEY_BASE + "timeout";
//
// /** Key name for USB communication timeout. */
// private static final String SCAN_INTERVAL_KEY = KEY_BASE + "scanInterval";
//
// /** Key name for the USBDK usage flag. */
// private static final String USE_USBDK_KEY = KEY_BASE + "useUSBDK";
//
// /** The timeout for USB communication in milliseconds. */
// private int timeout = DEFAULT_TIMEOUT;
//
// /** The scan interval in milliseconds. */
// private int scanInterval = DEFAULT_SCAN_INTERVAL;
//
// /** If USBDK is to be used on Windows. */
// private boolean useUSBDK = false;
//
// /**
// * Constructs new configuration from the specified properties.
// *
// * @param properties
// * The properties to read the configuration from.
// */
// Config(final Properties properties)
// {
// // Read the USB communication timeout
// if (properties.containsKey(TIMEOUT_KEY))
// {
// this.timeout = Integer.valueOf(properties.getProperty(TIMEOUT_KEY));
// }
//
// // Read the USB device scan interval
// if (properties.containsKey(SCAN_INTERVAL_KEY))
// {
// this.scanInterval = Integer.valueOf(properties.getProperty(
// SCAN_INTERVAL_KEY));
// }
//
// // Read the USBDK usage flag
// if (properties.containsKey(USE_USBDK_KEY))
// {
// this.useUSBDK = Boolean.valueOf(properties.getProperty(USE_USBDK_KEY));
// }
// }
//
// /**
// * Returns the USB communication timeout in milliseconds.
// *
// * @return The USB communication timeout in milliseconds.
// */
// public int getTimeout()
// {
// return this.timeout;
// }
//
// /**
// * Returns the scan interval in milliseconds.
// *
// * @return The scan interval in milliseconds.
// */
// public int getScanInterval()
// {
// return this.scanInterval;
// }
//
// /**
// * Check if USBDK is to be used on Windows.
// *
// * @return True if USBDK is to be used, false if not.
// */
// public boolean isUseUSBDK()
// {
// return this.useUSBDK;
// }
// }
// Path: src/test/java/org/usb4java/javax/ConfigTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Properties;
import org.junit.Test;
import org.usb4java.javax.Config;
/*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link Config} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class ConfigTest
{
/**
* Tests the default configuration
*/
@Test
public void testDefaultConfiguration()
{
final Properties properties = new Properties(); | final Config config = new Config(properties); |
usb4java/usb4java-javax | src/test/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptorTest.java | // Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptor.java
// public final class SimpleUsbStringDescriptor extends SimpleUsbDescriptor
// implements UsbStringDescriptor
// {
// /** The serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /** The string data in UTF-16LE encoding. */
// private final byte[] bString;
//
// /**
// * Constructs a new string descriptor by reading the descriptor data
// * from the specified byte buffer.
// *
// * @param data
// * The descriptor data as a byte buffer.
// */
// public SimpleUsbStringDescriptor(final ByteBuffer data)
// {
// super(data.get(0), data.get(1));
//
// data.position(2);
// this.bString = new byte[bLength() - 2];
// data.get(this.bString);
// }
//
// /**
// * Constructs a new string descriptor with the specified data.
// *
// * @param bLength
// * The descriptor length.
// * @param bDescriptorType
// * The descriptor type.
// * @param string
// * The string.
// * @throws UnsupportedEncodingException
// * When system does not support UTF-16LE encoding.
// */
// public SimpleUsbStringDescriptor(final byte bLength,
// final byte bDescriptorType, final String string)
// throws UnsupportedEncodingException
// {
// super(bLength, bDescriptorType);
// this.bString = string.getBytes("UTF-16LE");
// }
//
// /**
// * Copy constructor.
// *
// * @param descriptor
// * The descriptor from which to copy the data.
// */
// public SimpleUsbStringDescriptor(final UsbStringDescriptor descriptor)
// {
// super(descriptor.bLength(), descriptor.bDescriptorType());
// this.bString = descriptor.bString().clone();
// }
//
// @Override
// public byte[] bString()
// {
// return this.bString.clone();
// }
//
// @Override
// public String getString() throws UnsupportedEncodingException
// {
// return new String(this.bString, "UTF-16LE");
// }
//
// @Override
// public boolean equals(final Object obj)
// {
// if (this == obj) return true;
// if (obj == null || getClass() != obj.getClass()) return false;
// final SimpleUsbStringDescriptor other = (SimpleUsbStringDescriptor) obj;
// return new EqualsBuilder()
// .append(bLength(), other.bLength())
// .append(bDescriptorType(), other.bDescriptorType())
// .append(this.bString, other.bString)
// .isEquals();
// }
//
// @Override
// public int hashCode()
// {
// return new HashCodeBuilder()
// .append(bDescriptorType())
// .append(bLength())
// .append(this.bString)
// .toHashCode();
// }
//
// @Override
// public String toString()
// {
// return new String(this.bString, Charset.forName("UTF-16LE"));
// }
// }
| import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import org.junit.BeforeClass;
import org.junit.Test;
import org.usb4java.javax.descriptors.SimpleUsbStringDescriptor; | /*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax.descriptors;
/**
* Tests the {@link SimpleUsbStringDescriptor}.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class SimpleUsbStringDescriptorTest
{
/** The test subject. */ | // Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptor.java
// public final class SimpleUsbStringDescriptor extends SimpleUsbDescriptor
// implements UsbStringDescriptor
// {
// /** The serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /** The string data in UTF-16LE encoding. */
// private final byte[] bString;
//
// /**
// * Constructs a new string descriptor by reading the descriptor data
// * from the specified byte buffer.
// *
// * @param data
// * The descriptor data as a byte buffer.
// */
// public SimpleUsbStringDescriptor(final ByteBuffer data)
// {
// super(data.get(0), data.get(1));
//
// data.position(2);
// this.bString = new byte[bLength() - 2];
// data.get(this.bString);
// }
//
// /**
// * Constructs a new string descriptor with the specified data.
// *
// * @param bLength
// * The descriptor length.
// * @param bDescriptorType
// * The descriptor type.
// * @param string
// * The string.
// * @throws UnsupportedEncodingException
// * When system does not support UTF-16LE encoding.
// */
// public SimpleUsbStringDescriptor(final byte bLength,
// final byte bDescriptorType, final String string)
// throws UnsupportedEncodingException
// {
// super(bLength, bDescriptorType);
// this.bString = string.getBytes("UTF-16LE");
// }
//
// /**
// * Copy constructor.
// *
// * @param descriptor
// * The descriptor from which to copy the data.
// */
// public SimpleUsbStringDescriptor(final UsbStringDescriptor descriptor)
// {
// super(descriptor.bLength(), descriptor.bDescriptorType());
// this.bString = descriptor.bString().clone();
// }
//
// @Override
// public byte[] bString()
// {
// return this.bString.clone();
// }
//
// @Override
// public String getString() throws UnsupportedEncodingException
// {
// return new String(this.bString, "UTF-16LE");
// }
//
// @Override
// public boolean equals(final Object obj)
// {
// if (this == obj) return true;
// if (obj == null || getClass() != obj.getClass()) return false;
// final SimpleUsbStringDescriptor other = (SimpleUsbStringDescriptor) obj;
// return new EqualsBuilder()
// .append(bLength(), other.bLength())
// .append(bDescriptorType(), other.bDescriptorType())
// .append(this.bString, other.bString)
// .isEquals();
// }
//
// @Override
// public int hashCode()
// {
// return new HashCodeBuilder()
// .append(bDescriptorType())
// .append(bLength())
// .append(this.bString)
// .toHashCode();
// }
//
// @Override
// public String toString()
// {
// return new String(this.bString, Charset.forName("UTF-16LE"));
// }
// }
// Path: src/test/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptorTest.java
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import org.junit.BeforeClass;
import org.junit.Test;
import org.usb4java.javax.descriptors.SimpleUsbStringDescriptor;
/*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax.descriptors;
/**
* Tests the {@link SimpleUsbStringDescriptor}.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class SimpleUsbStringDescriptorTest
{
/** The test subject. */ | private static SimpleUsbStringDescriptor descriptor; |
usb4java/usb4java-javax | src/main/java/org/usb4java/javax/AbstractDevice.java | // Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptor.java
// public final class SimpleUsbStringDescriptor extends SimpleUsbDescriptor
// implements UsbStringDescriptor
// {
// /** The serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /** The string data in UTF-16LE encoding. */
// private final byte[] bString;
//
// /**
// * Constructs a new string descriptor by reading the descriptor data
// * from the specified byte buffer.
// *
// * @param data
// * The descriptor data as a byte buffer.
// */
// public SimpleUsbStringDescriptor(final ByteBuffer data)
// {
// super(data.get(0), data.get(1));
//
// data.position(2);
// this.bString = new byte[bLength() - 2];
// data.get(this.bString);
// }
//
// /**
// * Constructs a new string descriptor with the specified data.
// *
// * @param bLength
// * The descriptor length.
// * @param bDescriptorType
// * The descriptor type.
// * @param string
// * The string.
// * @throws UnsupportedEncodingException
// * When system does not support UTF-16LE encoding.
// */
// public SimpleUsbStringDescriptor(final byte bLength,
// final byte bDescriptorType, final String string)
// throws UnsupportedEncodingException
// {
// super(bLength, bDescriptorType);
// this.bString = string.getBytes("UTF-16LE");
// }
//
// /**
// * Copy constructor.
// *
// * @param descriptor
// * The descriptor from which to copy the data.
// */
// public SimpleUsbStringDescriptor(final UsbStringDescriptor descriptor)
// {
// super(descriptor.bLength(), descriptor.bDescriptorType());
// this.bString = descriptor.bString().clone();
// }
//
// @Override
// public byte[] bString()
// {
// return this.bString.clone();
// }
//
// @Override
// public String getString() throws UnsupportedEncodingException
// {
// return new String(this.bString, "UTF-16LE");
// }
//
// @Override
// public boolean equals(final Object obj)
// {
// if (this == obj) return true;
// if (obj == null || getClass() != obj.getClass()) return false;
// final SimpleUsbStringDescriptor other = (SimpleUsbStringDescriptor) obj;
// return new EqualsBuilder()
// .append(bLength(), other.bLength())
// .append(bDescriptorType(), other.bDescriptorType())
// .append(this.bString, other.bString)
// .isEquals();
// }
//
// @Override
// public int hashCode()
// {
// return new HashCodeBuilder()
// .append(bDescriptorType())
// .append(bLength())
// .append(this.bString)
// .toHashCode();
// }
//
// @Override
// public String toString()
// {
// return new String(this.bString, Charset.forName("UTF-16LE"));
// }
// }
| import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.usb.UsbClaimException;
import javax.usb.UsbConst;
import javax.usb.UsbControlIrp;
import javax.usb.UsbDevice;
import javax.usb.UsbDeviceDescriptor;
import javax.usb.UsbDisconnectedException;
import javax.usb.UsbException;
import javax.usb.UsbPlatformException;
import javax.usb.UsbPort;
import javax.usb.UsbStringDescriptor;
import javax.usb.event.UsbDeviceEvent;
import javax.usb.event.UsbDeviceListener;
import javax.usb.util.DefaultUsbControlIrp;
import org.usb4java.ConfigDescriptor;
import org.usb4java.Device;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.javax.descriptors.SimpleUsbStringDescriptor; |
@Override
public final boolean isConfigured()
{
return getActiveUsbConfigurationNumber() != 0;
}
@Override
public final UsbDeviceDescriptor getUsbDeviceDescriptor()
{
return this.id.getDeviceDescriptor();
}
@Override
public final UsbStringDescriptor getUsbStringDescriptor(final byte index)
throws UsbException
{
checkConnected();
final short[] languages = getLanguages();
final DeviceHandle handle = open();
final short langId = languages.length == 0 ? 0 : languages[0];
final ByteBuffer data = ByteBuffer.allocateDirect(256);
final int result =
LibUsb.getStringDescriptor(handle, index, langId, data);
if (result < 0)
{
throw ExceptionUtils.createPlatformException(
"Unable to get string descriptor " + index + " from device "
+ this, result);
} | // Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbStringDescriptor.java
// public final class SimpleUsbStringDescriptor extends SimpleUsbDescriptor
// implements UsbStringDescriptor
// {
// /** The serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /** The string data in UTF-16LE encoding. */
// private final byte[] bString;
//
// /**
// * Constructs a new string descriptor by reading the descriptor data
// * from the specified byte buffer.
// *
// * @param data
// * The descriptor data as a byte buffer.
// */
// public SimpleUsbStringDescriptor(final ByteBuffer data)
// {
// super(data.get(0), data.get(1));
//
// data.position(2);
// this.bString = new byte[bLength() - 2];
// data.get(this.bString);
// }
//
// /**
// * Constructs a new string descriptor with the specified data.
// *
// * @param bLength
// * The descriptor length.
// * @param bDescriptorType
// * The descriptor type.
// * @param string
// * The string.
// * @throws UnsupportedEncodingException
// * When system does not support UTF-16LE encoding.
// */
// public SimpleUsbStringDescriptor(final byte bLength,
// final byte bDescriptorType, final String string)
// throws UnsupportedEncodingException
// {
// super(bLength, bDescriptorType);
// this.bString = string.getBytes("UTF-16LE");
// }
//
// /**
// * Copy constructor.
// *
// * @param descriptor
// * The descriptor from which to copy the data.
// */
// public SimpleUsbStringDescriptor(final UsbStringDescriptor descriptor)
// {
// super(descriptor.bLength(), descriptor.bDescriptorType());
// this.bString = descriptor.bString().clone();
// }
//
// @Override
// public byte[] bString()
// {
// return this.bString.clone();
// }
//
// @Override
// public String getString() throws UnsupportedEncodingException
// {
// return new String(this.bString, "UTF-16LE");
// }
//
// @Override
// public boolean equals(final Object obj)
// {
// if (this == obj) return true;
// if (obj == null || getClass() != obj.getClass()) return false;
// final SimpleUsbStringDescriptor other = (SimpleUsbStringDescriptor) obj;
// return new EqualsBuilder()
// .append(bLength(), other.bLength())
// .append(bDescriptorType(), other.bDescriptorType())
// .append(this.bString, other.bString)
// .isEquals();
// }
//
// @Override
// public int hashCode()
// {
// return new HashCodeBuilder()
// .append(bDescriptorType())
// .append(bLength())
// .append(this.bString)
// .toHashCode();
// }
//
// @Override
// public String toString()
// {
// return new String(this.bString, Charset.forName("UTF-16LE"));
// }
// }
// Path: src/main/java/org/usb4java/javax/AbstractDevice.java
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.usb.UsbClaimException;
import javax.usb.UsbConst;
import javax.usb.UsbControlIrp;
import javax.usb.UsbDevice;
import javax.usb.UsbDeviceDescriptor;
import javax.usb.UsbDisconnectedException;
import javax.usb.UsbException;
import javax.usb.UsbPlatformException;
import javax.usb.UsbPort;
import javax.usb.UsbStringDescriptor;
import javax.usb.event.UsbDeviceEvent;
import javax.usb.event.UsbDeviceListener;
import javax.usb.util.DefaultUsbControlIrp;
import org.usb4java.ConfigDescriptor;
import org.usb4java.Device;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.javax.descriptors.SimpleUsbStringDescriptor;
@Override
public final boolean isConfigured()
{
return getActiveUsbConfigurationNumber() != 0;
}
@Override
public final UsbDeviceDescriptor getUsbDeviceDescriptor()
{
return this.id.getDeviceDescriptor();
}
@Override
public final UsbStringDescriptor getUsbStringDescriptor(final byte index)
throws UsbException
{
checkConnected();
final short[] languages = getLanguages();
final DeviceHandle handle = open();
final short langId = languages.length == 0 ? 0 : languages[0];
final ByteBuffer data = ByteBuffer.allocateDirect(256);
final int result =
LibUsb.getStringDescriptor(handle, index, langId, data);
if (result < 0)
{
throw ExceptionUtils.createPlatformException(
"Unable to get string descriptor " + index + " from device "
+ this, result);
} | return new SimpleUsbStringDescriptor(data); |
usb4java/usb4java-javax | src/test/java/org/usb4java/javax/adapter/UsbServicesAdapterTest.java | // Path: src/main/java/org/usb4java/javax/adapter/UsbServicesAdapter.java
// public abstract class UsbServicesAdapter implements UsbServicesListener
// {
// @Override
// public void usbDeviceAttached(final UsbServicesEvent event)
// {
// // Empty
// }
//
// @Override
// public void usbDeviceDetached(final UsbServicesEvent event)
// {
// // Empty
// }
// }
| import org.junit.Test;
import org.usb4java.javax.adapter.UsbServicesAdapter;
import javax.usb.event.UsbServicesEvent;
import javax.usb.event.UsbServicesListener; | /*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax.adapter;
/**
* Test the {@link UsbServicesAdapter} class. There is not really anything to
* test there. This class just ensures that the class exists and provides
* the needed methods.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class UsbServicesAdapterTest
{
/**
* Ensure the existence of the needed methods.
*/
@Test
public void testAbstractMethods()
{ | // Path: src/main/java/org/usb4java/javax/adapter/UsbServicesAdapter.java
// public abstract class UsbServicesAdapter implements UsbServicesListener
// {
// @Override
// public void usbDeviceAttached(final UsbServicesEvent event)
// {
// // Empty
// }
//
// @Override
// public void usbDeviceDetached(final UsbServicesEvent event)
// {
// // Empty
// }
// }
// Path: src/test/java/org/usb4java/javax/adapter/UsbServicesAdapterTest.java
import org.junit.Test;
import org.usb4java.javax.adapter.UsbServicesAdapter;
import javax.usb.event.UsbServicesEvent;
import javax.usb.event.UsbServicesListener;
/*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax.adapter;
/**
* Test the {@link UsbServicesAdapter} class. There is not really anything to
* test there. This class just ensures that the class exists and provides
* the needed methods.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class UsbServicesAdapterTest
{
/**
* Ensure the existence of the needed methods.
*/
@Test
public void testAbstractMethods()
{ | final UsbServicesListener adapter = new UsbServicesAdapter() |
usb4java/usb4java-javax | src/test/java/org/usb4java/javax/RootHubConfigurationTest.java | // Path: src/main/java/org/usb4java/javax/RootHubConfiguration.java
// final class RootHubConfiguration implements UsbConfiguration
// {
// /** The virtual interfaces. */
// private final List<UsbInterface> interfaces =
// new ArrayList<UsbInterface>();
//
// /** The device this configuration belongs to. */
// private final UsbDevice device;
//
// /** The USB configuration descriptor. */
// private final UsbConfigurationDescriptor descriptor =
// new SimpleUsbConfigurationDescriptor(
// UsbConst.DESCRIPTOR_MIN_LENGTH_CONFIGURATION,
// UsbConst.DESCRIPTOR_TYPE_CONFIGURATION,
// (byte) (UsbConst.DESCRIPTOR_MIN_LENGTH_CONFIGURATION
// + UsbConst.DESCRIPTOR_MIN_LENGTH_INTERFACE),
// (byte) 1,
// (byte) 1,
// (byte) 0,
// (byte) 0x80,
// (byte) 0);
//
// /**
// * Constructor.
// *
// * @param device
// * The device this configuration belongs to.
// */
// RootHubConfiguration(final UsbDevice device)
// {
// this.device = device;
// this.interfaces.add(new RootHubInterface(this));
// }
//
// @Override
// public boolean isActive()
// {
// return true;
// }
//
// @Override
// public List<UsbInterface> getUsbInterfaces()
// {
// return this.interfaces;
// }
//
// @Override
// public UsbInterface getUsbInterface(final byte number)
// {
// if (number != 0) return null;
// return this.interfaces.get(0);
// }
//
// @Override
// public boolean containsUsbInterface(final byte number)
// {
// return number == 0;
// }
//
// @Override
// public UsbDevice getUsbDevice()
// {
// return this.device;
// }
//
// @Override
// public UsbConfigurationDescriptor getUsbConfigurationDescriptor()
// {
// return this.descriptor;
// }
//
// @Override
// public String getConfigurationString()
// {
// return null;
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.List;
import javax.usb.UsbDevice;
import javax.usb.UsbInterface;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.usb4java.javax.RootHubConfiguration; | /*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link RootHubConfiguration} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class RootHubConfigurationTest
{
/** The test subject. */ | // Path: src/main/java/org/usb4java/javax/RootHubConfiguration.java
// final class RootHubConfiguration implements UsbConfiguration
// {
// /** The virtual interfaces. */
// private final List<UsbInterface> interfaces =
// new ArrayList<UsbInterface>();
//
// /** The device this configuration belongs to. */
// private final UsbDevice device;
//
// /** The USB configuration descriptor. */
// private final UsbConfigurationDescriptor descriptor =
// new SimpleUsbConfigurationDescriptor(
// UsbConst.DESCRIPTOR_MIN_LENGTH_CONFIGURATION,
// UsbConst.DESCRIPTOR_TYPE_CONFIGURATION,
// (byte) (UsbConst.DESCRIPTOR_MIN_LENGTH_CONFIGURATION
// + UsbConst.DESCRIPTOR_MIN_LENGTH_INTERFACE),
// (byte) 1,
// (byte) 1,
// (byte) 0,
// (byte) 0x80,
// (byte) 0);
//
// /**
// * Constructor.
// *
// * @param device
// * The device this configuration belongs to.
// */
// RootHubConfiguration(final UsbDevice device)
// {
// this.device = device;
// this.interfaces.add(new RootHubInterface(this));
// }
//
// @Override
// public boolean isActive()
// {
// return true;
// }
//
// @Override
// public List<UsbInterface> getUsbInterfaces()
// {
// return this.interfaces;
// }
//
// @Override
// public UsbInterface getUsbInterface(final byte number)
// {
// if (number != 0) return null;
// return this.interfaces.get(0);
// }
//
// @Override
// public boolean containsUsbInterface(final byte number)
// {
// return number == 0;
// }
//
// @Override
// public UsbDevice getUsbDevice()
// {
// return this.device;
// }
//
// @Override
// public UsbConfigurationDescriptor getUsbConfigurationDescriptor()
// {
// return this.descriptor;
// }
//
// @Override
// public String getConfigurationString()
// {
// return null;
// }
// }
// Path: src/test/java/org/usb4java/javax/RootHubConfigurationTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.List;
import javax.usb.UsbDevice;
import javax.usb.UsbInterface;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.usb4java.javax.RootHubConfiguration;
/*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link RootHubConfiguration} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class RootHubConfigurationTest
{
/** The test subject. */ | private RootHubConfiguration config; |
usb4java/usb4java-javax | src/main/java/org/usb4java/javax/Endpoint.java | // Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbEndpointDescriptor.java
// public final class SimpleUsbEndpointDescriptor extends SimpleUsbDescriptor
// implements UsbEndpointDescriptor
// {
// /** Serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /** The poll interval. */
// private final byte bInterval;
//
// /** The maximum packet size. */
// private final short wMaxPacketSize;
//
// /** The endpoint attributes. */
// private final byte bmAttributes;
//
// /** The endpoint address. */
// private final byte bEndpointAddress;
//
// /**
// * Constructor.
// *
// * @param bLength
// * The descriptor length.
// * @param bDescriptorType
// * The descriptor type.
// * @param bEndpointAddress
// * The address of the endpoint.
// * @param bmAttributes
// * The endpoint attributes.
// * @param wMaxPacketSize
// * The maximum packet size.
// * @param bInterval
// * The poll interval.
// */
// public SimpleUsbEndpointDescriptor(final byte bLength,
// final byte bDescriptorType, final byte bEndpointAddress,
// final byte bmAttributes, final short wMaxPacketSize,
// final byte bInterval)
// {
// super(bLength, bDescriptorType);
// this.bEndpointAddress = bEndpointAddress;
// this.wMaxPacketSize = wMaxPacketSize;
// this.bmAttributes = bmAttributes;
// this.bInterval = bInterval;
// }
//
// /**
// * Construct from a libusb4java endpoint descriptor.
// *
// * @param descriptor
// * The descriptor from which to copy the data.
// */
// public SimpleUsbEndpointDescriptor(final EndpointDescriptor descriptor)
// {
// this(descriptor.bLength(),
// descriptor.bDescriptorType(),
// descriptor.bEndpointAddress(),
// descriptor.bmAttributes(),
// descriptor.wMaxPacketSize(),
// descriptor.bInterval());
// }
//
// @Override
// public byte bEndpointAddress()
// {
// return this.bEndpointAddress;
// }
//
// @Override
// public byte bmAttributes()
// {
// return this.bmAttributes;
// }
//
// @Override
// public short wMaxPacketSize()
// {
// return this.wMaxPacketSize;
// }
//
// @Override
// public byte bInterval()
// {
// return this.bInterval;
// }
//
// @Override
// public int hashCode()
// {
// return new HashCodeBuilder()
// .append(bDescriptorType())
// .append(bLength())
// .append(this.bEndpointAddress)
// .append(this.bInterval)
// .append(this.bmAttributes)
// .append(this.wMaxPacketSize)
// .toHashCode();
// }
//
// @Override
// public boolean equals(final Object obj)
// {
// if (this == obj) return true;
// if (obj == null || getClass() != obj.getClass()) return false;
// final SimpleUsbEndpointDescriptor other =
// (SimpleUsbEndpointDescriptor) obj;
// return new EqualsBuilder()
// .append(bLength(), other.bLength())
// .append(bDescriptorType(), other.bDescriptorType())
// .append(this.bEndpointAddress, other.bEndpointAddress)
// .append(this.bInterval, other.bInterval)
// .append(this.bmAttributes, other.bmAttributes)
// .append(this.wMaxPacketSize, other.wMaxPacketSize)
// .isEquals();
// }
//
// @Override
// public String toString()
// {
// return String.format(
// "Endpoint Descriptor:%n" +
// " bLength %18d%n" +
// " bDescriptorType %10d%n" +
// " bEndpointAddress %9s EP %d %s%n" +
// " bmAttributes %13d%n" +
// " Transfer Type %s%n" +
// " Synch Type %s%n" +
// " Usage Type %s%n" +
// " wMaxPacketSize %11d%n" +
// " bInterval %16d%n",
// bLength() & 0xff,
// bDescriptorType() & 0xff,
// String.format("0x%02x", bEndpointAddress() & 0xff),
// bEndpointAddress() & 0x0f,
// DescriptorUtils.getDirectionName(bEndpointAddress()),
// bmAttributes() & 0xff,
// DescriptorUtils.getTransferTypeName(bmAttributes()),
// DescriptorUtils.getSynchTypeName(bmAttributes()),
// DescriptorUtils.getUsageTypeName(bmAttributes()),
// wMaxPacketSize() & 0xffff,
// bInterval() & 0xff);
// }
// }
| import javax.usb.UsbConst;
import javax.usb.UsbEndpoint;
import javax.usb.UsbEndpointDescriptor;
import javax.usb.UsbPipe;
import org.usb4java.EndpointDescriptor;
import org.usb4java.javax.descriptors.SimpleUsbEndpointDescriptor; | /*
* Copyright (C) 2011 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* usb4java implementation of UsbEndpoint.
*
* @author Klaus Reimer (k@ailis.de)
*/
final class Endpoint implements UsbEndpoint
{
/** The interface this endpoint belongs to. */
private final Interface iface;
/** The endpoint descriptor. */
private final UsbEndpointDescriptor descriptor;
/** The USB pipe for this endpoint. */
private final Pipe pipe;
/**
* Constructor.
*
* @param iface
* The interface this endpoint belongs to.
* @param descriptor
* The libusb endpoint descriptor.
*/
Endpoint(final Interface iface,
final EndpointDescriptor descriptor)
{
this.iface = iface; | // Path: src/main/java/org/usb4java/javax/descriptors/SimpleUsbEndpointDescriptor.java
// public final class SimpleUsbEndpointDescriptor extends SimpleUsbDescriptor
// implements UsbEndpointDescriptor
// {
// /** Serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /** The poll interval. */
// private final byte bInterval;
//
// /** The maximum packet size. */
// private final short wMaxPacketSize;
//
// /** The endpoint attributes. */
// private final byte bmAttributes;
//
// /** The endpoint address. */
// private final byte bEndpointAddress;
//
// /**
// * Constructor.
// *
// * @param bLength
// * The descriptor length.
// * @param bDescriptorType
// * The descriptor type.
// * @param bEndpointAddress
// * The address of the endpoint.
// * @param bmAttributes
// * The endpoint attributes.
// * @param wMaxPacketSize
// * The maximum packet size.
// * @param bInterval
// * The poll interval.
// */
// public SimpleUsbEndpointDescriptor(final byte bLength,
// final byte bDescriptorType, final byte bEndpointAddress,
// final byte bmAttributes, final short wMaxPacketSize,
// final byte bInterval)
// {
// super(bLength, bDescriptorType);
// this.bEndpointAddress = bEndpointAddress;
// this.wMaxPacketSize = wMaxPacketSize;
// this.bmAttributes = bmAttributes;
// this.bInterval = bInterval;
// }
//
// /**
// * Construct from a libusb4java endpoint descriptor.
// *
// * @param descriptor
// * The descriptor from which to copy the data.
// */
// public SimpleUsbEndpointDescriptor(final EndpointDescriptor descriptor)
// {
// this(descriptor.bLength(),
// descriptor.bDescriptorType(),
// descriptor.bEndpointAddress(),
// descriptor.bmAttributes(),
// descriptor.wMaxPacketSize(),
// descriptor.bInterval());
// }
//
// @Override
// public byte bEndpointAddress()
// {
// return this.bEndpointAddress;
// }
//
// @Override
// public byte bmAttributes()
// {
// return this.bmAttributes;
// }
//
// @Override
// public short wMaxPacketSize()
// {
// return this.wMaxPacketSize;
// }
//
// @Override
// public byte bInterval()
// {
// return this.bInterval;
// }
//
// @Override
// public int hashCode()
// {
// return new HashCodeBuilder()
// .append(bDescriptorType())
// .append(bLength())
// .append(this.bEndpointAddress)
// .append(this.bInterval)
// .append(this.bmAttributes)
// .append(this.wMaxPacketSize)
// .toHashCode();
// }
//
// @Override
// public boolean equals(final Object obj)
// {
// if (this == obj) return true;
// if (obj == null || getClass() != obj.getClass()) return false;
// final SimpleUsbEndpointDescriptor other =
// (SimpleUsbEndpointDescriptor) obj;
// return new EqualsBuilder()
// .append(bLength(), other.bLength())
// .append(bDescriptorType(), other.bDescriptorType())
// .append(this.bEndpointAddress, other.bEndpointAddress)
// .append(this.bInterval, other.bInterval)
// .append(this.bmAttributes, other.bmAttributes)
// .append(this.wMaxPacketSize, other.wMaxPacketSize)
// .isEquals();
// }
//
// @Override
// public String toString()
// {
// return String.format(
// "Endpoint Descriptor:%n" +
// " bLength %18d%n" +
// " bDescriptorType %10d%n" +
// " bEndpointAddress %9s EP %d %s%n" +
// " bmAttributes %13d%n" +
// " Transfer Type %s%n" +
// " Synch Type %s%n" +
// " Usage Type %s%n" +
// " wMaxPacketSize %11d%n" +
// " bInterval %16d%n",
// bLength() & 0xff,
// bDescriptorType() & 0xff,
// String.format("0x%02x", bEndpointAddress() & 0xff),
// bEndpointAddress() & 0x0f,
// DescriptorUtils.getDirectionName(bEndpointAddress()),
// bmAttributes() & 0xff,
// DescriptorUtils.getTransferTypeName(bmAttributes()),
// DescriptorUtils.getSynchTypeName(bmAttributes()),
// DescriptorUtils.getUsageTypeName(bmAttributes()),
// wMaxPacketSize() & 0xffff,
// bInterval() & 0xff);
// }
// }
// Path: src/main/java/org/usb4java/javax/Endpoint.java
import javax.usb.UsbConst;
import javax.usb.UsbEndpoint;
import javax.usb.UsbEndpointDescriptor;
import javax.usb.UsbPipe;
import org.usb4java.EndpointDescriptor;
import org.usb4java.javax.descriptors.SimpleUsbEndpointDescriptor;
/*
* Copyright (C) 2011 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* usb4java implementation of UsbEndpoint.
*
* @author Klaus Reimer (k@ailis.de)
*/
final class Endpoint implements UsbEndpoint
{
/** The interface this endpoint belongs to. */
private final Interface iface;
/** The endpoint descriptor. */
private final UsbEndpointDescriptor descriptor;
/** The USB pipe for this endpoint. */
private final Pipe pipe;
/**
* Constructor.
*
* @param iface
* The interface this endpoint belongs to.
* @param descriptor
* The libusb endpoint descriptor.
*/
Endpoint(final Interface iface,
final EndpointDescriptor descriptor)
{
this.iface = iface; | this.descriptor = new SimpleUsbEndpointDescriptor(descriptor); |
usb4java/usb4java-javax | src/test/java/org/usb4java/javax/PipeListenerListTest.java | // Path: src/main/java/org/usb4java/javax/PipeListenerList.java
// final class PipeListenerList extends
// EventListenerList<UsbPipeListener> implements UsbPipeListener
// {
// /**
// * Constructs a new USB pipe listener list.
// */
// PipeListenerList()
// {
// super();
// }
//
// @Override
// public UsbPipeListener[] toArray()
// {
// return getListeners().toArray(
// new UsbPipeListener[getListeners().size()]);
// }
//
// @Override
// public void errorEventOccurred(final UsbPipeErrorEvent event)
// {
// for (final UsbPipeListener listener: toArray())
// {
// listener.errorEventOccurred(event);
// }
// }
//
// @Override
// public void dataEventOccurred(final UsbPipeDataEvent event)
// {
// for (final UsbPipeListener listener: toArray())
// {
// listener.dataEventOccurred(event);
// }
// }
// }
| import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.usb.UsbException;
import javax.usb.UsbPipe;
import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;
import org.junit.Before;
import org.junit.Test;
import org.usb4java.javax.PipeListenerList; | /*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link PipeListenerList} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class PipeListenerListTest
{
/** The test subject. */ | // Path: src/main/java/org/usb4java/javax/PipeListenerList.java
// final class PipeListenerList extends
// EventListenerList<UsbPipeListener> implements UsbPipeListener
// {
// /**
// * Constructs a new USB pipe listener list.
// */
// PipeListenerList()
// {
// super();
// }
//
// @Override
// public UsbPipeListener[] toArray()
// {
// return getListeners().toArray(
// new UsbPipeListener[getListeners().size()]);
// }
//
// @Override
// public void errorEventOccurred(final UsbPipeErrorEvent event)
// {
// for (final UsbPipeListener listener: toArray())
// {
// listener.errorEventOccurred(event);
// }
// }
//
// @Override
// public void dataEventOccurred(final UsbPipeDataEvent event)
// {
// for (final UsbPipeListener listener: toArray())
// {
// listener.dataEventOccurred(event);
// }
// }
// }
// Path: src/test/java/org/usb4java/javax/PipeListenerListTest.java
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.usb.UsbException;
import javax.usb.UsbPipe;
import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;
import org.junit.Before;
import org.junit.Test;
import org.usb4java.javax.PipeListenerList;
/*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link PipeListenerList} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class PipeListenerListTest
{
/** The test subject. */ | private PipeListenerList list; |
usb4java/usb4java-javax | src/test/java/org/usb4java/javax/ServicesExceptionTest.java | // Path: src/main/java/org/usb4java/javax/ServicesException.java
// public final class ServicesException extends RuntimeException
// {
// /** Serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor.
// *
// * @param message
// * The error message.
// * @param cause
// * The root cause.
// */
// ServicesException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
// }
| import org.junit.Test;
import org.usb4java.javax.ServicesException;
import static org.junit.Assert.assertEquals; | /*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link ServicesException} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class ServicesExceptionTest
{
/**
* Tests the constructor.
*/
@Test
public void testConstructor()
{
final Throwable cause = new RuntimeException("");
final String message = "Bang"; | // Path: src/main/java/org/usb4java/javax/ServicesException.java
// public final class ServicesException extends RuntimeException
// {
// /** Serial version UID. */
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor.
// *
// * @param message
// * The error message.
// * @param cause
// * The root cause.
// */
// ServicesException(final String message, final Throwable cause)
// {
// super(message, cause);
// }
// }
// Path: src/test/java/org/usb4java/javax/ServicesExceptionTest.java
import org.junit.Test;
import org.usb4java.javax.ServicesException;
import static org.junit.Assert.assertEquals;
/*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link ServicesException} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class ServicesExceptionTest
{
/**
* Tests the constructor.
*/
@Test
public void testConstructor()
{
final Throwable cause = new RuntimeException("");
final String message = "Bang"; | final ServicesException exception = |
usb4java/usb4java-javax | src/test/java/org/usb4java/javax/ServicesListenerListTest.java | // Path: src/main/java/org/usb4java/javax/ServicesListenerList.java
// final class ServicesListenerList extends
// EventListenerList<UsbServicesListener> implements UsbServicesListener
// {
// /**
// * Constructs a new USB services listener list.
// */
// ServicesListenerList()
// {
// super();
// }
//
// @Override
// public UsbServicesListener[] toArray()
// {
// return getListeners().toArray(
// new UsbServicesListener[getListeners().size()]);
// }
//
// @Override
// public void usbDeviceAttached(final UsbServicesEvent event)
// {
// for (final UsbServicesListener listener: toArray())
// {
// listener.usbDeviceAttached(event);
// }
// }
//
// @Override
// public void usbDeviceDetached(final UsbServicesEvent event)
// {
// for (final UsbServicesListener listener: toArray())
// {
// listener.usbDeviceDetached(event);
// }
// }
// }
| import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.usb.UsbDevice;
import javax.usb.UsbServices;
import javax.usb.event.UsbServicesEvent;
import javax.usb.event.UsbServicesListener;
import org.junit.Before;
import org.junit.Test;
import org.usb4java.javax.ServicesListenerList; | /*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link ServicesListenerList} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class ServicesListenerListTest
{
/** The test subject. */ | // Path: src/main/java/org/usb4java/javax/ServicesListenerList.java
// final class ServicesListenerList extends
// EventListenerList<UsbServicesListener> implements UsbServicesListener
// {
// /**
// * Constructs a new USB services listener list.
// */
// ServicesListenerList()
// {
// super();
// }
//
// @Override
// public UsbServicesListener[] toArray()
// {
// return getListeners().toArray(
// new UsbServicesListener[getListeners().size()]);
// }
//
// @Override
// public void usbDeviceAttached(final UsbServicesEvent event)
// {
// for (final UsbServicesListener listener: toArray())
// {
// listener.usbDeviceAttached(event);
// }
// }
//
// @Override
// public void usbDeviceDetached(final UsbServicesEvent event)
// {
// for (final UsbServicesListener listener: toArray())
// {
// listener.usbDeviceDetached(event);
// }
// }
// }
// Path: src/test/java/org/usb4java/javax/ServicesListenerListTest.java
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.usb.UsbDevice;
import javax.usb.UsbServices;
import javax.usb.event.UsbServicesEvent;
import javax.usb.event.UsbServicesListener;
import org.junit.Before;
import org.junit.Test;
import org.usb4java.javax.ServicesListenerList;
/*
* Copyright (C) 2013 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package org.usb4java.javax;
/**
* Tests the {@link ServicesListenerList} class.
*
* @author Klaus Reimer (k@ailis.de)
*/
public class ServicesListenerListTest
{
/** The test subject. */ | private ServicesListenerList list; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.