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
|
---|---|---|---|---|---|---|
SpoonLabs/spoon-examples | src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/Collector.java | // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java
// public class Logger {
//
// public static Map<String, Object> observations = new HashMap<>();
//
// public static void observe(String name, Object object) {
// observations.put(name, object);
// }
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/test/TestRunner.java
// public class TestRunner {
//
// private static Function<String[], URL[]> arrayStringToArrayUrl = (arrayStr) ->
// Arrays.stream(arrayStr)
// .map(File::new)
// .map(File::toURI)
// .map(uri -> {
// try {
// return uri.toURL();
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
// })
// .toArray(URL[]::new);
//
// //TODO should maybe run the Listener
//
// public static List<Failure> runTest(String fullQualifiedName, String testCaseName, String[] classpath) throws MalformedURLException, ClassNotFoundException {
// ClassLoader classLoader = new URLClassLoader(
// arrayStringToArrayUrl.apply(classpath),
// ClassLoader.getSystemClassLoader()
// );
// Request request = Request.method(classLoader.loadClass(fullQualifiedName), testCaseName);
// Runner runner = request.getRunner();
// RunNotifier fNotifier = new RunNotifier();
// final TestListener listener = new TestListener();
// fNotifier.addFirstListener(listener);
// fNotifier.fireTestRunStarted(runner.getDescription());
// runner.run(fNotifier);
// return listener.getTestFails();
// }
//
// public static List<Failure> runTest(String fullQualifiedName, String[] classpath) throws MalformedURLException, ClassNotFoundException {
// ClassLoader classLoader = new URLClassLoader(
// arrayStringToArrayUrl.apply(classpath),
// ClassLoader.getSystemClassLoader()
// );
// Request request = Request.classes(classLoader.loadClass(fullQualifiedName));
// Runner runner = request.getRunner();
// RunNotifier fNotifier = new RunNotifier();
// final TestListener listener = new TestListener();
// fNotifier.addFirstListener(listener);
// fNotifier.fireTestRunStarted(runner.getDescription());
// runner.run(fNotifier);
// return listener.getTestFails();
// }
//
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static List<CtMethod> getGetters(CtLocalVariable localVariable) {
// return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream()
// .filter(method -> method.getParameters().isEmpty() &&
// method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE &&
// (method.getSimpleName().startsWith("get") ||
// method.getSimpleName().startsWith("is"))
// ).collect(Collectors.toList());
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static String getKey(CtMethod method) {
// return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName();
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) {
// final CtExecutableReference reference = method.getReference();
// final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false);
// return method.getFactory().createInvocation(variableRead, reference);
// }
| import fr.inria.gforge.spoon.assertgenerator.Logger;
import fr.inria.gforge.spoon.assertgenerator.test.TestRunner;
import spoon.Launcher;
import spoon.SpoonModelBuilder;
import spoon.reflect.code.CtInvocation;
import spoon.reflect.code.CtLocalVariable;
import spoon.reflect.code.CtTypeAccess;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.factory.Factory;
import spoon.reflect.reference.CtExecutableReference;
import java.util.List;
import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters;
import static fr.inria.gforge.spoon.assertgenerator.Util.getKey;
import static fr.inria.gforge.spoon.assertgenerator.Util.invok;
import java.net.MalformedURLException; | public void run(Launcher launcher, CtClass testClass, CtMethod<?> clone) {
String fullQualifiedName = testClass.getQualifiedName();
String testMethodName = clone.getSimpleName();
try {
final SpoonModelBuilder compiler = launcher.createCompiler();
compiler.compile(SpoonModelBuilder.InputType.CTTYPES);
TestRunner.runTest(fullQualifiedName, testMethodName, new String[]{"spooned-classes"});
} catch (ClassNotFoundException | MalformedURLException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public void instrument(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) {
ctLocalVariables.forEach(ctLocalVariable -> this.instrument(testMethod, ctLocalVariable));
}
void instrument(CtMethod testMethod, CtLocalVariable localVariable) {
List<CtMethod> getters = getGetters(localVariable);
getters.forEach(getter -> {
CtInvocation invocationToGetter =
invok(getter, localVariable);
CtInvocation invocationToObserve =
createObserve(getter, invocationToGetter);
testMethod.getBody().insertEnd(invocationToObserve);
});
}
CtInvocation createObserve(CtMethod getter, CtInvocation invocationToGetter) {
CtTypeAccess accessToLogger = | // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java
// public class Logger {
//
// public static Map<String, Object> observations = new HashMap<>();
//
// public static void observe(String name, Object object) {
// observations.put(name, object);
// }
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/test/TestRunner.java
// public class TestRunner {
//
// private static Function<String[], URL[]> arrayStringToArrayUrl = (arrayStr) ->
// Arrays.stream(arrayStr)
// .map(File::new)
// .map(File::toURI)
// .map(uri -> {
// try {
// return uri.toURL();
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
// })
// .toArray(URL[]::new);
//
// //TODO should maybe run the Listener
//
// public static List<Failure> runTest(String fullQualifiedName, String testCaseName, String[] classpath) throws MalformedURLException, ClassNotFoundException {
// ClassLoader classLoader = new URLClassLoader(
// arrayStringToArrayUrl.apply(classpath),
// ClassLoader.getSystemClassLoader()
// );
// Request request = Request.method(classLoader.loadClass(fullQualifiedName), testCaseName);
// Runner runner = request.getRunner();
// RunNotifier fNotifier = new RunNotifier();
// final TestListener listener = new TestListener();
// fNotifier.addFirstListener(listener);
// fNotifier.fireTestRunStarted(runner.getDescription());
// runner.run(fNotifier);
// return listener.getTestFails();
// }
//
// public static List<Failure> runTest(String fullQualifiedName, String[] classpath) throws MalformedURLException, ClassNotFoundException {
// ClassLoader classLoader = new URLClassLoader(
// arrayStringToArrayUrl.apply(classpath),
// ClassLoader.getSystemClassLoader()
// );
// Request request = Request.classes(classLoader.loadClass(fullQualifiedName));
// Runner runner = request.getRunner();
// RunNotifier fNotifier = new RunNotifier();
// final TestListener listener = new TestListener();
// fNotifier.addFirstListener(listener);
// fNotifier.fireTestRunStarted(runner.getDescription());
// runner.run(fNotifier);
// return listener.getTestFails();
// }
//
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static List<CtMethod> getGetters(CtLocalVariable localVariable) {
// return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream()
// .filter(method -> method.getParameters().isEmpty() &&
// method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE &&
// (method.getSimpleName().startsWith("get") ||
// method.getSimpleName().startsWith("is"))
// ).collect(Collectors.toList());
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static String getKey(CtMethod method) {
// return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName();
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) {
// final CtExecutableReference reference = method.getReference();
// final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false);
// return method.getFactory().createInvocation(variableRead, reference);
// }
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/Collector.java
import fr.inria.gforge.spoon.assertgenerator.Logger;
import fr.inria.gforge.spoon.assertgenerator.test.TestRunner;
import spoon.Launcher;
import spoon.SpoonModelBuilder;
import spoon.reflect.code.CtInvocation;
import spoon.reflect.code.CtLocalVariable;
import spoon.reflect.code.CtTypeAccess;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.factory.Factory;
import spoon.reflect.reference.CtExecutableReference;
import java.util.List;
import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters;
import static fr.inria.gforge.spoon.assertgenerator.Util.getKey;
import static fr.inria.gforge.spoon.assertgenerator.Util.invok;
import java.net.MalformedURLException;
public void run(Launcher launcher, CtClass testClass, CtMethod<?> clone) {
String fullQualifiedName = testClass.getQualifiedName();
String testMethodName = clone.getSimpleName();
try {
final SpoonModelBuilder compiler = launcher.createCompiler();
compiler.compile(SpoonModelBuilder.InputType.CTTYPES);
TestRunner.runTest(fullQualifiedName, testMethodName, new String[]{"spooned-classes"});
} catch (ClassNotFoundException | MalformedURLException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public void instrument(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) {
ctLocalVariables.forEach(ctLocalVariable -> this.instrument(testMethod, ctLocalVariable));
}
void instrument(CtMethod testMethod, CtLocalVariable localVariable) {
List<CtMethod> getters = getGetters(localVariable);
getters.forEach(getter -> {
CtInvocation invocationToGetter =
invok(getter, localVariable);
CtInvocation invocationToObserve =
createObserve(getter, invocationToGetter);
testMethod.getBody().insertEnd(invocationToObserve);
});
}
CtInvocation createObserve(CtMethod getter, CtInvocation invocationToGetter) {
CtTypeAccess accessToLogger = | factory.createTypeAccess(factory.createCtTypeReference(Logger.class)); |
SpoonLabs/spoon-examples | src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/Collector.java | // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java
// public class Logger {
//
// public static Map<String, Object> observations = new HashMap<>();
//
// public static void observe(String name, Object object) {
// observations.put(name, object);
// }
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/test/TestRunner.java
// public class TestRunner {
//
// private static Function<String[], URL[]> arrayStringToArrayUrl = (arrayStr) ->
// Arrays.stream(arrayStr)
// .map(File::new)
// .map(File::toURI)
// .map(uri -> {
// try {
// return uri.toURL();
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
// })
// .toArray(URL[]::new);
//
// //TODO should maybe run the Listener
//
// public static List<Failure> runTest(String fullQualifiedName, String testCaseName, String[] classpath) throws MalformedURLException, ClassNotFoundException {
// ClassLoader classLoader = new URLClassLoader(
// arrayStringToArrayUrl.apply(classpath),
// ClassLoader.getSystemClassLoader()
// );
// Request request = Request.method(classLoader.loadClass(fullQualifiedName), testCaseName);
// Runner runner = request.getRunner();
// RunNotifier fNotifier = new RunNotifier();
// final TestListener listener = new TestListener();
// fNotifier.addFirstListener(listener);
// fNotifier.fireTestRunStarted(runner.getDescription());
// runner.run(fNotifier);
// return listener.getTestFails();
// }
//
// public static List<Failure> runTest(String fullQualifiedName, String[] classpath) throws MalformedURLException, ClassNotFoundException {
// ClassLoader classLoader = new URLClassLoader(
// arrayStringToArrayUrl.apply(classpath),
// ClassLoader.getSystemClassLoader()
// );
// Request request = Request.classes(classLoader.loadClass(fullQualifiedName));
// Runner runner = request.getRunner();
// RunNotifier fNotifier = new RunNotifier();
// final TestListener listener = new TestListener();
// fNotifier.addFirstListener(listener);
// fNotifier.fireTestRunStarted(runner.getDescription());
// runner.run(fNotifier);
// return listener.getTestFails();
// }
//
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static List<CtMethod> getGetters(CtLocalVariable localVariable) {
// return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream()
// .filter(method -> method.getParameters().isEmpty() &&
// method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE &&
// (method.getSimpleName().startsWith("get") ||
// method.getSimpleName().startsWith("is"))
// ).collect(Collectors.toList());
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static String getKey(CtMethod method) {
// return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName();
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) {
// final CtExecutableReference reference = method.getReference();
// final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false);
// return method.getFactory().createInvocation(variableRead, reference);
// }
| import fr.inria.gforge.spoon.assertgenerator.Logger;
import fr.inria.gforge.spoon.assertgenerator.test.TestRunner;
import spoon.Launcher;
import spoon.SpoonModelBuilder;
import spoon.reflect.code.CtInvocation;
import spoon.reflect.code.CtLocalVariable;
import spoon.reflect.code.CtTypeAccess;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.factory.Factory;
import spoon.reflect.reference.CtExecutableReference;
import java.util.List;
import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters;
import static fr.inria.gforge.spoon.assertgenerator.Util.getKey;
import static fr.inria.gforge.spoon.assertgenerator.Util.invok;
import java.net.MalformedURLException; | TestRunner.runTest(fullQualifiedName, testMethodName, new String[]{"spooned-classes"});
} catch (ClassNotFoundException | MalformedURLException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public void instrument(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) {
ctLocalVariables.forEach(ctLocalVariable -> this.instrument(testMethod, ctLocalVariable));
}
void instrument(CtMethod testMethod, CtLocalVariable localVariable) {
List<CtMethod> getters = getGetters(localVariable);
getters.forEach(getter -> {
CtInvocation invocationToGetter =
invok(getter, localVariable);
CtInvocation invocationToObserve =
createObserve(getter, invocationToGetter);
testMethod.getBody().insertEnd(invocationToObserve);
});
}
CtInvocation createObserve(CtMethod getter, CtInvocation invocationToGetter) {
CtTypeAccess accessToLogger =
factory.createTypeAccess(factory.createCtTypeReference(Logger.class));
CtExecutableReference refObserve = factory.Type().get(Logger.class)
.getMethodsByName("observe").get(0).getReference();
return factory.createInvocation(
accessToLogger,
refObserve, | // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java
// public class Logger {
//
// public static Map<String, Object> observations = new HashMap<>();
//
// public static void observe(String name, Object object) {
// observations.put(name, object);
// }
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/test/TestRunner.java
// public class TestRunner {
//
// private static Function<String[], URL[]> arrayStringToArrayUrl = (arrayStr) ->
// Arrays.stream(arrayStr)
// .map(File::new)
// .map(File::toURI)
// .map(uri -> {
// try {
// return uri.toURL();
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
// })
// .toArray(URL[]::new);
//
// //TODO should maybe run the Listener
//
// public static List<Failure> runTest(String fullQualifiedName, String testCaseName, String[] classpath) throws MalformedURLException, ClassNotFoundException {
// ClassLoader classLoader = new URLClassLoader(
// arrayStringToArrayUrl.apply(classpath),
// ClassLoader.getSystemClassLoader()
// );
// Request request = Request.method(classLoader.loadClass(fullQualifiedName), testCaseName);
// Runner runner = request.getRunner();
// RunNotifier fNotifier = new RunNotifier();
// final TestListener listener = new TestListener();
// fNotifier.addFirstListener(listener);
// fNotifier.fireTestRunStarted(runner.getDescription());
// runner.run(fNotifier);
// return listener.getTestFails();
// }
//
// public static List<Failure> runTest(String fullQualifiedName, String[] classpath) throws MalformedURLException, ClassNotFoundException {
// ClassLoader classLoader = new URLClassLoader(
// arrayStringToArrayUrl.apply(classpath),
// ClassLoader.getSystemClassLoader()
// );
// Request request = Request.classes(classLoader.loadClass(fullQualifiedName));
// Runner runner = request.getRunner();
// RunNotifier fNotifier = new RunNotifier();
// final TestListener listener = new TestListener();
// fNotifier.addFirstListener(listener);
// fNotifier.fireTestRunStarted(runner.getDescription());
// runner.run(fNotifier);
// return listener.getTestFails();
// }
//
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static List<CtMethod> getGetters(CtLocalVariable localVariable) {
// return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream()
// .filter(method -> method.getParameters().isEmpty() &&
// method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE &&
// (method.getSimpleName().startsWith("get") ||
// method.getSimpleName().startsWith("is"))
// ).collect(Collectors.toList());
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static String getKey(CtMethod method) {
// return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName();
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java
// public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) {
// final CtExecutableReference reference = method.getReference();
// final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false);
// return method.getFactory().createInvocation(variableRead, reference);
// }
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/Collector.java
import fr.inria.gforge.spoon.assertgenerator.Logger;
import fr.inria.gforge.spoon.assertgenerator.test.TestRunner;
import spoon.Launcher;
import spoon.SpoonModelBuilder;
import spoon.reflect.code.CtInvocation;
import spoon.reflect.code.CtLocalVariable;
import spoon.reflect.code.CtTypeAccess;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.factory.Factory;
import spoon.reflect.reference.CtExecutableReference;
import java.util.List;
import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters;
import static fr.inria.gforge.spoon.assertgenerator.Util.getKey;
import static fr.inria.gforge.spoon.assertgenerator.Util.invok;
import java.net.MalformedURLException;
TestRunner.runTest(fullQualifiedName, testMethodName, new String[]{"spooned-classes"});
} catch (ClassNotFoundException | MalformedURLException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public void instrument(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) {
ctLocalVariables.forEach(ctLocalVariable -> this.instrument(testMethod, ctLocalVariable));
}
void instrument(CtMethod testMethod, CtLocalVariable localVariable) {
List<CtMethod> getters = getGetters(localVariable);
getters.forEach(getter -> {
CtInvocation invocationToGetter =
invok(getter, localVariable);
CtInvocation invocationToObserve =
createObserve(getter, invocationToGetter);
testMethod.getBody().insertEnd(invocationToObserve);
});
}
CtInvocation createObserve(CtMethod getter, CtInvocation invocationToGetter) {
CtTypeAccess accessToLogger =
factory.createTypeAccess(factory.createCtTypeReference(Logger.class));
CtExecutableReference refObserve = factory.Type().get(Logger.class)
.getMethodsByName("observe").get(0).getReference();
return factory.createInvocation(
accessToLogger,
refObserve, | factory.createLiteral(getKey(getter)), |
SpoonLabs/spoon-examples | src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/processing/DBAccessProcessor.java | // Path: src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/annotation/DBType.java
// public enum DBType {
// RELATIONAL,
// OBJECT,
// FILE
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/template/DBCodeTemplate.java
// public class DBCodeTemplate extends ExtensionTemplate {
// @Parameter
// public String _database_;
//
// @Parameter
// public String _username_;
//
// @Parameter
// public String _password_;
//
// @Parameter
// public String _tableName_;
//
// @Parameter
// public String _columnName_;
//
// Connection connection;
//
// @Local
// String key;
//
// public DBCodeTemplate(Factory f, String database, String username,
// String password, String tableName) {
// this._database_ = database;
// this._username_ = username;
// this._password_ = password;
// this._tableName_ = tableName;
// }
//
// public void initializerCode() {
// try {
// Class.forName("org.postgresql.Driver");
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// return;
// }
// try {
// connection = DriverManager.getConnection("jdbc:postgresql:"
// + _database_, _username_, _password_);
// } catch (SQLException e) {
// new Exception("failed to connect to the database with "
// + "jdbc:postgresql:" + _database_ + "," + _username_ + ","
// + _password_).printStackTrace();
// }
// }
//
// public String accessCode() {
// String query = "select " + _columnName_ + " from " + _tableName_
// + " where key=" + key;
// Statement s = null;
// try {
// s = connection.createStatement();
// ResultSet rs = s.executeQuery(query);
// rs.first();
// return rs.getString(1);
// } catch (java.sql.SQLException ex12) {
// ex12.printStackTrace();
// } finally {
// try {
// s.close();
// } catch (Exception ex13) {
// ex13.printStackTrace();
// }
// }
// return null;
// }
//
// }
| import fr.inria.gforge.spoon.transformation.dbaccess.annotation.DBAccess;
import fr.inria.gforge.spoon.transformation.dbaccess.annotation.DBType;
import fr.inria.gforge.spoon.transformation.dbaccess.template.DBCodeTemplate;
import org.apache.log4j.Level;
import spoon.processing.AbstractAnnotationProcessor;
import spoon.reflect.code.CtStatement;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtConstructor;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.factory.Factory;
import spoon.template.Substitution; | package fr.inria.gforge.spoon.transformation.dbaccess.processing;
public class DBAccessProcessor extends
AbstractAnnotationProcessor<DBAccess, CtClass<?>> {
public void process(DBAccess dbAccess, CtClass<?> target) {
Factory f = target.getFactory(); | // Path: src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/annotation/DBType.java
// public enum DBType {
// RELATIONAL,
// OBJECT,
// FILE
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/template/DBCodeTemplate.java
// public class DBCodeTemplate extends ExtensionTemplate {
// @Parameter
// public String _database_;
//
// @Parameter
// public String _username_;
//
// @Parameter
// public String _password_;
//
// @Parameter
// public String _tableName_;
//
// @Parameter
// public String _columnName_;
//
// Connection connection;
//
// @Local
// String key;
//
// public DBCodeTemplate(Factory f, String database, String username,
// String password, String tableName) {
// this._database_ = database;
// this._username_ = username;
// this._password_ = password;
// this._tableName_ = tableName;
// }
//
// public void initializerCode() {
// try {
// Class.forName("org.postgresql.Driver");
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// return;
// }
// try {
// connection = DriverManager.getConnection("jdbc:postgresql:"
// + _database_, _username_, _password_);
// } catch (SQLException e) {
// new Exception("failed to connect to the database with "
// + "jdbc:postgresql:" + _database_ + "," + _username_ + ","
// + _password_).printStackTrace();
// }
// }
//
// public String accessCode() {
// String query = "select " + _columnName_ + " from " + _tableName_
// + " where key=" + key;
// Statement s = null;
// try {
// s = connection.createStatement();
// ResultSet rs = s.executeQuery(query);
// rs.first();
// return rs.getString(1);
// } catch (java.sql.SQLException ex12) {
// ex12.printStackTrace();
// } finally {
// try {
// s.close();
// } catch (Exception ex13) {
// ex13.printStackTrace();
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/processing/DBAccessProcessor.java
import fr.inria.gforge.spoon.transformation.dbaccess.annotation.DBAccess;
import fr.inria.gforge.spoon.transformation.dbaccess.annotation.DBType;
import fr.inria.gforge.spoon.transformation.dbaccess.template.DBCodeTemplate;
import org.apache.log4j.Level;
import spoon.processing.AbstractAnnotationProcessor;
import spoon.reflect.code.CtStatement;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtConstructor;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.factory.Factory;
import spoon.template.Substitution;
package fr.inria.gforge.spoon.transformation.dbaccess.processing;
public class DBAccessProcessor extends
AbstractAnnotationProcessor<DBAccess, CtClass<?>> {
public void process(DBAccess dbAccess, CtClass<?> target) {
Factory f = target.getFactory(); | DBType t = dbAccess.type(); |
SpoonLabs/spoon-examples | src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/processing/DBAccessProcessor.java | // Path: src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/annotation/DBType.java
// public enum DBType {
// RELATIONAL,
// OBJECT,
// FILE
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/template/DBCodeTemplate.java
// public class DBCodeTemplate extends ExtensionTemplate {
// @Parameter
// public String _database_;
//
// @Parameter
// public String _username_;
//
// @Parameter
// public String _password_;
//
// @Parameter
// public String _tableName_;
//
// @Parameter
// public String _columnName_;
//
// Connection connection;
//
// @Local
// String key;
//
// public DBCodeTemplate(Factory f, String database, String username,
// String password, String tableName) {
// this._database_ = database;
// this._username_ = username;
// this._password_ = password;
// this._tableName_ = tableName;
// }
//
// public void initializerCode() {
// try {
// Class.forName("org.postgresql.Driver");
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// return;
// }
// try {
// connection = DriverManager.getConnection("jdbc:postgresql:"
// + _database_, _username_, _password_);
// } catch (SQLException e) {
// new Exception("failed to connect to the database with "
// + "jdbc:postgresql:" + _database_ + "," + _username_ + ","
// + _password_).printStackTrace();
// }
// }
//
// public String accessCode() {
// String query = "select " + _columnName_ + " from " + _tableName_
// + " where key=" + key;
// Statement s = null;
// try {
// s = connection.createStatement();
// ResultSet rs = s.executeQuery(query);
// rs.first();
// return rs.getString(1);
// } catch (java.sql.SQLException ex12) {
// ex12.printStackTrace();
// } finally {
// try {
// s.close();
// } catch (Exception ex13) {
// ex13.printStackTrace();
// }
// }
// return null;
// }
//
// }
| import fr.inria.gforge.spoon.transformation.dbaccess.annotation.DBAccess;
import fr.inria.gforge.spoon.transformation.dbaccess.annotation.DBType;
import fr.inria.gforge.spoon.transformation.dbaccess.template.DBCodeTemplate;
import org.apache.log4j.Level;
import spoon.processing.AbstractAnnotationProcessor;
import spoon.reflect.code.CtStatement;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtConstructor;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.factory.Factory;
import spoon.template.Substitution; | package fr.inria.gforge.spoon.transformation.dbaccess.processing;
public class DBAccessProcessor extends
AbstractAnnotationProcessor<DBAccess, CtClass<?>> {
public void process(DBAccess dbAccess, CtClass<?> target) {
Factory f = target.getFactory();
DBType t = dbAccess.type();
if (t != DBType.RELATIONAL)
f.getEnvironment().report(
this,
Level.ERROR,
target.getAnnotation(f.Type().createReference(
DBAccess.class)), "unsupported DB system");
| // Path: src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/annotation/DBType.java
// public enum DBType {
// RELATIONAL,
// OBJECT,
// FILE
// }
//
// Path: src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/template/DBCodeTemplate.java
// public class DBCodeTemplate extends ExtensionTemplate {
// @Parameter
// public String _database_;
//
// @Parameter
// public String _username_;
//
// @Parameter
// public String _password_;
//
// @Parameter
// public String _tableName_;
//
// @Parameter
// public String _columnName_;
//
// Connection connection;
//
// @Local
// String key;
//
// public DBCodeTemplate(Factory f, String database, String username,
// String password, String tableName) {
// this._database_ = database;
// this._username_ = username;
// this._password_ = password;
// this._tableName_ = tableName;
// }
//
// public void initializerCode() {
// try {
// Class.forName("org.postgresql.Driver");
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// return;
// }
// try {
// connection = DriverManager.getConnection("jdbc:postgresql:"
// + _database_, _username_, _password_);
// } catch (SQLException e) {
// new Exception("failed to connect to the database with "
// + "jdbc:postgresql:" + _database_ + "," + _username_ + ","
// + _password_).printStackTrace();
// }
// }
//
// public String accessCode() {
// String query = "select " + _columnName_ + " from " + _tableName_
// + " where key=" + key;
// Statement s = null;
// try {
// s = connection.createStatement();
// ResultSet rs = s.executeQuery(query);
// rs.first();
// return rs.getString(1);
// } catch (java.sql.SQLException ex12) {
// ex12.printStackTrace();
// } finally {
// try {
// s.close();
// } catch (Exception ex13) {
// ex13.printStackTrace();
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/fr/inria/gforge/spoon/transformation/dbaccess/processing/DBAccessProcessor.java
import fr.inria.gforge.spoon.transformation.dbaccess.annotation.DBAccess;
import fr.inria.gforge.spoon.transformation.dbaccess.annotation.DBType;
import fr.inria.gforge.spoon.transformation.dbaccess.template.DBCodeTemplate;
import org.apache.log4j.Level;
import spoon.processing.AbstractAnnotationProcessor;
import spoon.reflect.code.CtStatement;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtConstructor;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.factory.Factory;
import spoon.template.Substitution;
package fr.inria.gforge.spoon.transformation.dbaccess.processing;
public class DBAccessProcessor extends
AbstractAnnotationProcessor<DBAccess, CtClass<?>> {
public void process(DBAccess dbAccess, CtClass<?> target) {
Factory f = target.getFactory();
DBType t = dbAccess.type();
if (t != DBType.RELATIONAL)
f.getEnvironment().report(
this,
Level.ERROR,
target.getAnnotation(f.Type().createReference(
DBAccess.class)), "unsupported DB system");
| DBCodeTemplate template = new DBCodeTemplate(f, dbAccess.database(), |
samuelhehe/androidpn_enhanced_client | asmack/org/xbill/DNS/TSIG.java | // Path: asmack/org/xbill/DNS/utils/HMAC.java
// public class HMAC {
//
// MessageDigest digest;
// private byte [] ipad, opad;
//
// private static final byte IPAD = 0x36;
// private static final byte OPAD = 0x5c;
// private static final byte PADLEN = 64;
//
// private void
// init(byte [] key) {
// int i;
//
// if (key.length > PADLEN) {
// key = digest.digest(key);
// digest.reset();
// }
// ipad = new byte[PADLEN];
// opad = new byte[PADLEN];
// for (i = 0; i < key.length; i++) {
// ipad[i] = (byte) (key[i] ^ IPAD);
// opad[i] = (byte) (key[i] ^ OPAD);
// }
// for (; i < PADLEN; i++) {
// ipad[i] = IPAD;
// opad[i] = OPAD;
// }
// digest.update(ipad);
// }
//
// /**
// * Creates a new HMAC instance
// * @param digest The message digest object.
// * @param key The secret key
// */
// public
// HMAC(MessageDigest digest, byte [] key) {
// digest.reset();
// this.digest = digest;
// init(key);
// }
//
// /**
// * Creates a new HMAC instance
// * @param digestName The name of the message digest function.
// * @param key The secret key.
// */
// public
// HMAC(String digestName, byte [] key) {
// try {
// digest = MessageDigest.getInstance(digestName);
// } catch (NoSuchAlgorithmException e) {
// throw new IllegalArgumentException("unknown digest algorithm "
// + digestName);
// }
// init(key);
// }
//
// /**
// * Adds data to the current hash
// * @param b The data
// * @param offset The index at which to start adding to the hash
// * @param length The number of bytes to hash
// */
// public void
// update(byte [] b, int offset, int length) {
// digest.update(b, offset, length);
// }
//
// /**
// * Adds data to the current hash
// * @param b The data
// */
// public void
// update(byte [] b) {
// digest.update(b);
// }
//
// /**
// * Signs the data (computes the secure hash)
// * @return An array with the signature
// */
// public byte []
// sign() {
// byte [] output = digest.digest();
// digest.reset();
// digest.update(opad);
// return digest.digest(output);
// }
//
// /**
// * Verifies the data (computes the secure hash and compares it to the input)
// * @param signature The signature to compare against
// * @return true if the signature matched, false otherwise
// */
// public boolean
// verify(byte [] signature) {
// return Arrays.equals(signature, sign());
// }
//
// /**
// * Resets the HMAC object for further use
// */
// public void
// clear() {
// digest.reset();
// digest.update(ipad);
// }
//
// }
| import java.util.Date;
import org.xbill.DNS.utils.HMAC;
import org.xbill.DNS.utils.base64; | // Copyright (c) 1999-2004 Brian Wellington ([email protected])
package org.xbill.DNS;
/**
* Transaction signature handling. This class generates and verifies
* TSIG records on messages, which provide transaction security.
* @see TSIGRecord
*
* @author Brian Wellington
*/
public class TSIG {
private static final String HMAC_MD5_STR = "HMAC-MD5.SIG-ALG.REG.INT.";
private static final String HMAC_SHA1_STR = "hmac-sha1.";
private static final String HMAC_SHA256_STR = "hmac-sha256.";
/** The domain name representing the HMAC-MD5 algorithm. */
public static final Name HMAC_MD5 = Name.fromConstantString(HMAC_MD5_STR);
/** The domain name representing the HMAC-MD5 algorithm (deprecated). */ | // Path: asmack/org/xbill/DNS/utils/HMAC.java
// public class HMAC {
//
// MessageDigest digest;
// private byte [] ipad, opad;
//
// private static final byte IPAD = 0x36;
// private static final byte OPAD = 0x5c;
// private static final byte PADLEN = 64;
//
// private void
// init(byte [] key) {
// int i;
//
// if (key.length > PADLEN) {
// key = digest.digest(key);
// digest.reset();
// }
// ipad = new byte[PADLEN];
// opad = new byte[PADLEN];
// for (i = 0; i < key.length; i++) {
// ipad[i] = (byte) (key[i] ^ IPAD);
// opad[i] = (byte) (key[i] ^ OPAD);
// }
// for (; i < PADLEN; i++) {
// ipad[i] = IPAD;
// opad[i] = OPAD;
// }
// digest.update(ipad);
// }
//
// /**
// * Creates a new HMAC instance
// * @param digest The message digest object.
// * @param key The secret key
// */
// public
// HMAC(MessageDigest digest, byte [] key) {
// digest.reset();
// this.digest = digest;
// init(key);
// }
//
// /**
// * Creates a new HMAC instance
// * @param digestName The name of the message digest function.
// * @param key The secret key.
// */
// public
// HMAC(String digestName, byte [] key) {
// try {
// digest = MessageDigest.getInstance(digestName);
// } catch (NoSuchAlgorithmException e) {
// throw new IllegalArgumentException("unknown digest algorithm "
// + digestName);
// }
// init(key);
// }
//
// /**
// * Adds data to the current hash
// * @param b The data
// * @param offset The index at which to start adding to the hash
// * @param length The number of bytes to hash
// */
// public void
// update(byte [] b, int offset, int length) {
// digest.update(b, offset, length);
// }
//
// /**
// * Adds data to the current hash
// * @param b The data
// */
// public void
// update(byte [] b) {
// digest.update(b);
// }
//
// /**
// * Signs the data (computes the secure hash)
// * @return An array with the signature
// */
// public byte []
// sign() {
// byte [] output = digest.digest();
// digest.reset();
// digest.update(opad);
// return digest.digest(output);
// }
//
// /**
// * Verifies the data (computes the secure hash and compares it to the input)
// * @param signature The signature to compare against
// * @return true if the signature matched, false otherwise
// */
// public boolean
// verify(byte [] signature) {
// return Arrays.equals(signature, sign());
// }
//
// /**
// * Resets the HMAC object for further use
// */
// public void
// clear() {
// digest.reset();
// digest.update(ipad);
// }
//
// }
// Path: asmack/org/xbill/DNS/TSIG.java
import java.util.Date;
import org.xbill.DNS.utils.HMAC;
import org.xbill.DNS.utils.base64;
// Copyright (c) 1999-2004 Brian Wellington ([email protected])
package org.xbill.DNS;
/**
* Transaction signature handling. This class generates and verifies
* TSIG records on messages, which provide transaction security.
* @see TSIGRecord
*
* @author Brian Wellington
*/
public class TSIG {
private static final String HMAC_MD5_STR = "HMAC-MD5.SIG-ALG.REG.INT.";
private static final String HMAC_SHA1_STR = "hmac-sha1.";
private static final String HMAC_SHA256_STR = "hmac-sha256.";
/** The domain name representing the HMAC-MD5 algorithm. */
public static final Name HMAC_MD5 = Name.fromConstantString(HMAC_MD5_STR);
/** The domain name representing the HMAC-MD5 algorithm (deprecated). */ | public static final Name HMAC = HMAC_MD5; |
samuelhehe/androidpn_enhanced_client | asmack/org/jivesoftware/smack/AccountManager.java | // Path: asmack/org/jivesoftware/smack/filter/AndFilter.java
// public class AndFilter implements PacketFilter {
//
// /**
// * The list of filters.
// */
// private List<PacketFilter> filters = new ArrayList<PacketFilter>();
//
// /**
// * Creates an empty AND filter. Filters should be added using the
// * {@link #addFilter(PacketFilter)} method.
// */
// public AndFilter() {
//
// }
//
// /**
// * Creates an AND filter using the specified filters.
// *
// * @param filters the filters to add.
// */
// public AndFilter(PacketFilter... filters) {
// if (filters == null) {
// throw new IllegalArgumentException("Parameter cannot be null.");
// }
// for(PacketFilter filter : filters) {
// if(filter == null) {
// throw new IllegalArgumentException("Parameter cannot be null.");
// }
// this.filters.add(filter);
// }
// }
//
// /**
// * Adds a filter to the filter list for the AND operation. A packet
// * will pass the filter if all of the filters in the list accept it.
// *
// * @param filter a filter to add to the filter list.
// */
// public void addFilter(PacketFilter filter) {
// if (filter == null) {
// throw new IllegalArgumentException("Parameter cannot be null.");
// }
// filters.add(filter);
// }
//
// public boolean accept(Packet packet) {
// for (PacketFilter filter : filters) {
// if (!filter.accept(packet)) {
// return false;
// }
// }
// return true;
// }
//
// public String toString() {
// return filters.toString();
// }
// }
| import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smack.util.StringUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter; | attributes.put(attributeName, "");
}
createAccount(username, password, attributes);
}
/**
* Creates a new account using the specified username, password and account attributes.
* The attributes Map must contain only String name/value pairs and must also have values
* for all required attributes.
*
* @param username the username.
* @param password the password.
* @param attributes the account attributes.
* @throws XMPPException if an error occurs creating the account.
* @see #getAccountAttributes()
*/
public void createAccount(String username, String password, Map<String, String> attributes)
throws XMPPException
{
if (!supportsAccountCreation()) {
throw new XMPPException("Server does not support account creation.");
}
Registration reg = new Registration();
reg.setType(IQ.Type.SET);
reg.setTo(connection.getServiceName());
reg.setUsername(username);
reg.setPassword(password);
for(String s : attributes.keySet()){
reg.addAttribute(s, attributes.get(s));
} | // Path: asmack/org/jivesoftware/smack/filter/AndFilter.java
// public class AndFilter implements PacketFilter {
//
// /**
// * The list of filters.
// */
// private List<PacketFilter> filters = new ArrayList<PacketFilter>();
//
// /**
// * Creates an empty AND filter. Filters should be added using the
// * {@link #addFilter(PacketFilter)} method.
// */
// public AndFilter() {
//
// }
//
// /**
// * Creates an AND filter using the specified filters.
// *
// * @param filters the filters to add.
// */
// public AndFilter(PacketFilter... filters) {
// if (filters == null) {
// throw new IllegalArgumentException("Parameter cannot be null.");
// }
// for(PacketFilter filter : filters) {
// if(filter == null) {
// throw new IllegalArgumentException("Parameter cannot be null.");
// }
// this.filters.add(filter);
// }
// }
//
// /**
// * Adds a filter to the filter list for the AND operation. A packet
// * will pass the filter if all of the filters in the list accept it.
// *
// * @param filter a filter to add to the filter list.
// */
// public void addFilter(PacketFilter filter) {
// if (filter == null) {
// throw new IllegalArgumentException("Parameter cannot be null.");
// }
// filters.add(filter);
// }
//
// public boolean accept(Packet packet) {
// for (PacketFilter filter : filters) {
// if (!filter.accept(packet)) {
// return false;
// }
// }
// return true;
// }
//
// public String toString() {
// return filters.toString();
// }
// }
// Path: asmack/org/jivesoftware/smack/AccountManager.java
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smack.util.StringUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
attributes.put(attributeName, "");
}
createAccount(username, password, attributes);
}
/**
* Creates a new account using the specified username, password and account attributes.
* The attributes Map must contain only String name/value pairs and must also have values
* for all required attributes.
*
* @param username the username.
* @param password the password.
* @param attributes the account attributes.
* @throws XMPPException if an error occurs creating the account.
* @see #getAccountAttributes()
*/
public void createAccount(String username, String password, Map<String, String> attributes)
throws XMPPException
{
if (!supportsAccountCreation()) {
throw new XMPPException("Server does not support account creation.");
}
Registration reg = new Registration();
reg.setType(IQ.Type.SET);
reg.setTo(connection.getServiceName());
reg.setUsername(username);
reg.setPassword(password);
for(String s : attributes.keySet()){
reg.addAttribute(s, attributes.get(s));
} | PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), |
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/client/connection/factory/HttpConnectionFactory.java | // Path: src/main/java/com/biasedbit/hotpotato/client/connection/HttpConnection.java
// public interface HttpConnection extends ChannelHandler {
//
// /**
// * Shut down the connection, cancelling all requests executing meanwhile.
// * <p/>
// * After a connection is shut down, no more requests will be accepted.
// */
// void terminate();
//
// /**
// * Returns the unique identifier of this connection.
// *
// * @return An identifier of the connection.
// */
// String getId();
//
// /**
// * Returns the host address to which this connection is connected to.
// *
// * @return The host address to which this connection is currently connected to.
// */
// String getHost();
//
// /**
// * Returns the port to which this connection is connected to.
// *
// * @return The port of to which this connection is connected to.
// */
// int getPort();
//
// /**
// * Returns whether this connection is available to process a request. Connections that execute HTTP 1.0 requests
// * will <strong>never</strong> return true after the request has been approved for processing as the socket will
// * be closed by the server.
// *
// * @return true if this connection is connected and ready to execute a request
// */
// boolean isAvailable();
//
// /**
// * Execute a given request context in this connection. All calls to this method should first test whether this
// * connection is available or not by calling {@link #isAvailable()} first. If this method is called while
// * {@link #isAvailable()} would return {@code false}, then implementations will instantly cause a failure on the
// * request with the reason {@link com.biasedbit.hotpotato.request.HttpRequestFuture#EXECUTION_REJECTED} and return
// * {@code true}, meaning the request was consumed (and failed).
// * <p/>
// * The exception to the above rule is when the request is submitted and the connection goes down meanwhile. In this
// * case, the request <strong>will not</strong> be marked as failed and this method will return {@code false} so that
// * the caller may retry the same request in another connection.
// * <p/>
// * You should always, <strong>always</strong> test first with {@link #isAvailable()}.
// * <p/>
// * This is a non-blocking call.
// *
// * @param context Request execution context.
// *
// * @return {@code true} if the request was accepted, {@code false} otherwise. If a request is accepted, the
// * {@code HttpConnection} becomes responsible for calling {@link
// * com.biasedbit.hotpotato.request.HttpRequestFuture#setFailure(Throwable) setFailure()} or {@link
// * com.biasedbit.hotpotato.request.HttpRequestFuture#setSuccess(Object,
// * org.jboss.netty.handler.codec.http.HttpResponse) setSuccess()} on it.
// */
// boolean execute(HttpRequestContext context);
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/connection/HttpConnectionListener.java
// public interface HttpConnectionListener {
//
// /**
// * Connection opened event, called by the {@link HttpConnection} when a requested connection establishes.
// *
// * @param connection Connection that just established.
// */
// void connectionOpened(HttpConnection connection);
//
// /**
// * Connection terminated event, called by the {@link HttpConnection} when an active connection disconnects.
// *
// * This is the event that {@link HttpConnection}s that support submission of multiple parallel requests call to
// * signal disconnection, since some of the requests may still be executed in another connection (e.g. a pipelining
// * connection that goes down after a couple of requests but still has some more idempotent requests queued).
// *
// * @param connection Connection that was disconnected.
// * @param retryRequests List of pending submitted requests that should be retried in a new connection, if possible.
// */
// void connectionTerminated(HttpConnection connection, Collection<HttpRequestContext> retryRequests);
//
// /**
// * Connection terminated event, called by the {@link HttpConnection} when an active connection disconnects.
// *
// * This is the event that {@link HttpConnection}s that only support a single request at a time use to signal
// * disconnection. It can also be used by {@link HttpConnection}s that support submission of multiple parallel
// * requests (e.g. a pipelining connection) when they disconnect and have no requests that should be retried (i.e.
// * all pipelined requests executed successfully).
// *
// * @param connection Connection that was disconnected.
// */
// void connectionTerminated(HttpConnection connection);
//
// /**
// * Connection failed event, called by the {@link HttpConnection} when a connection attempt fails.
// *
// * @param connection Connection that failed.
// */
// void connectionFailed(HttpConnection connection);
//
// /**
// * Request complete event, called by the {@link HttpConnection} when a response to a request allocated to it is
// * either received or fails for some reason.
// *
// * @param connection Connection in which the event finished.
// * @param context Request context containing the request that has completed.
// */
// void requestFinished(HttpConnection connection, HttpRequestContext context);
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/timeout/TimeoutManager.java
// public interface TimeoutManager {
//
// boolean init();
//
// void terminate();
//
// /**
// * Manage the timeout for the provided context.
// *
// * @param context The request context to monitor. Timeout value is extracted from {@link
// * com.biasedbit.hotpotato.client.HttpRequestContext#getTimeout()}.
// */
// void manageRequestTimeout(HttpRequestContext context);
// }
| import com.biasedbit.hotpotato.client.connection.HttpConnection;
import com.biasedbit.hotpotato.client.connection.HttpConnectionListener;
import com.biasedbit.hotpotato.client.timeout.TimeoutManager;
import java.util.concurrent.Executor; | /*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.connection.factory;
/**
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public interface HttpConnectionFactory {
HttpConnection createConnection(String id, String host, int port, HttpConnectionListener listener, | // Path: src/main/java/com/biasedbit/hotpotato/client/connection/HttpConnection.java
// public interface HttpConnection extends ChannelHandler {
//
// /**
// * Shut down the connection, cancelling all requests executing meanwhile.
// * <p/>
// * After a connection is shut down, no more requests will be accepted.
// */
// void terminate();
//
// /**
// * Returns the unique identifier of this connection.
// *
// * @return An identifier of the connection.
// */
// String getId();
//
// /**
// * Returns the host address to which this connection is connected to.
// *
// * @return The host address to which this connection is currently connected to.
// */
// String getHost();
//
// /**
// * Returns the port to which this connection is connected to.
// *
// * @return The port of to which this connection is connected to.
// */
// int getPort();
//
// /**
// * Returns whether this connection is available to process a request. Connections that execute HTTP 1.0 requests
// * will <strong>never</strong> return true after the request has been approved for processing as the socket will
// * be closed by the server.
// *
// * @return true if this connection is connected and ready to execute a request
// */
// boolean isAvailable();
//
// /**
// * Execute a given request context in this connection. All calls to this method should first test whether this
// * connection is available or not by calling {@link #isAvailable()} first. If this method is called while
// * {@link #isAvailable()} would return {@code false}, then implementations will instantly cause a failure on the
// * request with the reason {@link com.biasedbit.hotpotato.request.HttpRequestFuture#EXECUTION_REJECTED} and return
// * {@code true}, meaning the request was consumed (and failed).
// * <p/>
// * The exception to the above rule is when the request is submitted and the connection goes down meanwhile. In this
// * case, the request <strong>will not</strong> be marked as failed and this method will return {@code false} so that
// * the caller may retry the same request in another connection.
// * <p/>
// * You should always, <strong>always</strong> test first with {@link #isAvailable()}.
// * <p/>
// * This is a non-blocking call.
// *
// * @param context Request execution context.
// *
// * @return {@code true} if the request was accepted, {@code false} otherwise. If a request is accepted, the
// * {@code HttpConnection} becomes responsible for calling {@link
// * com.biasedbit.hotpotato.request.HttpRequestFuture#setFailure(Throwable) setFailure()} or {@link
// * com.biasedbit.hotpotato.request.HttpRequestFuture#setSuccess(Object,
// * org.jboss.netty.handler.codec.http.HttpResponse) setSuccess()} on it.
// */
// boolean execute(HttpRequestContext context);
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/connection/HttpConnectionListener.java
// public interface HttpConnectionListener {
//
// /**
// * Connection opened event, called by the {@link HttpConnection} when a requested connection establishes.
// *
// * @param connection Connection that just established.
// */
// void connectionOpened(HttpConnection connection);
//
// /**
// * Connection terminated event, called by the {@link HttpConnection} when an active connection disconnects.
// *
// * This is the event that {@link HttpConnection}s that support submission of multiple parallel requests call to
// * signal disconnection, since some of the requests may still be executed in another connection (e.g. a pipelining
// * connection that goes down after a couple of requests but still has some more idempotent requests queued).
// *
// * @param connection Connection that was disconnected.
// * @param retryRequests List of pending submitted requests that should be retried in a new connection, if possible.
// */
// void connectionTerminated(HttpConnection connection, Collection<HttpRequestContext> retryRequests);
//
// /**
// * Connection terminated event, called by the {@link HttpConnection} when an active connection disconnects.
// *
// * This is the event that {@link HttpConnection}s that only support a single request at a time use to signal
// * disconnection. It can also be used by {@link HttpConnection}s that support submission of multiple parallel
// * requests (e.g. a pipelining connection) when they disconnect and have no requests that should be retried (i.e.
// * all pipelined requests executed successfully).
// *
// * @param connection Connection that was disconnected.
// */
// void connectionTerminated(HttpConnection connection);
//
// /**
// * Connection failed event, called by the {@link HttpConnection} when a connection attempt fails.
// *
// * @param connection Connection that failed.
// */
// void connectionFailed(HttpConnection connection);
//
// /**
// * Request complete event, called by the {@link HttpConnection} when a response to a request allocated to it is
// * either received or fails for some reason.
// *
// * @param connection Connection in which the event finished.
// * @param context Request context containing the request that has completed.
// */
// void requestFinished(HttpConnection connection, HttpRequestContext context);
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/timeout/TimeoutManager.java
// public interface TimeoutManager {
//
// boolean init();
//
// void terminate();
//
// /**
// * Manage the timeout for the provided context.
// *
// * @param context The request context to monitor. Timeout value is extracted from {@link
// * com.biasedbit.hotpotato.client.HttpRequestContext#getTimeout()}.
// */
// void manageRequestTimeout(HttpRequestContext context);
// }
// Path: src/main/java/com/biasedbit/hotpotato/client/connection/factory/HttpConnectionFactory.java
import com.biasedbit.hotpotato.client.connection.HttpConnection;
import com.biasedbit.hotpotato.client.connection.HttpConnectionListener;
import com.biasedbit.hotpotato.client.timeout.TimeoutManager;
import java.util.concurrent.Executor;
/*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.connection.factory;
/**
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public interface HttpConnectionFactory {
HttpConnection createConnection(String id, String host, int port, HttpConnectionListener listener, | TimeoutManager manager); |
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/request/HttpRequestFuture.java | // Path: src/main/java/com/biasedbit/hotpotato/client/HttpClient.java
// public interface HttpClient {
//
// /**
// * Initialise the instance.
// * <p/>
// * All clients must be initialised prior to their usage. Calling any of the {@code execute()} methods on a client
// * prior to calling {@code init()} will result in a {@link CannotExecuteRequestException}.
// *
// * @return {@code true} if successfully initialised, {@code false} otherwise.
// */
// boolean init();
//
// /**
// * Terminate the instance.
// * <p/>
// * When a client is no longer needed, it should be properly shut down by calling {@code terminate()} in order to
// * release resources.
// * <p/>
// * Terminating a client while it is still processing requests will result in all requests being finished (failing),
// * no matter if they are in the event queue, request queue or already executing inside a connection.
// */
// void terminate();
//
// /**
// * Executes a request to a given host on port 80 with default timeout of the client.
// *
// * @param host Destination host.
// * @param port Destination port.
// * @param request Request to execute.
// * @param processor Response body processor.
// *
// * @return Future associated with the operation.
// *
// * @throws CannotExecuteRequestException Thrown when the request is invalid or the client can no longer accept
// * requests, either due to termination or full queue.
// */
// <T> HttpRequestFuture<T> execute(String host, int port, HttpRequest request, HttpResponseProcessor<T> processor)
// throws CannotExecuteRequestException;
//
// /**
// * Version of {@code execute()} that allows manual definition of timeout.
// *
// * @param host Destination host.
// * @param port Destination port.
// * @param timeout Manual timeout for the operation to complete. This timeout is related to the request execution
// * time once it enters a connection, not the full lifecycle of the request. If there are many
// * events in the event queue it is likely that the request will have to wait a couple of
// * milliseconds before actually entering a connection.
// * @param request Request to execute.
// * @param processor Response body processor.
// *
// * @return Future associated with the operation.
// *
// * @throws CannotExecuteRequestException Thrown when the request is invalid or the client can no longer accept
// * requests, either due to termination or full queue.
// */
// <T> HttpRequestFuture<T> execute(String host, int port, int timeout, HttpRequest request,
// HttpResponseProcessor<T> processor)
// throws CannotExecuteRequestException;
//
// /**
// * Version {@code execute()} that discards the result of the operation.
// *
// * @param host Destination host.
// * @param port Destination port.
// * @param request Request to execute.
// *
// * @return Future associated with the operation.
// *
// * @throws CannotExecuteRequestException Thrown when the request is invalid or the client can no longer accept
// * requests, either due to termination or full queue.
// */
// HttpRequestFuture execute(String host, int port, HttpRequest request)
// throws CannotExecuteRequestException;
//
// boolean isHttps();
// }
| import com.biasedbit.hotpotato.client.HttpClient;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import java.util.concurrent.TimeUnit; | *
* @param timeoutMillis Time alloted for the wait, in milliseconds.
*
* @return {@code true} if and only if the future was completed within the specified time limit
*
* @throws InterruptedException if the current thread was interrupted
*/
boolean await(long timeoutMillis) throws InterruptedException;
/**
* Waits for this future to be completed within the specified time limit without interruption. This method catches
* an {@link InterruptedException} and discards it silently.
*
* @param timeout Time alloted for the wait.
* @param unit Unit of time to wait.
*
* @return {@code true} if and only if the future was completed within the specified time limit
*/
boolean awaitUninterruptibly(long timeout, TimeUnit unit);
/**
* Waits for this future to be completed within the specified time limit without interruption. This method catches
* an {@link InterruptedException} and discards it silently.
*
* @param timeoutMillis Time alloted for the wait, in milliseconds.
*
* @return {@code true} if and only if the future was completed within the specified time limit
*/
boolean awaitUninterruptibly(long timeoutMillis);
| // Path: src/main/java/com/biasedbit/hotpotato/client/HttpClient.java
// public interface HttpClient {
//
// /**
// * Initialise the instance.
// * <p/>
// * All clients must be initialised prior to their usage. Calling any of the {@code execute()} methods on a client
// * prior to calling {@code init()} will result in a {@link CannotExecuteRequestException}.
// *
// * @return {@code true} if successfully initialised, {@code false} otherwise.
// */
// boolean init();
//
// /**
// * Terminate the instance.
// * <p/>
// * When a client is no longer needed, it should be properly shut down by calling {@code terminate()} in order to
// * release resources.
// * <p/>
// * Terminating a client while it is still processing requests will result in all requests being finished (failing),
// * no matter if they are in the event queue, request queue or already executing inside a connection.
// */
// void terminate();
//
// /**
// * Executes a request to a given host on port 80 with default timeout of the client.
// *
// * @param host Destination host.
// * @param port Destination port.
// * @param request Request to execute.
// * @param processor Response body processor.
// *
// * @return Future associated with the operation.
// *
// * @throws CannotExecuteRequestException Thrown when the request is invalid or the client can no longer accept
// * requests, either due to termination or full queue.
// */
// <T> HttpRequestFuture<T> execute(String host, int port, HttpRequest request, HttpResponseProcessor<T> processor)
// throws CannotExecuteRequestException;
//
// /**
// * Version of {@code execute()} that allows manual definition of timeout.
// *
// * @param host Destination host.
// * @param port Destination port.
// * @param timeout Manual timeout for the operation to complete. This timeout is related to the request execution
// * time once it enters a connection, not the full lifecycle of the request. If there are many
// * events in the event queue it is likely that the request will have to wait a couple of
// * milliseconds before actually entering a connection.
// * @param request Request to execute.
// * @param processor Response body processor.
// *
// * @return Future associated with the operation.
// *
// * @throws CannotExecuteRequestException Thrown when the request is invalid or the client can no longer accept
// * requests, either due to termination or full queue.
// */
// <T> HttpRequestFuture<T> execute(String host, int port, int timeout, HttpRequest request,
// HttpResponseProcessor<T> processor)
// throws CannotExecuteRequestException;
//
// /**
// * Version {@code execute()} that discards the result of the operation.
// *
// * @param host Destination host.
// * @param port Destination port.
// * @param request Request to execute.
// *
// * @return Future associated with the operation.
// *
// * @throws CannotExecuteRequestException Thrown when the request is invalid or the client can no longer accept
// * requests, either due to termination or full queue.
// */
// HttpRequestFuture execute(String host, int port, HttpRequest request)
// throws CannotExecuteRequestException;
//
// boolean isHttps();
// }
// Path: src/main/java/com/biasedbit/hotpotato/request/HttpRequestFuture.java
import com.biasedbit.hotpotato.client.HttpClient;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import java.util.concurrent.TimeUnit;
*
* @param timeoutMillis Time alloted for the wait, in milliseconds.
*
* @return {@code true} if and only if the future was completed within the specified time limit
*
* @throws InterruptedException if the current thread was interrupted
*/
boolean await(long timeoutMillis) throws InterruptedException;
/**
* Waits for this future to be completed within the specified time limit without interruption. This method catches
* an {@link InterruptedException} and discards it silently.
*
* @param timeout Time alloted for the wait.
* @param unit Unit of time to wait.
*
* @return {@code true} if and only if the future was completed within the specified time limit
*/
boolean awaitUninterruptibly(long timeout, TimeUnit unit);
/**
* Waits for this future to be completed within the specified time limit without interruption. This method catches
* an {@link InterruptedException} and discards it silently.
*
* @param timeoutMillis Time alloted for the wait, in milliseconds.
*
* @return {@code true} if and only if the future was completed within the specified time limit
*/
boolean awaitUninterruptibly(long timeoutMillis);
| HttpClient getClient(); |
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/util/DummyHttpServer.java | // Path: src/main/java/org/jboss/netty/example/securechat/SecureChatSslContextFactory.java
// public class SecureChatSslContextFactory {
//
// private static final String PROTOCOL = "TLS";
// private static final SSLContext SERVER_CONTEXT;
// private static final SSLContext CLIENT_CONTEXT;
//
// static {
// String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
// if (algorithm == null) {
// algorithm = "SunX509";
// }
//
// SSLContext serverContext;
// SSLContext clientContext;
// try {
// KeyStore ks = KeyStore.getInstance("JKS");
// ks.load(SecureChatKeyStore.asInputStream(), SecureChatKeyStore.getKeyStorePassword());
//
// // Set up key manager factory to use our key store
// KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
// kmf.init(ks, SecureChatKeyStore.getCertificatePassword());
//
// // Initialize the SSLContext to work with our key managers.
// serverContext = SSLContext.getInstance(PROTOCOL);
// serverContext.init(kmf.getKeyManagers(), SecureChatTrustManagerFactory.getTrustManagers(), null);
// } catch (Exception e) {
// throw new Error("Failed to initialize the server-side SSLContext", e);
// }
//
// try {
// clientContext = SSLContext.getInstance(PROTOCOL);
// clientContext.init(null, SecureChatTrustManagerFactory.getTrustManagers(), null);
// } catch (Exception e) {
// throw new Error("Failed to initialize the client-side SSLContext", e);
// }
//
// SERVER_CONTEXT = serverContext;
// CLIENT_CONTEXT = clientContext;
// }
//
// public static SSLContext getServerContext() {
// return SERVER_CONTEXT;
// }
//
// public static SSLContext getClientContext() {
// return CLIENT_CONTEXT;
// }
// }
| import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory;
import org.jboss.netty.example.securechat.SecureChatSslContextFactory;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.util.CharsetUtil;
import javax.net.ssl.SSLEngine;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger; |
this.useSsl = USE_SSL;
this.failureProbability = FAILURE_PROBABILITY;
this.responseLatency = RESPONSE_LATENCY;
this.content = CONTENT;
this.useOldIo = USE_OLD_IO;
}
public DummyHttpServer(int port) {
this(null, port);
}
// public methods -------------------------------------------------------------------------------------------------
public boolean init() {
if (this.useOldIo) {
this.bootstrap = new ServerBootstrap(new OioServerSocketChannelFactory(Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
} else {
this.bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
}
this.bootstrap.setOption("child.tcpNoDelay", true);
this.bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
if (useSsl) { | // Path: src/main/java/org/jboss/netty/example/securechat/SecureChatSslContextFactory.java
// public class SecureChatSslContextFactory {
//
// private static final String PROTOCOL = "TLS";
// private static final SSLContext SERVER_CONTEXT;
// private static final SSLContext CLIENT_CONTEXT;
//
// static {
// String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
// if (algorithm == null) {
// algorithm = "SunX509";
// }
//
// SSLContext serverContext;
// SSLContext clientContext;
// try {
// KeyStore ks = KeyStore.getInstance("JKS");
// ks.load(SecureChatKeyStore.asInputStream(), SecureChatKeyStore.getKeyStorePassword());
//
// // Set up key manager factory to use our key store
// KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
// kmf.init(ks, SecureChatKeyStore.getCertificatePassword());
//
// // Initialize the SSLContext to work with our key managers.
// serverContext = SSLContext.getInstance(PROTOCOL);
// serverContext.init(kmf.getKeyManagers(), SecureChatTrustManagerFactory.getTrustManagers(), null);
// } catch (Exception e) {
// throw new Error("Failed to initialize the server-side SSLContext", e);
// }
//
// try {
// clientContext = SSLContext.getInstance(PROTOCOL);
// clientContext.init(null, SecureChatTrustManagerFactory.getTrustManagers(), null);
// } catch (Exception e) {
// throw new Error("Failed to initialize the client-side SSLContext", e);
// }
//
// SERVER_CONTEXT = serverContext;
// CLIENT_CONTEXT = clientContext;
// }
//
// public static SSLContext getServerContext() {
// return SERVER_CONTEXT;
// }
//
// public static SSLContext getClientContext() {
// return CLIENT_CONTEXT;
// }
// }
// Path: src/main/java/com/biasedbit/hotpotato/util/DummyHttpServer.java
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory;
import org.jboss.netty.example.securechat.SecureChatSslContextFactory;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.util.CharsetUtil;
import javax.net.ssl.SSLEngine;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
this.useSsl = USE_SSL;
this.failureProbability = FAILURE_PROBABILITY;
this.responseLatency = RESPONSE_LATENCY;
this.content = CONTENT;
this.useOldIo = USE_OLD_IO;
}
public DummyHttpServer(int port) {
this(null, port);
}
// public methods -------------------------------------------------------------------------------------------------
public boolean init() {
if (this.useOldIo) {
this.bootstrap = new ServerBootstrap(new OioServerSocketChannelFactory(Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
} else {
this.bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
}
this.bootstrap.setOption("child.tcpNoDelay", true);
this.bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
if (useSsl) { | SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine(); |
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/client/timeout/TimeoutManager.java | // Path: src/main/java/com/biasedbit/hotpotato/client/HttpRequestContext.java
// public class HttpRequestContext<T> {
//
// // internal vars --------------------------------------------------------------------------------------------------
//
// private final String host;
// private final int port;
// private final int timeout;
// private final HttpRequest request;
// private final HttpResponseProcessor<T> processor;
// private final HttpRequestFuture<T> future;
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public HttpRequestContext(String host, int port, int timeout, HttpRequest request,
// HttpResponseProcessor<T> processor, HttpRequestFuture<T> future) {
// if (host == null) {
// throw new IllegalArgumentException("Host cannot be null");
// }
// if ((port <= 0) || (port > 65536)) {
// throw new IllegalArgumentException("Invalid port: " + port);
// }
// if (request == null) {
// throw new IllegalArgumentException("HttpRequest cannot be null");
// }
// if (processor == null) {
// throw new IllegalArgumentException("HttpResponseProcessor cannot be null");
// }
// if (future == null) {
// throw new IllegalArgumentException("HttpRequestFuture cannot be null");
// }
//
// this.timeout = timeout < 0 ? 0 : timeout;
// this.host = host;
// this.port = port;
// this.request = request;
// this.processor = processor;
// this.future = future;
// }
//
// public HttpRequestContext(String host, int timeout, HttpRequest request, HttpResponseProcessor<T> processor,
// HttpRequestFuture<T> future) {
// this(host, 80, timeout, request, processor, future);
// }
//
// // public methods -------------------------------------------------------------------------------------------------
//
// /**
// * Determines (based on request method) if a request is idempotent or not, based on recommendations of the RFC.
// *
// * Idempotent requests: GET, HEAD, PUT, DELETE, OPTIONS, TRACE
// * Non-idempotent requests: POST, PATCH, CONNECT (not sure about this last one, couldn't find any info on it...)
// *
// * @return true if request is idempotent, false otherwise.
// */
// public boolean isIdempotent() {
// return !(this.request.getMethod().equals(HttpMethod.POST) ||
// this.request.getMethod().equals(HttpMethod.PATCH) ||
// this.request.getMethod().equals(HttpMethod.CONNECT));
// }
//
// // getters & setters ----------------------------------------------------------------------------------------------
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public HttpRequest getRequest() {
// return request;
// }
//
// public HttpResponseProcessor<T> getProcessor() {
// return processor;
// }
//
// public HttpRequestFuture<T> getFuture() {
// return future;
// }
//
// // low level overrides --------------------------------------------------------------------------------------------
//
// @Override
// public String toString() {
// return new StringBuilder()
// .append(this.request.getProtocolVersion()).append(' ')
// .append(this.request.getMethod()).append(' ')
// .append(this.request.getUri()).append(" (")
// .append(this.host).append(':')
// .append(this.port).append(')').append("@").append(Integer.toHexString(this.hashCode())).toString();
// }
// }
| import com.biasedbit.hotpotato.client.HttpRequestContext; | /*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.timeout;
/**
* Facility to manage timeouts for requests.
*
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public interface TimeoutManager {
boolean init();
void terminate();
/**
* Manage the timeout for the provided context.
*
* @param context The request context to monitor. Timeout value is extracted from {@link
* com.biasedbit.hotpotato.client.HttpRequestContext#getTimeout()}.
*/ | // Path: src/main/java/com/biasedbit/hotpotato/client/HttpRequestContext.java
// public class HttpRequestContext<T> {
//
// // internal vars --------------------------------------------------------------------------------------------------
//
// private final String host;
// private final int port;
// private final int timeout;
// private final HttpRequest request;
// private final HttpResponseProcessor<T> processor;
// private final HttpRequestFuture<T> future;
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public HttpRequestContext(String host, int port, int timeout, HttpRequest request,
// HttpResponseProcessor<T> processor, HttpRequestFuture<T> future) {
// if (host == null) {
// throw new IllegalArgumentException("Host cannot be null");
// }
// if ((port <= 0) || (port > 65536)) {
// throw new IllegalArgumentException("Invalid port: " + port);
// }
// if (request == null) {
// throw new IllegalArgumentException("HttpRequest cannot be null");
// }
// if (processor == null) {
// throw new IllegalArgumentException("HttpResponseProcessor cannot be null");
// }
// if (future == null) {
// throw new IllegalArgumentException("HttpRequestFuture cannot be null");
// }
//
// this.timeout = timeout < 0 ? 0 : timeout;
// this.host = host;
// this.port = port;
// this.request = request;
// this.processor = processor;
// this.future = future;
// }
//
// public HttpRequestContext(String host, int timeout, HttpRequest request, HttpResponseProcessor<T> processor,
// HttpRequestFuture<T> future) {
// this(host, 80, timeout, request, processor, future);
// }
//
// // public methods -------------------------------------------------------------------------------------------------
//
// /**
// * Determines (based on request method) if a request is idempotent or not, based on recommendations of the RFC.
// *
// * Idempotent requests: GET, HEAD, PUT, DELETE, OPTIONS, TRACE
// * Non-idempotent requests: POST, PATCH, CONNECT (not sure about this last one, couldn't find any info on it...)
// *
// * @return true if request is idempotent, false otherwise.
// */
// public boolean isIdempotent() {
// return !(this.request.getMethod().equals(HttpMethod.POST) ||
// this.request.getMethod().equals(HttpMethod.PATCH) ||
// this.request.getMethod().equals(HttpMethod.CONNECT));
// }
//
// // getters & setters ----------------------------------------------------------------------------------------------
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public HttpRequest getRequest() {
// return request;
// }
//
// public HttpResponseProcessor<T> getProcessor() {
// return processor;
// }
//
// public HttpRequestFuture<T> getFuture() {
// return future;
// }
//
// // low level overrides --------------------------------------------------------------------------------------------
//
// @Override
// public String toString() {
// return new StringBuilder()
// .append(this.request.getProtocolVersion()).append(' ')
// .append(this.request.getMethod()).append(' ')
// .append(this.request.getUri()).append(" (")
// .append(this.host).append(':')
// .append(this.port).append(')').append("@").append(Integer.toHexString(this.hashCode())).toString();
// }
// }
// Path: src/main/java/com/biasedbit/hotpotato/client/timeout/TimeoutManager.java
import com.biasedbit.hotpotato.client.HttpRequestContext;
/*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.timeout;
/**
* Facility to manage timeouts for requests.
*
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public interface TimeoutManager {
boolean init();
void terminate();
/**
* Manage the timeout for the provided context.
*
* @param context The request context to monitor. Timeout value is extracted from {@link
* com.biasedbit.hotpotato.client.HttpRequestContext#getTimeout()}.
*/ | void manageRequestTimeout(HttpRequestContext context); |
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/util/digest/DigestUtils.java | // Path: src/main/java/com/biasedbit/hotpotato/util/TextUtils.java
// public class TextUtils {
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// private TextUtils() {
//
// }
//
// // public static methods ------------------------------------------------------------------------------------------
//
// /**
// * Hash a string
// *
// * @param toHash String to be hashed.
// *
// * @return Hashed string.
// */
// public static String hash(Object toHash) {
// String hashString = toHash.toString();
// MessageDigest md;
// try {
// md = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException e) {
// return hashString;
// }
//
// md.update(hashString.getBytes(), 0, hashString.length());
// return convertToHex(md.digest());
// }
//
// public static String convertToHex(byte[] data) {
// StringBuffer buf = new StringBuffer();
// for (byte aData : data) {
// int halfbyte = (aData >>> 4) & 0x0F;
// int two_halfs = 0;
// do {
// if ((0 <= halfbyte) && (halfbyte <= 9)) {
// buf.append((char) ('0' + halfbyte));
// } else {
// buf.append((char) ('a' + (halfbyte - 10)));
// }
// halfbyte = aData & 0x0F;
// } while (two_halfs++ < 1);
// }
// return buf.toString();
// }
//
// /**
// * Returns a string with a given characted repeated n times.
// *
// * @param str String.
// * @param times Number of repetitions.
// *
// * @return String with <code>times</code> repetitions of <code>str</code>
// */
// public static String repeat(Object str, int times) {
// StringBuilder builder = new StringBuilder(str.toString());
// for (int i = 1; i < times; i++) {
// builder.append(str);
// }
//
// return builder.toString();
// }
// }
| import com.biasedbit.hotpotato.util.TextUtils;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
| }
Map<String, String> response = new HashMap<String, String>();
response.put(SCHEME, header.substring(0, firstSpace));
String[] params = header.substring(firstSpace + 1).split(",");
if (params.length < 4) {
throw new ParseException("Invalid header content: username, response, nonce & uri are required", 0);
}
for (String param : params) {
param = param.trim();
Matcher m = PROPERTY_PATTERN.matcher(param);
if (m.find()) {
response.put(m.group(1), m.group(3));
}
}
return response;
}
public static DigestAuthChallengeResponse computeResponse(DigestAuthChallenge challenge, String method, String content,
String uri, String username, String password, int nonceCount)
throws ParseException {
String realm = challenge.getRealm();
String nonce = challenge.getNonce();
String cnonce = null;
String qop = challenge.getQop();
boolean hasQop = (qop != null) && (qop.length() > 0);
String nc = toNonceCount(nonceCount);
| // Path: src/main/java/com/biasedbit/hotpotato/util/TextUtils.java
// public class TextUtils {
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// private TextUtils() {
//
// }
//
// // public static methods ------------------------------------------------------------------------------------------
//
// /**
// * Hash a string
// *
// * @param toHash String to be hashed.
// *
// * @return Hashed string.
// */
// public static String hash(Object toHash) {
// String hashString = toHash.toString();
// MessageDigest md;
// try {
// md = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException e) {
// return hashString;
// }
//
// md.update(hashString.getBytes(), 0, hashString.length());
// return convertToHex(md.digest());
// }
//
// public static String convertToHex(byte[] data) {
// StringBuffer buf = new StringBuffer();
// for (byte aData : data) {
// int halfbyte = (aData >>> 4) & 0x0F;
// int two_halfs = 0;
// do {
// if ((0 <= halfbyte) && (halfbyte <= 9)) {
// buf.append((char) ('0' + halfbyte));
// } else {
// buf.append((char) ('a' + (halfbyte - 10)));
// }
// halfbyte = aData & 0x0F;
// } while (two_halfs++ < 1);
// }
// return buf.toString();
// }
//
// /**
// * Returns a string with a given characted repeated n times.
// *
// * @param str String.
// * @param times Number of repetitions.
// *
// * @return String with <code>times</code> repetitions of <code>str</code>
// */
// public static String repeat(Object str, int times) {
// StringBuilder builder = new StringBuilder(str.toString());
// for (int i = 1; i < times; i++) {
// builder.append(str);
// }
//
// return builder.toString();
// }
// }
// Path: src/main/java/com/biasedbit/hotpotato/util/digest/DigestUtils.java
import com.biasedbit.hotpotato.util.TextUtils;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
}
Map<String, String> response = new HashMap<String, String>();
response.put(SCHEME, header.substring(0, firstSpace));
String[] params = header.substring(firstSpace + 1).split(",");
if (params.length < 4) {
throw new ParseException("Invalid header content: username, response, nonce & uri are required", 0);
}
for (String param : params) {
param = param.trim();
Matcher m = PROPERTY_PATTERN.matcher(param);
if (m.find()) {
response.put(m.group(1), m.group(3));
}
}
return response;
}
public static DigestAuthChallengeResponse computeResponse(DigestAuthChallenge challenge, String method, String content,
String uri, String username, String password, int nonceCount)
throws ParseException {
String realm = challenge.getRealm();
String nonce = challenge.getNonce();
String cnonce = null;
String qop = challenge.getQop();
boolean hasQop = (qop != null) && (qop.length() > 0);
String nc = toNonceCount(nonceCount);
| String ha1 = TextUtils.hash(new StringBuilder()
|
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/client/ConnectionPool.java | // Path: src/main/java/com/biasedbit/hotpotato/client/connection/HttpConnection.java
// public interface HttpConnection extends ChannelHandler {
//
// /**
// * Shut down the connection, cancelling all requests executing meanwhile.
// * <p/>
// * After a connection is shut down, no more requests will be accepted.
// */
// void terminate();
//
// /**
// * Returns the unique identifier of this connection.
// *
// * @return An identifier of the connection.
// */
// String getId();
//
// /**
// * Returns the host address to which this connection is connected to.
// *
// * @return The host address to which this connection is currently connected to.
// */
// String getHost();
//
// /**
// * Returns the port to which this connection is connected to.
// *
// * @return The port of to which this connection is connected to.
// */
// int getPort();
//
// /**
// * Returns whether this connection is available to process a request. Connections that execute HTTP 1.0 requests
// * will <strong>never</strong> return true after the request has been approved for processing as the socket will
// * be closed by the server.
// *
// * @return true if this connection is connected and ready to execute a request
// */
// boolean isAvailable();
//
// /**
// * Execute a given request context in this connection. All calls to this method should first test whether this
// * connection is available or not by calling {@link #isAvailable()} first. If this method is called while
// * {@link #isAvailable()} would return {@code false}, then implementations will instantly cause a failure on the
// * request with the reason {@link com.biasedbit.hotpotato.request.HttpRequestFuture#EXECUTION_REJECTED} and return
// * {@code true}, meaning the request was consumed (and failed).
// * <p/>
// * The exception to the above rule is when the request is submitted and the connection goes down meanwhile. In this
// * case, the request <strong>will not</strong> be marked as failed and this method will return {@code false} so that
// * the caller may retry the same request in another connection.
// * <p/>
// * You should always, <strong>always</strong> test first with {@link #isAvailable()}.
// * <p/>
// * This is a non-blocking call.
// *
// * @param context Request execution context.
// *
// * @return {@code true} if the request was accepted, {@code false} otherwise. If a request is accepted, the
// * {@code HttpConnection} becomes responsible for calling {@link
// * com.biasedbit.hotpotato.request.HttpRequestFuture#setFailure(Throwable) setFailure()} or {@link
// * com.biasedbit.hotpotato.request.HttpRequestFuture#setSuccess(Object,
// * org.jboss.netty.handler.codec.http.HttpResponse) setSuccess()} on it.
// */
// boolean execute(HttpRequestContext context);
// }
| import com.biasedbit.hotpotato.client.connection.HttpConnection;
import java.util.Collection;
import java.util.LinkedList; | /*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client;
/**
* Helper class to hold both active connections and the number of connections opening to a given host.
*
* This class is not thread-safe and should only be updated by a thread at a time unless manual external synchronization
* is used.
*
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public class ConnectionPool {
// internal vars --------------------------------------------------------------------------------------------------
private boolean connectionFailures;
private int connectionsOpening; | // Path: src/main/java/com/biasedbit/hotpotato/client/connection/HttpConnection.java
// public interface HttpConnection extends ChannelHandler {
//
// /**
// * Shut down the connection, cancelling all requests executing meanwhile.
// * <p/>
// * After a connection is shut down, no more requests will be accepted.
// */
// void terminate();
//
// /**
// * Returns the unique identifier of this connection.
// *
// * @return An identifier of the connection.
// */
// String getId();
//
// /**
// * Returns the host address to which this connection is connected to.
// *
// * @return The host address to which this connection is currently connected to.
// */
// String getHost();
//
// /**
// * Returns the port to which this connection is connected to.
// *
// * @return The port of to which this connection is connected to.
// */
// int getPort();
//
// /**
// * Returns whether this connection is available to process a request. Connections that execute HTTP 1.0 requests
// * will <strong>never</strong> return true after the request has been approved for processing as the socket will
// * be closed by the server.
// *
// * @return true if this connection is connected and ready to execute a request
// */
// boolean isAvailable();
//
// /**
// * Execute a given request context in this connection. All calls to this method should first test whether this
// * connection is available or not by calling {@link #isAvailable()} first. If this method is called while
// * {@link #isAvailable()} would return {@code false}, then implementations will instantly cause a failure on the
// * request with the reason {@link com.biasedbit.hotpotato.request.HttpRequestFuture#EXECUTION_REJECTED} and return
// * {@code true}, meaning the request was consumed (and failed).
// * <p/>
// * The exception to the above rule is when the request is submitted and the connection goes down meanwhile. In this
// * case, the request <strong>will not</strong> be marked as failed and this method will return {@code false} so that
// * the caller may retry the same request in another connection.
// * <p/>
// * You should always, <strong>always</strong> test first with {@link #isAvailable()}.
// * <p/>
// * This is a non-blocking call.
// *
// * @param context Request execution context.
// *
// * @return {@code true} if the request was accepted, {@code false} otherwise. If a request is accepted, the
// * {@code HttpConnection} becomes responsible for calling {@link
// * com.biasedbit.hotpotato.request.HttpRequestFuture#setFailure(Throwable) setFailure()} or {@link
// * com.biasedbit.hotpotato.request.HttpRequestFuture#setSuccess(Object,
// * org.jboss.netty.handler.codec.http.HttpResponse) setSuccess()} on it.
// */
// boolean execute(HttpRequestContext context);
// }
// Path: src/main/java/com/biasedbit/hotpotato/client/ConnectionPool.java
import com.biasedbit.hotpotato.client.connection.HttpConnection;
import java.util.Collection;
import java.util.LinkedList;
/*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client;
/**
* Helper class to hold both active connections and the number of connections opening to a given host.
*
* This class is not thread-safe and should only be updated by a thread at a time unless manual external synchronization
* is used.
*
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public class ConnectionPool {
// internal vars --------------------------------------------------------------------------------------------------
private boolean connectionFailures;
private int connectionsOpening; | private final Collection<HttpConnection> connections; |
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/client/EventProcessorStatsProvider.java | // Path: src/main/java/com/biasedbit/hotpotato/client/event/EventType.java
// public enum EventType {
//
// /**
// * A new request execution call was issued.
// */
// EXECUTE_REQUEST,
// /**
// * A request execution was completeed (successfully or not).
// */
// REQUEST_COMPLETE,
// /**
// * A new connection to a given host was opened.
// */
// CONNECTION_OPEN,
// /**
// * An existing connection to a host was closed.
// */
// CONNECTION_CLOSED,
// /**
// * An attempt to connect to a given host failed.
// */
// CONNECTION_FAILED,
// }
| import com.biasedbit.hotpotato.client.event.EventType; | /*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client;
/**
* Provides statistics for an event processor.
* <p/>
* This is used mostly for development stages, to compare improvements of modifications.
* <p/>
* @see StatsGatheringHttpClient
*
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public interface EventProcessorStatsProvider {
/**
* @return Total execution time of the event processor, in milliseconds.
*/
long getTotalExecutionTime();
/**
* @param event Type of event to query for.
*
* @return Processing time for events of given type, in milliseconds.
*/ | // Path: src/main/java/com/biasedbit/hotpotato/client/event/EventType.java
// public enum EventType {
//
// /**
// * A new request execution call was issued.
// */
// EXECUTE_REQUEST,
// /**
// * A request execution was completeed (successfully or not).
// */
// REQUEST_COMPLETE,
// /**
// * A new connection to a given host was opened.
// */
// CONNECTION_OPEN,
// /**
// * An existing connection to a host was closed.
// */
// CONNECTION_CLOSED,
// /**
// * An attempt to connect to a given host failed.
// */
// CONNECTION_FAILED,
// }
// Path: src/main/java/com/biasedbit/hotpotato/client/EventProcessorStatsProvider.java
import com.biasedbit.hotpotato.client.event.EventType;
/*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client;
/**
* Provides statistics for an event processor.
* <p/>
* This is used mostly for development stages, to compare improvements of modifications.
* <p/>
* @see StatsGatheringHttpClient
*
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public interface EventProcessorStatsProvider {
/**
* @return Total execution time of the event processor, in milliseconds.
*/
long getTotalExecutionTime();
/**
* @param event Type of event to query for.
*
* @return Processing time for events of given type, in milliseconds.
*/ | long getEventProcessingTime(EventType event); |
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/client/host/factory/DefaultHostContextFactory.java | // Path: src/main/java/com/biasedbit/hotpotato/client/host/DefaultHostContext.java
// public class DefaultHostContext extends AbstractHostContext {
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public DefaultHostContext(String host, int port, int maxConnections) {
// super(host, port, maxConnections);
// }
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/host/HostContext.java
// public interface HostContext {
//
// public enum DrainQueueResult {
// QUEUE_EMPTY,
// DRAINED,
// NOT_DRAINED,
// OPEN_CONNECTION,
// }
//
// String getHost();
//
// int getPort();
//
// ConnectionPool getConnectionPool();
//
// Queue<HttpRequestContext> getQueue();
//
// /**
// * Used to restore requests to the head of the queue.
// *
// * An example of the usage of this method is when a pipelining HTTP connection disconnects unexpectedly while some
// * of the requests were still waiting for a response. Instead of simply failing those requests, they can be retried
// * in a different connection, provided that their execution order is maintained (i.e. they go back to the head of
// * the queue and not the tail).
// *
// * @param requests Collection of requests to add to the queue head.
// */
// void restoreRequestsToQueue(Collection<HttpRequestContext> requests);
//
// /**
// * Adds a request to the end of the queue.
// *
// * @param request Request to add.
// */
// void addToQueue(HttpRequestContext request);
//
// /**
// * Drains one (or more) elements of the queue into one (or more) connections in the connection pool.
// *
// * This is the method used to move queue elements into connections and thus advance the request dispatching process.
// *
// * @return The result of the drain operation.
// */
// DrainQueueResult drainQueue();
//
// /**
// * Retrieves the first element of the queue (head).
// *
// * @return The first element of the queue.
// */
// HttpRequestContext pollQueue();
//
// /**
// * Fails all queued requests with the given cause.
// *
// * @param cause Cause to fail all queued requests.
// */
// void failAllRequests(Throwable cause);
// }
| import com.biasedbit.hotpotato.client.host.DefaultHostContext;
import com.biasedbit.hotpotato.client.host.HostContext; | /*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.host.factory;
/**
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public class DefaultHostContextFactory implements HostContextFactory {
// HostContextFactory ---------------------------------------------------------------------------------------------
@Override | // Path: src/main/java/com/biasedbit/hotpotato/client/host/DefaultHostContext.java
// public class DefaultHostContext extends AbstractHostContext {
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public DefaultHostContext(String host, int port, int maxConnections) {
// super(host, port, maxConnections);
// }
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/host/HostContext.java
// public interface HostContext {
//
// public enum DrainQueueResult {
// QUEUE_EMPTY,
// DRAINED,
// NOT_DRAINED,
// OPEN_CONNECTION,
// }
//
// String getHost();
//
// int getPort();
//
// ConnectionPool getConnectionPool();
//
// Queue<HttpRequestContext> getQueue();
//
// /**
// * Used to restore requests to the head of the queue.
// *
// * An example of the usage of this method is when a pipelining HTTP connection disconnects unexpectedly while some
// * of the requests were still waiting for a response. Instead of simply failing those requests, they can be retried
// * in a different connection, provided that their execution order is maintained (i.e. they go back to the head of
// * the queue and not the tail).
// *
// * @param requests Collection of requests to add to the queue head.
// */
// void restoreRequestsToQueue(Collection<HttpRequestContext> requests);
//
// /**
// * Adds a request to the end of the queue.
// *
// * @param request Request to add.
// */
// void addToQueue(HttpRequestContext request);
//
// /**
// * Drains one (or more) elements of the queue into one (or more) connections in the connection pool.
// *
// * This is the method used to move queue elements into connections and thus advance the request dispatching process.
// *
// * @return The result of the drain operation.
// */
// DrainQueueResult drainQueue();
//
// /**
// * Retrieves the first element of the queue (head).
// *
// * @return The first element of the queue.
// */
// HttpRequestContext pollQueue();
//
// /**
// * Fails all queued requests with the given cause.
// *
// * @param cause Cause to fail all queued requests.
// */
// void failAllRequests(Throwable cause);
// }
// Path: src/main/java/com/biasedbit/hotpotato/client/host/factory/DefaultHostContextFactory.java
import com.biasedbit.hotpotato.client.host.DefaultHostContext;
import com.biasedbit.hotpotato.client.host.HostContext;
/*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.host.factory;
/**
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public class DefaultHostContextFactory implements HostContextFactory {
// HostContextFactory ---------------------------------------------------------------------------------------------
@Override | public HostContext createHostContext(String host, int port, int maxConnections) { |
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/client/host/factory/DefaultHostContextFactory.java | // Path: src/main/java/com/biasedbit/hotpotato/client/host/DefaultHostContext.java
// public class DefaultHostContext extends AbstractHostContext {
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public DefaultHostContext(String host, int port, int maxConnections) {
// super(host, port, maxConnections);
// }
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/host/HostContext.java
// public interface HostContext {
//
// public enum DrainQueueResult {
// QUEUE_EMPTY,
// DRAINED,
// NOT_DRAINED,
// OPEN_CONNECTION,
// }
//
// String getHost();
//
// int getPort();
//
// ConnectionPool getConnectionPool();
//
// Queue<HttpRequestContext> getQueue();
//
// /**
// * Used to restore requests to the head of the queue.
// *
// * An example of the usage of this method is when a pipelining HTTP connection disconnects unexpectedly while some
// * of the requests were still waiting for a response. Instead of simply failing those requests, they can be retried
// * in a different connection, provided that their execution order is maintained (i.e. they go back to the head of
// * the queue and not the tail).
// *
// * @param requests Collection of requests to add to the queue head.
// */
// void restoreRequestsToQueue(Collection<HttpRequestContext> requests);
//
// /**
// * Adds a request to the end of the queue.
// *
// * @param request Request to add.
// */
// void addToQueue(HttpRequestContext request);
//
// /**
// * Drains one (or more) elements of the queue into one (or more) connections in the connection pool.
// *
// * This is the method used to move queue elements into connections and thus advance the request dispatching process.
// *
// * @return The result of the drain operation.
// */
// DrainQueueResult drainQueue();
//
// /**
// * Retrieves the first element of the queue (head).
// *
// * @return The first element of the queue.
// */
// HttpRequestContext pollQueue();
//
// /**
// * Fails all queued requests with the given cause.
// *
// * @param cause Cause to fail all queued requests.
// */
// void failAllRequests(Throwable cause);
// }
| import com.biasedbit.hotpotato.client.host.DefaultHostContext;
import com.biasedbit.hotpotato.client.host.HostContext; | /*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.host.factory;
/**
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public class DefaultHostContextFactory implements HostContextFactory {
// HostContextFactory ---------------------------------------------------------------------------------------------
@Override
public HostContext createHostContext(String host, int port, int maxConnections) { | // Path: src/main/java/com/biasedbit/hotpotato/client/host/DefaultHostContext.java
// public class DefaultHostContext extends AbstractHostContext {
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public DefaultHostContext(String host, int port, int maxConnections) {
// super(host, port, maxConnections);
// }
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/host/HostContext.java
// public interface HostContext {
//
// public enum DrainQueueResult {
// QUEUE_EMPTY,
// DRAINED,
// NOT_DRAINED,
// OPEN_CONNECTION,
// }
//
// String getHost();
//
// int getPort();
//
// ConnectionPool getConnectionPool();
//
// Queue<HttpRequestContext> getQueue();
//
// /**
// * Used to restore requests to the head of the queue.
// *
// * An example of the usage of this method is when a pipelining HTTP connection disconnects unexpectedly while some
// * of the requests were still waiting for a response. Instead of simply failing those requests, they can be retried
// * in a different connection, provided that their execution order is maintained (i.e. they go back to the head of
// * the queue and not the tail).
// *
// * @param requests Collection of requests to add to the queue head.
// */
// void restoreRequestsToQueue(Collection<HttpRequestContext> requests);
//
// /**
// * Adds a request to the end of the queue.
// *
// * @param request Request to add.
// */
// void addToQueue(HttpRequestContext request);
//
// /**
// * Drains one (or more) elements of the queue into one (or more) connections in the connection pool.
// *
// * This is the method used to move queue elements into connections and thus advance the request dispatching process.
// *
// * @return The result of the drain operation.
// */
// DrainQueueResult drainQueue();
//
// /**
// * Retrieves the first element of the queue (head).
// *
// * @return The first element of the queue.
// */
// HttpRequestContext pollQueue();
//
// /**
// * Fails all queued requests with the given cause.
// *
// * @param cause Cause to fail all queued requests.
// */
// void failAllRequests(Throwable cause);
// }
// Path: src/main/java/com/biasedbit/hotpotato/client/host/factory/DefaultHostContextFactory.java
import com.biasedbit.hotpotato.client.host.DefaultHostContext;
import com.biasedbit.hotpotato.client.host.HostContext;
/*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.host.factory;
/**
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public class DefaultHostContextFactory implements HostContextFactory {
// HostContextFactory ---------------------------------------------------------------------------------------------
@Override
public HostContext createHostContext(String host, int port, int maxConnections) { | return new DefaultHostContext(host, port, maxConnections); |
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/client/host/factory/EagerDrainHostContextFactory.java | // Path: src/main/java/com/biasedbit/hotpotato/client/host/EagerDrainHostContext.java
// public class EagerDrainHostContext extends AbstractHostContext {
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public EagerDrainHostContext(String host, int port, int maxConnections) {
// super(host, port, maxConnections);
// }
//
// // DefaultHostContext ---------------------------------------------------------------------------------------------
//
// @Override
// public DrainQueueResult drainQueue() {
// // 1. Test if there's anything to drain
// if (this.queue.isEmpty()) {
// return DrainQueueResult.QUEUE_EMPTY;
// }
//
// // 2. There are contents to drain, test if there are any connections created.
// if (this.connectionPool.getConnections().isEmpty()) {
// // 2a. No connections open, test if there is still room to create a new one.
// if (this.connectionPool.getTotalConnections() < this.maxConnections) {
// return DrainQueueResult.OPEN_CONNECTION;
// } else {
// return DrainQueueResult.NOT_DRAINED;
// }
// }
//
// // 3. There is content to drain and there are connections, drain as much as possible in a single loop.
// boolean drained = false;
// for (HttpConnection connection : this.connectionPool.getConnections()) {
// // Drain the first element in queue.
// // There will always be an element in the queue, ensured by 1. or by the premature exit right below.
// while (connection.isAvailable()) {
// // Peek the next request and see if the connection is able to accept it.
// HttpRequestContext context = this.queue.peek();
// if (connection.execute(context)) {
// // Request was accepted by the connection, remove it from the queue.
// this.queue.remove();
// if (this.queue.isEmpty()) {
// // Prematurely exit in case there are no further requests to execute.
// // Returning prematurely dispenses additional check before queue.remove()
// return DrainQueueResult.DRAINED;
// }
// // Otherwise, result WILL be DRAINED, no matter if we manage do execute another request or not.
// drained = true;
// }
// // Request was not accepted by this connection, keep trying other connections.
// }
// }
// if (drained) {
// return DrainQueueResult.DRAINED;
// }
//
// // 4. There were connections open but none of them was available; if possible, request a new one.
// if (this.connectionPool.getTotalConnections() < this.maxConnections) {
// return DrainQueueResult.OPEN_CONNECTION;
// } else {
// return DrainQueueResult.NOT_DRAINED;
// }
// }
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/host/HostContext.java
// public interface HostContext {
//
// public enum DrainQueueResult {
// QUEUE_EMPTY,
// DRAINED,
// NOT_DRAINED,
// OPEN_CONNECTION,
// }
//
// String getHost();
//
// int getPort();
//
// ConnectionPool getConnectionPool();
//
// Queue<HttpRequestContext> getQueue();
//
// /**
// * Used to restore requests to the head of the queue.
// *
// * An example of the usage of this method is when a pipelining HTTP connection disconnects unexpectedly while some
// * of the requests were still waiting for a response. Instead of simply failing those requests, they can be retried
// * in a different connection, provided that their execution order is maintained (i.e. they go back to the head of
// * the queue and not the tail).
// *
// * @param requests Collection of requests to add to the queue head.
// */
// void restoreRequestsToQueue(Collection<HttpRequestContext> requests);
//
// /**
// * Adds a request to the end of the queue.
// *
// * @param request Request to add.
// */
// void addToQueue(HttpRequestContext request);
//
// /**
// * Drains one (or more) elements of the queue into one (or more) connections in the connection pool.
// *
// * This is the method used to move queue elements into connections and thus advance the request dispatching process.
// *
// * @return The result of the drain operation.
// */
// DrainQueueResult drainQueue();
//
// /**
// * Retrieves the first element of the queue (head).
// *
// * @return The first element of the queue.
// */
// HttpRequestContext pollQueue();
//
// /**
// * Fails all queued requests with the given cause.
// *
// * @param cause Cause to fail all queued requests.
// */
// void failAllRequests(Throwable cause);
// }
| import com.biasedbit.hotpotato.client.host.EagerDrainHostContext;
import com.biasedbit.hotpotato.client.host.HostContext; | /*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.host.factory;
/**
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public class EagerDrainHostContextFactory implements HostContextFactory {
// HostContextFactory ---------------------------------------------------------------------------------------------
@Override | // Path: src/main/java/com/biasedbit/hotpotato/client/host/EagerDrainHostContext.java
// public class EagerDrainHostContext extends AbstractHostContext {
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public EagerDrainHostContext(String host, int port, int maxConnections) {
// super(host, port, maxConnections);
// }
//
// // DefaultHostContext ---------------------------------------------------------------------------------------------
//
// @Override
// public DrainQueueResult drainQueue() {
// // 1. Test if there's anything to drain
// if (this.queue.isEmpty()) {
// return DrainQueueResult.QUEUE_EMPTY;
// }
//
// // 2. There are contents to drain, test if there are any connections created.
// if (this.connectionPool.getConnections().isEmpty()) {
// // 2a. No connections open, test if there is still room to create a new one.
// if (this.connectionPool.getTotalConnections() < this.maxConnections) {
// return DrainQueueResult.OPEN_CONNECTION;
// } else {
// return DrainQueueResult.NOT_DRAINED;
// }
// }
//
// // 3. There is content to drain and there are connections, drain as much as possible in a single loop.
// boolean drained = false;
// for (HttpConnection connection : this.connectionPool.getConnections()) {
// // Drain the first element in queue.
// // There will always be an element in the queue, ensured by 1. or by the premature exit right below.
// while (connection.isAvailable()) {
// // Peek the next request and see if the connection is able to accept it.
// HttpRequestContext context = this.queue.peek();
// if (connection.execute(context)) {
// // Request was accepted by the connection, remove it from the queue.
// this.queue.remove();
// if (this.queue.isEmpty()) {
// // Prematurely exit in case there are no further requests to execute.
// // Returning prematurely dispenses additional check before queue.remove()
// return DrainQueueResult.DRAINED;
// }
// // Otherwise, result WILL be DRAINED, no matter if we manage do execute another request or not.
// drained = true;
// }
// // Request was not accepted by this connection, keep trying other connections.
// }
// }
// if (drained) {
// return DrainQueueResult.DRAINED;
// }
//
// // 4. There were connections open but none of them was available; if possible, request a new one.
// if (this.connectionPool.getTotalConnections() < this.maxConnections) {
// return DrainQueueResult.OPEN_CONNECTION;
// } else {
// return DrainQueueResult.NOT_DRAINED;
// }
// }
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/host/HostContext.java
// public interface HostContext {
//
// public enum DrainQueueResult {
// QUEUE_EMPTY,
// DRAINED,
// NOT_DRAINED,
// OPEN_CONNECTION,
// }
//
// String getHost();
//
// int getPort();
//
// ConnectionPool getConnectionPool();
//
// Queue<HttpRequestContext> getQueue();
//
// /**
// * Used to restore requests to the head of the queue.
// *
// * An example of the usage of this method is when a pipelining HTTP connection disconnects unexpectedly while some
// * of the requests were still waiting for a response. Instead of simply failing those requests, they can be retried
// * in a different connection, provided that their execution order is maintained (i.e. they go back to the head of
// * the queue and not the tail).
// *
// * @param requests Collection of requests to add to the queue head.
// */
// void restoreRequestsToQueue(Collection<HttpRequestContext> requests);
//
// /**
// * Adds a request to the end of the queue.
// *
// * @param request Request to add.
// */
// void addToQueue(HttpRequestContext request);
//
// /**
// * Drains one (or more) elements of the queue into one (or more) connections in the connection pool.
// *
// * This is the method used to move queue elements into connections and thus advance the request dispatching process.
// *
// * @return The result of the drain operation.
// */
// DrainQueueResult drainQueue();
//
// /**
// * Retrieves the first element of the queue (head).
// *
// * @return The first element of the queue.
// */
// HttpRequestContext pollQueue();
//
// /**
// * Fails all queued requests with the given cause.
// *
// * @param cause Cause to fail all queued requests.
// */
// void failAllRequests(Throwable cause);
// }
// Path: src/main/java/com/biasedbit/hotpotato/client/host/factory/EagerDrainHostContextFactory.java
import com.biasedbit.hotpotato.client.host.EagerDrainHostContext;
import com.biasedbit.hotpotato.client.host.HostContext;
/*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.host.factory;
/**
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public class EagerDrainHostContextFactory implements HostContextFactory {
// HostContextFactory ---------------------------------------------------------------------------------------------
@Override | public HostContext createHostContext(String host, int port, int maxConnections) { |
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/client/host/factory/EagerDrainHostContextFactory.java | // Path: src/main/java/com/biasedbit/hotpotato/client/host/EagerDrainHostContext.java
// public class EagerDrainHostContext extends AbstractHostContext {
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public EagerDrainHostContext(String host, int port, int maxConnections) {
// super(host, port, maxConnections);
// }
//
// // DefaultHostContext ---------------------------------------------------------------------------------------------
//
// @Override
// public DrainQueueResult drainQueue() {
// // 1. Test if there's anything to drain
// if (this.queue.isEmpty()) {
// return DrainQueueResult.QUEUE_EMPTY;
// }
//
// // 2. There are contents to drain, test if there are any connections created.
// if (this.connectionPool.getConnections().isEmpty()) {
// // 2a. No connections open, test if there is still room to create a new one.
// if (this.connectionPool.getTotalConnections() < this.maxConnections) {
// return DrainQueueResult.OPEN_CONNECTION;
// } else {
// return DrainQueueResult.NOT_DRAINED;
// }
// }
//
// // 3. There is content to drain and there are connections, drain as much as possible in a single loop.
// boolean drained = false;
// for (HttpConnection connection : this.connectionPool.getConnections()) {
// // Drain the first element in queue.
// // There will always be an element in the queue, ensured by 1. or by the premature exit right below.
// while (connection.isAvailable()) {
// // Peek the next request and see if the connection is able to accept it.
// HttpRequestContext context = this.queue.peek();
// if (connection.execute(context)) {
// // Request was accepted by the connection, remove it from the queue.
// this.queue.remove();
// if (this.queue.isEmpty()) {
// // Prematurely exit in case there are no further requests to execute.
// // Returning prematurely dispenses additional check before queue.remove()
// return DrainQueueResult.DRAINED;
// }
// // Otherwise, result WILL be DRAINED, no matter if we manage do execute another request or not.
// drained = true;
// }
// // Request was not accepted by this connection, keep trying other connections.
// }
// }
// if (drained) {
// return DrainQueueResult.DRAINED;
// }
//
// // 4. There were connections open but none of them was available; if possible, request a new one.
// if (this.connectionPool.getTotalConnections() < this.maxConnections) {
// return DrainQueueResult.OPEN_CONNECTION;
// } else {
// return DrainQueueResult.NOT_DRAINED;
// }
// }
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/host/HostContext.java
// public interface HostContext {
//
// public enum DrainQueueResult {
// QUEUE_EMPTY,
// DRAINED,
// NOT_DRAINED,
// OPEN_CONNECTION,
// }
//
// String getHost();
//
// int getPort();
//
// ConnectionPool getConnectionPool();
//
// Queue<HttpRequestContext> getQueue();
//
// /**
// * Used to restore requests to the head of the queue.
// *
// * An example of the usage of this method is when a pipelining HTTP connection disconnects unexpectedly while some
// * of the requests were still waiting for a response. Instead of simply failing those requests, they can be retried
// * in a different connection, provided that their execution order is maintained (i.e. they go back to the head of
// * the queue and not the tail).
// *
// * @param requests Collection of requests to add to the queue head.
// */
// void restoreRequestsToQueue(Collection<HttpRequestContext> requests);
//
// /**
// * Adds a request to the end of the queue.
// *
// * @param request Request to add.
// */
// void addToQueue(HttpRequestContext request);
//
// /**
// * Drains one (or more) elements of the queue into one (or more) connections in the connection pool.
// *
// * This is the method used to move queue elements into connections and thus advance the request dispatching process.
// *
// * @return The result of the drain operation.
// */
// DrainQueueResult drainQueue();
//
// /**
// * Retrieves the first element of the queue (head).
// *
// * @return The first element of the queue.
// */
// HttpRequestContext pollQueue();
//
// /**
// * Fails all queued requests with the given cause.
// *
// * @param cause Cause to fail all queued requests.
// */
// void failAllRequests(Throwable cause);
// }
| import com.biasedbit.hotpotato.client.host.EagerDrainHostContext;
import com.biasedbit.hotpotato.client.host.HostContext; | /*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.host.factory;
/**
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public class EagerDrainHostContextFactory implements HostContextFactory {
// HostContextFactory ---------------------------------------------------------------------------------------------
@Override
public HostContext createHostContext(String host, int port, int maxConnections) { | // Path: src/main/java/com/biasedbit/hotpotato/client/host/EagerDrainHostContext.java
// public class EagerDrainHostContext extends AbstractHostContext {
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public EagerDrainHostContext(String host, int port, int maxConnections) {
// super(host, port, maxConnections);
// }
//
// // DefaultHostContext ---------------------------------------------------------------------------------------------
//
// @Override
// public DrainQueueResult drainQueue() {
// // 1. Test if there's anything to drain
// if (this.queue.isEmpty()) {
// return DrainQueueResult.QUEUE_EMPTY;
// }
//
// // 2. There are contents to drain, test if there are any connections created.
// if (this.connectionPool.getConnections().isEmpty()) {
// // 2a. No connections open, test if there is still room to create a new one.
// if (this.connectionPool.getTotalConnections() < this.maxConnections) {
// return DrainQueueResult.OPEN_CONNECTION;
// } else {
// return DrainQueueResult.NOT_DRAINED;
// }
// }
//
// // 3. There is content to drain and there are connections, drain as much as possible in a single loop.
// boolean drained = false;
// for (HttpConnection connection : this.connectionPool.getConnections()) {
// // Drain the first element in queue.
// // There will always be an element in the queue, ensured by 1. or by the premature exit right below.
// while (connection.isAvailable()) {
// // Peek the next request and see if the connection is able to accept it.
// HttpRequestContext context = this.queue.peek();
// if (connection.execute(context)) {
// // Request was accepted by the connection, remove it from the queue.
// this.queue.remove();
// if (this.queue.isEmpty()) {
// // Prematurely exit in case there are no further requests to execute.
// // Returning prematurely dispenses additional check before queue.remove()
// return DrainQueueResult.DRAINED;
// }
// // Otherwise, result WILL be DRAINED, no matter if we manage do execute another request or not.
// drained = true;
// }
// // Request was not accepted by this connection, keep trying other connections.
// }
// }
// if (drained) {
// return DrainQueueResult.DRAINED;
// }
//
// // 4. There were connections open but none of them was available; if possible, request a new one.
// if (this.connectionPool.getTotalConnections() < this.maxConnections) {
// return DrainQueueResult.OPEN_CONNECTION;
// } else {
// return DrainQueueResult.NOT_DRAINED;
// }
// }
// }
//
// Path: src/main/java/com/biasedbit/hotpotato/client/host/HostContext.java
// public interface HostContext {
//
// public enum DrainQueueResult {
// QUEUE_EMPTY,
// DRAINED,
// NOT_DRAINED,
// OPEN_CONNECTION,
// }
//
// String getHost();
//
// int getPort();
//
// ConnectionPool getConnectionPool();
//
// Queue<HttpRequestContext> getQueue();
//
// /**
// * Used to restore requests to the head of the queue.
// *
// * An example of the usage of this method is when a pipelining HTTP connection disconnects unexpectedly while some
// * of the requests were still waiting for a response. Instead of simply failing those requests, they can be retried
// * in a different connection, provided that their execution order is maintained (i.e. they go back to the head of
// * the queue and not the tail).
// *
// * @param requests Collection of requests to add to the queue head.
// */
// void restoreRequestsToQueue(Collection<HttpRequestContext> requests);
//
// /**
// * Adds a request to the end of the queue.
// *
// * @param request Request to add.
// */
// void addToQueue(HttpRequestContext request);
//
// /**
// * Drains one (or more) elements of the queue into one (or more) connections in the connection pool.
// *
// * This is the method used to move queue elements into connections and thus advance the request dispatching process.
// *
// * @return The result of the drain operation.
// */
// DrainQueueResult drainQueue();
//
// /**
// * Retrieves the first element of the queue (head).
// *
// * @return The first element of the queue.
// */
// HttpRequestContext pollQueue();
//
// /**
// * Fails all queued requests with the given cause.
// *
// * @param cause Cause to fail all queued requests.
// */
// void failAllRequests(Throwable cause);
// }
// Path: src/main/java/com/biasedbit/hotpotato/client/host/factory/EagerDrainHostContextFactory.java
import com.biasedbit.hotpotato.client.host.EagerDrainHostContext;
import com.biasedbit.hotpotato.client.host.HostContext;
/*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.host.factory;
/**
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public class EagerDrainHostContextFactory implements HostContextFactory {
// HostContextFactory ---------------------------------------------------------------------------------------------
@Override
public HostContext createHostContext(String host, int port, int maxConnections) { | return new EagerDrainHostContext(host, port, maxConnections); |
jasondevj/hotpotato | src/main/java/com/biasedbit/hotpotato/client/connection/HttpConnectionListener.java | // Path: src/main/java/com/biasedbit/hotpotato/client/HttpRequestContext.java
// public class HttpRequestContext<T> {
//
// // internal vars --------------------------------------------------------------------------------------------------
//
// private final String host;
// private final int port;
// private final int timeout;
// private final HttpRequest request;
// private final HttpResponseProcessor<T> processor;
// private final HttpRequestFuture<T> future;
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public HttpRequestContext(String host, int port, int timeout, HttpRequest request,
// HttpResponseProcessor<T> processor, HttpRequestFuture<T> future) {
// if (host == null) {
// throw new IllegalArgumentException("Host cannot be null");
// }
// if ((port <= 0) || (port > 65536)) {
// throw new IllegalArgumentException("Invalid port: " + port);
// }
// if (request == null) {
// throw new IllegalArgumentException("HttpRequest cannot be null");
// }
// if (processor == null) {
// throw new IllegalArgumentException("HttpResponseProcessor cannot be null");
// }
// if (future == null) {
// throw new IllegalArgumentException("HttpRequestFuture cannot be null");
// }
//
// this.timeout = timeout < 0 ? 0 : timeout;
// this.host = host;
// this.port = port;
// this.request = request;
// this.processor = processor;
// this.future = future;
// }
//
// public HttpRequestContext(String host, int timeout, HttpRequest request, HttpResponseProcessor<T> processor,
// HttpRequestFuture<T> future) {
// this(host, 80, timeout, request, processor, future);
// }
//
// // public methods -------------------------------------------------------------------------------------------------
//
// /**
// * Determines (based on request method) if a request is idempotent or not, based on recommendations of the RFC.
// *
// * Idempotent requests: GET, HEAD, PUT, DELETE, OPTIONS, TRACE
// * Non-idempotent requests: POST, PATCH, CONNECT (not sure about this last one, couldn't find any info on it...)
// *
// * @return true if request is idempotent, false otherwise.
// */
// public boolean isIdempotent() {
// return !(this.request.getMethod().equals(HttpMethod.POST) ||
// this.request.getMethod().equals(HttpMethod.PATCH) ||
// this.request.getMethod().equals(HttpMethod.CONNECT));
// }
//
// // getters & setters ----------------------------------------------------------------------------------------------
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public HttpRequest getRequest() {
// return request;
// }
//
// public HttpResponseProcessor<T> getProcessor() {
// return processor;
// }
//
// public HttpRequestFuture<T> getFuture() {
// return future;
// }
//
// // low level overrides --------------------------------------------------------------------------------------------
//
// @Override
// public String toString() {
// return new StringBuilder()
// .append(this.request.getProtocolVersion()).append(' ')
// .append(this.request.getMethod()).append(' ')
// .append(this.request.getUri()).append(" (")
// .append(this.host).append(':')
// .append(this.port).append(')').append("@").append(Integer.toHexString(this.hashCode())).toString();
// }
// }
| import com.biasedbit.hotpotato.client.HttpRequestContext;
import java.util.Collection; | /*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.connection;
/**
* {@link HttpConnection} listener.
*
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public interface HttpConnectionListener {
/**
* Connection opened event, called by the {@link HttpConnection} when a requested connection establishes.
*
* @param connection Connection that just established.
*/
void connectionOpened(HttpConnection connection);
/**
* Connection terminated event, called by the {@link HttpConnection} when an active connection disconnects.
*
* This is the event that {@link HttpConnection}s that support submission of multiple parallel requests call to
* signal disconnection, since some of the requests may still be executed in another connection (e.g. a pipelining
* connection that goes down after a couple of requests but still has some more idempotent requests queued).
*
* @param connection Connection that was disconnected.
* @param retryRequests List of pending submitted requests that should be retried in a new connection, if possible.
*/ | // Path: src/main/java/com/biasedbit/hotpotato/client/HttpRequestContext.java
// public class HttpRequestContext<T> {
//
// // internal vars --------------------------------------------------------------------------------------------------
//
// private final String host;
// private final int port;
// private final int timeout;
// private final HttpRequest request;
// private final HttpResponseProcessor<T> processor;
// private final HttpRequestFuture<T> future;
//
// // constructors ---------------------------------------------------------------------------------------------------
//
// public HttpRequestContext(String host, int port, int timeout, HttpRequest request,
// HttpResponseProcessor<T> processor, HttpRequestFuture<T> future) {
// if (host == null) {
// throw new IllegalArgumentException("Host cannot be null");
// }
// if ((port <= 0) || (port > 65536)) {
// throw new IllegalArgumentException("Invalid port: " + port);
// }
// if (request == null) {
// throw new IllegalArgumentException("HttpRequest cannot be null");
// }
// if (processor == null) {
// throw new IllegalArgumentException("HttpResponseProcessor cannot be null");
// }
// if (future == null) {
// throw new IllegalArgumentException("HttpRequestFuture cannot be null");
// }
//
// this.timeout = timeout < 0 ? 0 : timeout;
// this.host = host;
// this.port = port;
// this.request = request;
// this.processor = processor;
// this.future = future;
// }
//
// public HttpRequestContext(String host, int timeout, HttpRequest request, HttpResponseProcessor<T> processor,
// HttpRequestFuture<T> future) {
// this(host, 80, timeout, request, processor, future);
// }
//
// // public methods -------------------------------------------------------------------------------------------------
//
// /**
// * Determines (based on request method) if a request is idempotent or not, based on recommendations of the RFC.
// *
// * Idempotent requests: GET, HEAD, PUT, DELETE, OPTIONS, TRACE
// * Non-idempotent requests: POST, PATCH, CONNECT (not sure about this last one, couldn't find any info on it...)
// *
// * @return true if request is idempotent, false otherwise.
// */
// public boolean isIdempotent() {
// return !(this.request.getMethod().equals(HttpMethod.POST) ||
// this.request.getMethod().equals(HttpMethod.PATCH) ||
// this.request.getMethod().equals(HttpMethod.CONNECT));
// }
//
// // getters & setters ----------------------------------------------------------------------------------------------
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public HttpRequest getRequest() {
// return request;
// }
//
// public HttpResponseProcessor<T> getProcessor() {
// return processor;
// }
//
// public HttpRequestFuture<T> getFuture() {
// return future;
// }
//
// // low level overrides --------------------------------------------------------------------------------------------
//
// @Override
// public String toString() {
// return new StringBuilder()
// .append(this.request.getProtocolVersion()).append(' ')
// .append(this.request.getMethod()).append(' ')
// .append(this.request.getUri()).append(" (")
// .append(this.host).append(':')
// .append(this.port).append(')').append("@").append(Integer.toHexString(this.hashCode())).toString();
// }
// }
// Path: src/main/java/com/biasedbit/hotpotato/client/connection/HttpConnectionListener.java
import com.biasedbit.hotpotato.client.HttpRequestContext;
import java.util.Collection;
/*
* Copyright 2010 Bruno de Carvalho
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.biasedbit.hotpotato.client.connection;
/**
* {@link HttpConnection} listener.
*
* @author <a href="http://bruno.biasedbit.com/">Bruno de Carvalho</a>
*/
public interface HttpConnectionListener {
/**
* Connection opened event, called by the {@link HttpConnection} when a requested connection establishes.
*
* @param connection Connection that just established.
*/
void connectionOpened(HttpConnection connection);
/**
* Connection terminated event, called by the {@link HttpConnection} when an active connection disconnects.
*
* This is the event that {@link HttpConnection}s that support submission of multiple parallel requests call to
* signal disconnection, since some of the requests may still be executed in another connection (e.g. a pipelining
* connection that goes down after a couple of requests but still has some more idempotent requests queued).
*
* @param connection Connection that was disconnected.
* @param retryRequests List of pending submitted requests that should be retried in a new connection, if possible.
*/ | void connectionTerminated(HttpConnection connection, Collection<HttpRequestContext> retryRequests); |
fracpete/collective-classification-weka-package | src/main/java/weka/classifiers/collective/meta/CollectiveNeighbor.java | // Path: src/main/java/weka/classifiers/evaluation/CollectiveEvaluationUtils.java
// public class CollectiveEvaluationUtils
// extends EvaluationUtils {
//
// /**
// * Generate a bunch of predictions ready for processing, by performing a
// * evaluation on a test set after training on the given training set.
// *
// * @param classifier the Classifier to evaluate
// * @param train the training dataset
// * @param test the test dataset
// * @exception Exception if an error occurs
// */
// @Override
// public ArrayList<Prediction> getTrainTestPredictions(Classifier classifier,
// Instances train, Instances test)
// throws Exception {
//
// if (classifier instanceof CollectiveClassifier) {
// CollectiveClassifier c = (CollectiveClassifier) classifier;
// c.reset();
// c.setTestSet(test);
// }
//
// return super.getTrainTestPredictions(classifier, train, test);
// }
//
// /**
// * runs the classifier instance with the given options.
// *
// * @param classifier the classifier to run
// * @param options the commandline options
// */
// public static void runClassifier(CollectiveClassifier classifier, String[] options) {
// try {
// System.out.println(CollectiveEvaluation.evaluateModel(classifier, options));
// }
// catch (Exception e) {
// if ( ((e.getMessage() != null) && (e.getMessage().indexOf("General options") == -1))
// || (e.getMessage() == null) )
// e.printStackTrace();
// else
// System.err.println(e.getMessage());
// }
// }
//
// /**
// * Returns the revision string.
// *
// * @return the revision
// */
// @Override
// public String getRevision() {
// return RevisionUtils.extract("$Revision: 2019 $");
// }
// }
| import weka.classifiers.evaluation.CollectiveEvaluationUtils; | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* CollectiveNeighbor.java
* Copyright (C) 2005-2013 University of Waikato, Hamilton, New Zealand
*
*/
package weka.classifiers.collective.meta;
/**
<!-- globalinfo-start -->
* Dummy classifier for TwoStageCollective - only used to keep experiments working!
* <p/>
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -I <num>
* Number of iterations.
* (default 10)</pre>
*
* <pre> -R <num>
* Number of restarts.
* (default 10)</pre>
*
* <pre> -V
* Inverts the fold selection, i.e., instead of using the first
* fold for the training set it is used for test set and the
* remaining folds for training.</pre>
*
* <pre> -log
* Creates logs in the tmp directory for all kinds of internal data.
* Use only for debugging purposes!
* </pre>
*
* <pre> -eval
* The type of evaluation to use (0 = Randomwalk/Last model used for
* prediction, 1=Randomwalk/Best model used for prediction,
* 2=Hillclimbing).
* </pre>
*
* <pre> -compare
* The type of comparisong used for comparing models.
* (0=overall RMS, 1=RMS on train set, 2=RMS on test set)
* </pre>
*
* <pre> -flipper "<classname [parameters]>"
* The flipping algorithm (and optional parameters) to use for
* flipping labels.
* </pre>
*
* <pre> -folds <folds>
* The number of folds for splitting the training set into
* train and test set. The first fold is always the training
* set. With '-V' you can invert this, i.e., instead of 20/80
* for 5 folds you'll get 80/20.
* (default 5)</pre>
*
* <pre> -V
* Inverts the fold selection, i.e., instead of using the first
* fold for the training set it is used for test set and the
* remaining folds for training.</pre>
*
* <pre> -verbose
* Whether to print some more information during building the
* classifier.
* (default is off)</pre>
*
* <pre> -verbose
* Whether to print some more information during building the
* classifier.
* (default is off)</pre>
*
* <pre> -S <num>
* Random number seed.
* (default 1)</pre>
*
* <pre> -B <classifier specification>
* Full class name of classifier to include, followed
* by scheme options. May be specified multiple times.
* (default: "weka.classifiers.rules.ZeroR")</pre>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
<!-- options-end -->
*
* @author Bernhard Pfahringer (bernhard at cs dot waikato dot ac dot nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision: 2019 $
* @see TwoStageCollective
*/
public class CollectiveNeighbor
extends TwoStageCollective {
/** for serialization */
private static final long serialVersionUID = -4606667554231860447L;
/**
* Returns a string describing classifier
* @return a description suitable for
* displaying in the explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Dummy classifier for TwoStageCollective - only used to keep experiments working!";
}
/**
* Main method for testing this class.
*
* @param args the options
*/
public static void main(String[] args) { | // Path: src/main/java/weka/classifiers/evaluation/CollectiveEvaluationUtils.java
// public class CollectiveEvaluationUtils
// extends EvaluationUtils {
//
// /**
// * Generate a bunch of predictions ready for processing, by performing a
// * evaluation on a test set after training on the given training set.
// *
// * @param classifier the Classifier to evaluate
// * @param train the training dataset
// * @param test the test dataset
// * @exception Exception if an error occurs
// */
// @Override
// public ArrayList<Prediction> getTrainTestPredictions(Classifier classifier,
// Instances train, Instances test)
// throws Exception {
//
// if (classifier instanceof CollectiveClassifier) {
// CollectiveClassifier c = (CollectiveClassifier) classifier;
// c.reset();
// c.setTestSet(test);
// }
//
// return super.getTrainTestPredictions(classifier, train, test);
// }
//
// /**
// * runs the classifier instance with the given options.
// *
// * @param classifier the classifier to run
// * @param options the commandline options
// */
// public static void runClassifier(CollectiveClassifier classifier, String[] options) {
// try {
// System.out.println(CollectiveEvaluation.evaluateModel(classifier, options));
// }
// catch (Exception e) {
// if ( ((e.getMessage() != null) && (e.getMessage().indexOf("General options") == -1))
// || (e.getMessage() == null) )
// e.printStackTrace();
// else
// System.err.println(e.getMessage());
// }
// }
//
// /**
// * Returns the revision string.
// *
// * @return the revision
// */
// @Override
// public String getRevision() {
// return RevisionUtils.extract("$Revision: 2019 $");
// }
// }
// Path: src/main/java/weka/classifiers/collective/meta/CollectiveNeighbor.java
import weka.classifiers.evaluation.CollectiveEvaluationUtils;
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* CollectiveNeighbor.java
* Copyright (C) 2005-2013 University of Waikato, Hamilton, New Zealand
*
*/
package weka.classifiers.collective.meta;
/**
<!-- globalinfo-start -->
* Dummy classifier for TwoStageCollective - only used to keep experiments working!
* <p/>
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -I <num>
* Number of iterations.
* (default 10)</pre>
*
* <pre> -R <num>
* Number of restarts.
* (default 10)</pre>
*
* <pre> -V
* Inverts the fold selection, i.e., instead of using the first
* fold for the training set it is used for test set and the
* remaining folds for training.</pre>
*
* <pre> -log
* Creates logs in the tmp directory for all kinds of internal data.
* Use only for debugging purposes!
* </pre>
*
* <pre> -eval
* The type of evaluation to use (0 = Randomwalk/Last model used for
* prediction, 1=Randomwalk/Best model used for prediction,
* 2=Hillclimbing).
* </pre>
*
* <pre> -compare
* The type of comparisong used for comparing models.
* (0=overall RMS, 1=RMS on train set, 2=RMS on test set)
* </pre>
*
* <pre> -flipper "<classname [parameters]>"
* The flipping algorithm (and optional parameters) to use for
* flipping labels.
* </pre>
*
* <pre> -folds <folds>
* The number of folds for splitting the training set into
* train and test set. The first fold is always the training
* set. With '-V' you can invert this, i.e., instead of 20/80
* for 5 folds you'll get 80/20.
* (default 5)</pre>
*
* <pre> -V
* Inverts the fold selection, i.e., instead of using the first
* fold for the training set it is used for test set and the
* remaining folds for training.</pre>
*
* <pre> -verbose
* Whether to print some more information during building the
* classifier.
* (default is off)</pre>
*
* <pre> -verbose
* Whether to print some more information during building the
* classifier.
* (default is off)</pre>
*
* <pre> -S <num>
* Random number seed.
* (default 1)</pre>
*
* <pre> -B <classifier specification>
* Full class name of classifier to include, followed
* by scheme options. May be specified multiple times.
* (default: "weka.classifiers.rules.ZeroR")</pre>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
<!-- options-end -->
*
* @author Bernhard Pfahringer (bernhard at cs dot waikato dot ac dot nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision: 2019 $
* @see TwoStageCollective
*/
public class CollectiveNeighbor
extends TwoStageCollective {
/** for serialization */
private static final long serialVersionUID = -4606667554231860447L;
/**
* Returns a string describing classifier
* @return a description suitable for
* displaying in the explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Dummy classifier for TwoStageCollective - only used to keep experiments working!";
}
/**
* Main method for testing this class.
*
* @param args the options
*/
public static void main(String[] args) { | CollectiveEvaluationUtils.runClassifier(new CollectiveNeighbor(), args); |
fracpete/collective-classification-weka-package | src/test/java/weka/classifiers/collective/AbstractCollectiveClassifierTest.java | // Path: src/main/java/weka/classifiers/evaluation/CollectiveEvaluationUtils.java
// public class CollectiveEvaluationUtils
// extends EvaluationUtils {
//
// /**
// * Generate a bunch of predictions ready for processing, by performing a
// * evaluation on a test set after training on the given training set.
// *
// * @param classifier the Classifier to evaluate
// * @param train the training dataset
// * @param test the test dataset
// * @exception Exception if an error occurs
// */
// @Override
// public ArrayList<Prediction> getTrainTestPredictions(Classifier classifier,
// Instances train, Instances test)
// throws Exception {
//
// if (classifier instanceof CollectiveClassifier) {
// CollectiveClassifier c = (CollectiveClassifier) classifier;
// c.reset();
// c.setTestSet(test);
// }
//
// return super.getTrainTestPredictions(classifier, train, test);
// }
//
// /**
// * runs the classifier instance with the given options.
// *
// * @param classifier the classifier to run
// * @param options the commandline options
// */
// public static void runClassifier(CollectiveClassifier classifier, String[] options) {
// try {
// System.out.println(CollectiveEvaluation.evaluateModel(classifier, options));
// }
// catch (Exception e) {
// if ( ((e.getMessage() != null) && (e.getMessage().indexOf("General options") == -1))
// || (e.getMessage() == null) )
// e.printStackTrace();
// else
// System.err.println(e.getMessage());
// }
// }
//
// /**
// * Returns the revision string.
// *
// * @return the revision
// */
// @Override
// public String getRevision() {
// return RevisionUtils.extract("$Revision: 2019 $");
// }
// }
| import java.util.ArrayList;
import weka.classifiers.AbstractClassifierTest;
import weka.classifiers.CheckClassifier;
import weka.classifiers.Classifier;
import weka.classifiers.evaluation.CollectiveEvaluationUtils;
import weka.classifiers.evaluation.EvaluationUtils;
import weka.classifiers.evaluation.Prediction;
import weka.core.CheckGOE;
import weka.core.Instances; | /**
* Configures the CheckGOE used for testing GOE stuff.
*
* @return the fully configured CheckGOE
*/
@Override
protected CheckGOE getGOETester() {
CheckGOE result;
result = super.getGOETester();
result.setIgnoredProperties(result.getIgnoredProperties() + ",testSet");
return result;
}
/**
* Builds a model using the current classifier using the first
* half of the current data for training, and generates a bunch of
* predictions using the remaining half of the data for testing.
*
* @param data the instances to test the classifier on
* @return a <code>FastVector</code> containing the predictions.
*/
@Override
protected ArrayList<Prediction> useClassifier(Instances data) throws Exception {
Classifier dc = null;
int tot = data.numInstances();
int mid = tot / 2;
Instances train = null;
Instances test = null; | // Path: src/main/java/weka/classifiers/evaluation/CollectiveEvaluationUtils.java
// public class CollectiveEvaluationUtils
// extends EvaluationUtils {
//
// /**
// * Generate a bunch of predictions ready for processing, by performing a
// * evaluation on a test set after training on the given training set.
// *
// * @param classifier the Classifier to evaluate
// * @param train the training dataset
// * @param test the test dataset
// * @exception Exception if an error occurs
// */
// @Override
// public ArrayList<Prediction> getTrainTestPredictions(Classifier classifier,
// Instances train, Instances test)
// throws Exception {
//
// if (classifier instanceof CollectiveClassifier) {
// CollectiveClassifier c = (CollectiveClassifier) classifier;
// c.reset();
// c.setTestSet(test);
// }
//
// return super.getTrainTestPredictions(classifier, train, test);
// }
//
// /**
// * runs the classifier instance with the given options.
// *
// * @param classifier the classifier to run
// * @param options the commandline options
// */
// public static void runClassifier(CollectiveClassifier classifier, String[] options) {
// try {
// System.out.println(CollectiveEvaluation.evaluateModel(classifier, options));
// }
// catch (Exception e) {
// if ( ((e.getMessage() != null) && (e.getMessage().indexOf("General options") == -1))
// || (e.getMessage() == null) )
// e.printStackTrace();
// else
// System.err.println(e.getMessage());
// }
// }
//
// /**
// * Returns the revision string.
// *
// * @return the revision
// */
// @Override
// public String getRevision() {
// return RevisionUtils.extract("$Revision: 2019 $");
// }
// }
// Path: src/test/java/weka/classifiers/collective/AbstractCollectiveClassifierTest.java
import java.util.ArrayList;
import weka.classifiers.AbstractClassifierTest;
import weka.classifiers.CheckClassifier;
import weka.classifiers.Classifier;
import weka.classifiers.evaluation.CollectiveEvaluationUtils;
import weka.classifiers.evaluation.EvaluationUtils;
import weka.classifiers.evaluation.Prediction;
import weka.core.CheckGOE;
import weka.core.Instances;
/**
* Configures the CheckGOE used for testing GOE stuff.
*
* @return the fully configured CheckGOE
*/
@Override
protected CheckGOE getGOETester() {
CheckGOE result;
result = super.getGOETester();
result.setIgnoredProperties(result.getIgnoredProperties() + ",testSet");
return result;
}
/**
* Builds a model using the current classifier using the first
* half of the current data for training, and generates a bunch of
* predictions using the remaining half of the data for testing.
*
* @param data the instances to test the classifier on
* @return a <code>FastVector</code> containing the predictions.
*/
@Override
protected ArrayList<Prediction> useClassifier(Instances data) throws Exception {
Classifier dc = null;
int tot = data.numInstances();
int mid = tot / 2;
Instances train = null;
Instances test = null; | EvaluationUtils evaluation = new CollectiveEvaluationUtils(); |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateClass.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/UrlParamsMap.java
// public class UrlParamsMap extends HashMap<String, String> {
// public UrlParamsMap(String url) {
//
// int s = url.indexOf("?");
// if (s == -1)
// return;
// url = url.substring(s + 1);
//
// String[] params = url.split("&");
// for (String paramGroup : params) {
// String[] param = paramGroup.split("=");
// String key = param[0];
// String value;
// if (param.length > 1) {
// value = param[1];
// } else {
// value = "";
// }
// put(key, value);
// }
// }
// }
| import com.fei_ke.chiphellclient.utils.UrlParamsMap; |
package com.fei_ke.chiphellclient.bean;
/**
* 版块分类
*
* @author fei-ke
* @2014-6-14
*/
public class PlateClass extends Plate {
String title;
String url;
String fid;// 版块id
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return title;
}
public String getFid() {
if (fid == null) { | // Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/UrlParamsMap.java
// public class UrlParamsMap extends HashMap<String, String> {
// public UrlParamsMap(String url) {
//
// int s = url.indexOf("?");
// if (s == -1)
// return;
// url = url.substring(s + 1);
//
// String[] params = url.split("&");
// for (String paramGroup : params) {
// String[] param = paramGroup.split("=");
// String key = param[0];
// String value;
// if (param.length > 1) {
// value = param[1];
// } else {
// value = "";
// }
// put(key, value);
// }
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateClass.java
import com.fei_ke.chiphellclient.utils.UrlParamsMap;
package com.fei_ke.chiphellclient.bean;
/**
* 版块分类
*
* @author fei-ke
* @2014-6-14
*/
public class PlateClass extends Plate {
String title;
String url;
String fid;// 版块id
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return title;
}
public String getFid() {
if (fid == null) { | fid = new UrlParamsMap(url).get("fid"); |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateItemView.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
| import android.content.Context;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.Plate;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById; |
package com.fei_ke.chiphellclient.ui.customviews;
/**
* 版块item
*
* @author fei-ke
* @2014-6-15
*/
@EViewGroup(R.layout.layout_plate_item)
public class PlateItemView extends FrameLayout {
@ViewById(R.id.textView_title)
TextView textViewTitle;
@ViewById(R.id.textView_count)
TextView textViewCount;
public static PlateItemView getInstance(Context context) {
return PlateItemView_.build(context);
}
public PlateItemView(Context context) {
super(context);
}
void initViews() {
}
| // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateItemView.java
import android.content.Context;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.Plate;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
package com.fei_ke.chiphellclient.ui.customviews;
/**
* 版块item
*
* @author fei-ke
* @2014-6-15
*/
@EViewGroup(R.layout.layout_plate_item)
public class PlateItemView extends FrameLayout {
@ViewById(R.id.textView_title)
TextView textViewTitle;
@ViewById(R.id.textView_count)
TextView textViewCount;
public static PlateItemView getInstance(Context context) {
return PlateItemView_.build(context);
}
public PlateItemView(Context context) {
super(context);
}
void initViews() {
}
| public void bindValue(Plate plate) { |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/api/support/ApiRequest.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ChhApplication.java
// public class ChhApplication extends Application {
// private static ChhApplication instance;
// private String formHash;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// instance = this;
//
// LogMessage.setDebug(BuildConfig.DEBUG);
//
// initImageLoader();
//
// setupUpdate();
// }
//
// private void setupUpdate() {
// UmengUpdateAgent.setUpdateAutoPopup(false);
// UmengUpdateAgent.setUpdateOnlyWifi(false);
// }
//
//
// public String getFormHash() {
// return formHash;
// }
//
// public void setFormHash(String formHash) {
// this.formHash = formHash;
// }
//
// // 初始化ImageLoader
// private void initImageLoader() {
// DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true)
// .cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.logo)
// .showImageOnFail(R.drawable.logo)
// .showImageOnLoading(R.drawable.logo)
// // .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
// .build();
//
// OkHttpClient client = new OkHttpClient.Builder()
// .connectTimeout(10, TimeUnit.SECONDS)
// .readTimeout(40, TimeUnit.SECONDS)
// .cookieJar(new JavaNetCookieJar(WebViewCookieHandler.getInstance()))
// .build();
// ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
// .denyCacheImageMultipleSizesInMemory()
// .defaultDisplayImageOptions(defaultDisplayImageOptions)
// .imageDownloader(new OkHttpImageDownloader(this, client))
// .build();
// // Initialize ImageLoader with configuration.
// ImageLoader.getInstance().init(config);
//
// }
//
// static class OkHttpImageDownloader extends BaseImageDownloader {
//
//
// private OkHttpClient client;
//
//
// public OkHttpImageDownloader(Context context, OkHttpClient client) {
// super(context);
// this.client = client;
// }
//
//
// @Override
// protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
// Request request = new Request.Builder().url(imageUri).build();
// ResponseBody responseBody = client.newCall(request).execute().body();
// InputStream inputStream = responseBody.byteStream();
// int contentLength = (int) responseBody.contentLength();
// return new ContentLengthInputStream(inputStream, contentLength);
// }
// }
//
// public static ChhApplication getInstance() {
// return instance;
// }
//
// /**
// * 是否登录
// *
// * @return
// */
// public boolean isLogin() {
// return !TextUtils.isEmpty(formHash);
// }
//
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/LogMessage.java
// public class LogMessage {
//
// // 是否打印日志
// private static boolean isDebug = true;
// // 日志标签
// public static String LOG_TAG = "frame";
//
// public static void v(String tag, Object msg) {
// if (isDebug) {
// Log.v(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void i(String tag, Object msg) {
// if (isDebug) {
// Log.i(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void d(String tag, Object msg) {
// if (isDebug) {
// Log.d(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void w(String tag, Object msg) {
// if (isDebug) {
// Log.w(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void e(String tag, Object msg) {
// if (isDebug) {
// Log.e(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void print(String tag, String msg) {
// // System.out.println("tag=="+msg);
// }
//
// /**
// * 设置debug 模式
// *
// * @param isDebug true 打印日志 false:不打印
// */
//
// public static void setDebug(boolean isDebug) {
// LogMessage.isDebug = isDebug;
// }
//
// public static boolean isDebug(){
// return isDebug;
// }
//
// }
| import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Cache;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.fei_ke.chiphellclient.BuildConfig;
import com.fei_ke.chiphellclient.ChhApplication;
import com.fei_ke.chiphellclient.utils.LogMessage;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.atomic.AtomicBoolean; | return cacheEntry;
}
@Override
public Request<?> setRequestQueue(RequestQueue requestQueue) {
onStart();
return super.setRequestQueue(requestQueue);
}
@Override
protected void deliverResponse(T response) {
if (shouldCache() && isResponseFromCache.get()) {
onCache(response);
} else {
onSuccess(response);
}
}
@Override
public void cancel() {
super.cancel();
onCancel();
}
@Override
public void deliverError(VolleyError error) {
onFailure(error, error.getMessage());
}
protected void onStart() { | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ChhApplication.java
// public class ChhApplication extends Application {
// private static ChhApplication instance;
// private String formHash;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// instance = this;
//
// LogMessage.setDebug(BuildConfig.DEBUG);
//
// initImageLoader();
//
// setupUpdate();
// }
//
// private void setupUpdate() {
// UmengUpdateAgent.setUpdateAutoPopup(false);
// UmengUpdateAgent.setUpdateOnlyWifi(false);
// }
//
//
// public String getFormHash() {
// return formHash;
// }
//
// public void setFormHash(String formHash) {
// this.formHash = formHash;
// }
//
// // 初始化ImageLoader
// private void initImageLoader() {
// DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true)
// .cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.logo)
// .showImageOnFail(R.drawable.logo)
// .showImageOnLoading(R.drawable.logo)
// // .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
// .build();
//
// OkHttpClient client = new OkHttpClient.Builder()
// .connectTimeout(10, TimeUnit.SECONDS)
// .readTimeout(40, TimeUnit.SECONDS)
// .cookieJar(new JavaNetCookieJar(WebViewCookieHandler.getInstance()))
// .build();
// ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
// .denyCacheImageMultipleSizesInMemory()
// .defaultDisplayImageOptions(defaultDisplayImageOptions)
// .imageDownloader(new OkHttpImageDownloader(this, client))
// .build();
// // Initialize ImageLoader with configuration.
// ImageLoader.getInstance().init(config);
//
// }
//
// static class OkHttpImageDownloader extends BaseImageDownloader {
//
//
// private OkHttpClient client;
//
//
// public OkHttpImageDownloader(Context context, OkHttpClient client) {
// super(context);
// this.client = client;
// }
//
//
// @Override
// protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
// Request request = new Request.Builder().url(imageUri).build();
// ResponseBody responseBody = client.newCall(request).execute().body();
// InputStream inputStream = responseBody.byteStream();
// int contentLength = (int) responseBody.contentLength();
// return new ContentLengthInputStream(inputStream, contentLength);
// }
// }
//
// public static ChhApplication getInstance() {
// return instance;
// }
//
// /**
// * 是否登录
// *
// * @return
// */
// public boolean isLogin() {
// return !TextUtils.isEmpty(formHash);
// }
//
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/LogMessage.java
// public class LogMessage {
//
// // 是否打印日志
// private static boolean isDebug = true;
// // 日志标签
// public static String LOG_TAG = "frame";
//
// public static void v(String tag, Object msg) {
// if (isDebug) {
// Log.v(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void i(String tag, Object msg) {
// if (isDebug) {
// Log.i(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void d(String tag, Object msg) {
// if (isDebug) {
// Log.d(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void w(String tag, Object msg) {
// if (isDebug) {
// Log.w(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void e(String tag, Object msg) {
// if (isDebug) {
// Log.e(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void print(String tag, String msg) {
// // System.out.println("tag=="+msg);
// }
//
// /**
// * 设置debug 模式
// *
// * @param isDebug true 打印日志 false:不打印
// */
//
// public static void setDebug(boolean isDebug) {
// LogMessage.isDebug = isDebug;
// }
//
// public static boolean isDebug(){
// return isDebug;
// }
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/api/support/ApiRequest.java
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Cache;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.fei_ke.chiphellclient.BuildConfig;
import com.fei_ke.chiphellclient.ChhApplication;
import com.fei_ke.chiphellclient.utils.LogMessage;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.atomic.AtomicBoolean;
return cacheEntry;
}
@Override
public Request<?> setRequestQueue(RequestQueue requestQueue) {
onStart();
return super.setRequestQueue(requestQueue);
}
@Override
protected void deliverResponse(T response) {
if (shouldCache() && isResponseFromCache.get()) {
onCache(response);
} else {
onSuccess(response);
}
}
@Override
public void cancel() {
super.cancel();
onCancel();
}
@Override
public void deliverError(VolleyError error) {
onFailure(error, error.getMessage());
}
protected void onStart() { | if (LogMessage.isDebug()) { |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/BaseActivity.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/GlobalSetting.java
// public class GlobalSetting {
// private static final String SETTING = "setting";
// public static final String SWIPE_BACK_EDGE = "swipe_back_edge";
// public static final String FORUM_ADDRESS = "forum_address";
// public static final String DEFAULT_FORUM_ADDRESS;
//
// private static SharedPreferences mPreferences;
//
// static {
// DEFAULT_FORUM_ADDRESS = ChhApplication.getInstance().getString(R.string.default_forum_address);
// mPreferences = ChhApplication.getInstance().getSharedPreferences(SETTING, Context.MODE_PRIVATE);
// }
//
// public static int getSwipeBackEdge() {
// return mPreferences.getInt(SWIPE_BACK_EDGE, 1);
// }
//
// public static void putSwipeBackEdge(int edge) {
// putInt(SWIPE_BACK_EDGE, edge);
// }
//
// public static String getForumAddress() {
// return mPreferences.getString(FORUM_ADDRESS, DEFAULT_FORUM_ADDRESS);
// }
//
// public static void setForumAddress(String forumAddress) {
// putString(FORUM_ADDRESS, forumAddress);
// }
//
// private static void putInt(String key, int value) {
// mPreferences.edit().putInt(key, value).apply();
// }
//
// private static void putString(String key, String value) {
// mPreferences.edit().putString(key, value).apply();
// }
// }
| import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.utils.GlobalSetting;
import com.umeng.analytics.MobclickAgent;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity; |
package com.fei_ke.chiphellclient.ui.activity;
/**
* Activity基类
*
* @author fei-ke
* @2014-6-14
*/
@EActivity
public abstract class BaseActivity extends SwipeBackActivity {
protected MenuItem menuItemRefresh;
boolean mIsRefreshing = true;
private Toolbar toolbar;
/**
* 切勿调用和复写此方法
*/
@AfterViews
final protected void onPrivateAfterViews() {
onAfterViews();
}
/**
* 此方法在onCreate之后调用,勿在此方法上添加@AfterViews注解
*/
protected abstract void onAfterViews();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/GlobalSetting.java
// public class GlobalSetting {
// private static final String SETTING = "setting";
// public static final String SWIPE_BACK_EDGE = "swipe_back_edge";
// public static final String FORUM_ADDRESS = "forum_address";
// public static final String DEFAULT_FORUM_ADDRESS;
//
// private static SharedPreferences mPreferences;
//
// static {
// DEFAULT_FORUM_ADDRESS = ChhApplication.getInstance().getString(R.string.default_forum_address);
// mPreferences = ChhApplication.getInstance().getSharedPreferences(SETTING, Context.MODE_PRIVATE);
// }
//
// public static int getSwipeBackEdge() {
// return mPreferences.getInt(SWIPE_BACK_EDGE, 1);
// }
//
// public static void putSwipeBackEdge(int edge) {
// putInt(SWIPE_BACK_EDGE, edge);
// }
//
// public static String getForumAddress() {
// return mPreferences.getString(FORUM_ADDRESS, DEFAULT_FORUM_ADDRESS);
// }
//
// public static void setForumAddress(String forumAddress) {
// putString(FORUM_ADDRESS, forumAddress);
// }
//
// private static void putInt(String key, int value) {
// mPreferences.edit().putInt(key, value).apply();
// }
//
// private static void putString(String key, String value) {
// mPreferences.edit().putString(key, value).apply();
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/BaseActivity.java
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.utils.GlobalSetting;
import com.umeng.analytics.MobclickAgent;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
package com.fei_ke.chiphellclient.ui.activity;
/**
* Activity基类
*
* @author fei-ke
* @2014-6-14
*/
@EActivity
public abstract class BaseActivity extends SwipeBackActivity {
protected MenuItem menuItemRefresh;
boolean mIsRefreshing = true;
private Toolbar toolbar;
/**
* 切勿调用和复写此方法
*/
@AfterViews
final protected void onPrivateAfterViews() {
onAfterViews();
}
/**
* 此方法在onCreate之后调用,勿在此方法上添加@AfterViews注解
*/
protected abstract void onAfterViews();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | getSwipeBackLayout().setEdgeTrackingEnabled(GlobalSetting.getSwipeBackEdge()); |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/PlateListAdapter.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateGroup.java
// public class PlateGroup extends BaseBean {
// String gid;
// String title;
// List<Plate> plates;
//
// public String getGid() {
// return gid;
// }
//
// public void setGid(String gid) {
// this.gid = gid;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<Plate> getPlates() {
// return plates;
// }
//
// public void setPlates(List<Plate> plates) {
// this.plates = plates;
// }
//
// @Override
// public String toString() {
// return "PlateGroup [gid=" + gid + ", title=" + title + ", plates=" + plates + "]";
// }
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateGroupView.java
// @EViewGroup(R.layout.layout_plate_group)
// public class PlateGroupView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// public static PlateGroupView getInstance(Context context) {
// return PlateGroupView_.build(context);
// }
//
// public PlateGroupView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(PlateGroup plateGroup) {
// textViewTitle.setText(plateGroup.getTitle());
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateItemView.java
// @EViewGroup(R.layout.layout_plate_item)
// public class PlateItemView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// @ViewById(R.id.textView_count)
// TextView textViewCount;
//
// public static PlateItemView getInstance(Context context) {
// return PlateItemView_.build(context);
// }
//
// public PlateItemView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(Plate plate) {
// textViewTitle.setText(plate.getTitle());
// textViewCount.setText(plate.getXg1());
// }
// }
| import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import com.fei_ke.chiphellclient.bean.Plate;
import com.fei_ke.chiphellclient.bean.PlateGroup;
import com.fei_ke.chiphellclient.ui.customviews.PlateGroupView;
import com.fei_ke.chiphellclient.ui.customviews.PlateItemView;
import java.util.ArrayList;
import java.util.List; |
package com.fei_ke.chiphellclient.ui.adapter;
/**
* 版块列表适配器
*
* @author fei-ke
* @2014-6-14
*/
public class PlateListAdapter extends BaseExpandableListAdapter {
private List<PlateGroup> mPlateGroups;
public PlateListAdapter(List<PlateGroup> mPlateGroups) {
super();
this.mPlateGroups = mPlateGroups;
}
@Override
public int getGroupCount() {
return mPlateGroups == null ? 0 : mPlateGroups.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return mPlateGroups == null ? 0 : mPlateGroups.get(groupPosition).getPlates().size();
}
@Override
public PlateGroup getGroup(int groupPosition) {
return mPlateGroups.get(groupPosition);
}
@Override | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateGroup.java
// public class PlateGroup extends BaseBean {
// String gid;
// String title;
// List<Plate> plates;
//
// public String getGid() {
// return gid;
// }
//
// public void setGid(String gid) {
// this.gid = gid;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<Plate> getPlates() {
// return plates;
// }
//
// public void setPlates(List<Plate> plates) {
// this.plates = plates;
// }
//
// @Override
// public String toString() {
// return "PlateGroup [gid=" + gid + ", title=" + title + ", plates=" + plates + "]";
// }
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateGroupView.java
// @EViewGroup(R.layout.layout_plate_group)
// public class PlateGroupView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// public static PlateGroupView getInstance(Context context) {
// return PlateGroupView_.build(context);
// }
//
// public PlateGroupView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(PlateGroup plateGroup) {
// textViewTitle.setText(plateGroup.getTitle());
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateItemView.java
// @EViewGroup(R.layout.layout_plate_item)
// public class PlateItemView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// @ViewById(R.id.textView_count)
// TextView textViewCount;
//
// public static PlateItemView getInstance(Context context) {
// return PlateItemView_.build(context);
// }
//
// public PlateItemView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(Plate plate) {
// textViewTitle.setText(plate.getTitle());
// textViewCount.setText(plate.getXg1());
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/PlateListAdapter.java
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import com.fei_ke.chiphellclient.bean.Plate;
import com.fei_ke.chiphellclient.bean.PlateGroup;
import com.fei_ke.chiphellclient.ui.customviews.PlateGroupView;
import com.fei_ke.chiphellclient.ui.customviews.PlateItemView;
import java.util.ArrayList;
import java.util.List;
package com.fei_ke.chiphellclient.ui.adapter;
/**
* 版块列表适配器
*
* @author fei-ke
* @2014-6-14
*/
public class PlateListAdapter extends BaseExpandableListAdapter {
private List<PlateGroup> mPlateGroups;
public PlateListAdapter(List<PlateGroup> mPlateGroups) {
super();
this.mPlateGroups = mPlateGroups;
}
@Override
public int getGroupCount() {
return mPlateGroups == null ? 0 : mPlateGroups.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return mPlateGroups == null ? 0 : mPlateGroups.get(groupPosition).getPlates().size();
}
@Override
public PlateGroup getGroup(int groupPosition) {
return mPlateGroups.get(groupPosition);
}
@Override | public Plate getChild(int groupPosition, int childPosition) { |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/PlateListAdapter.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateGroup.java
// public class PlateGroup extends BaseBean {
// String gid;
// String title;
// List<Plate> plates;
//
// public String getGid() {
// return gid;
// }
//
// public void setGid(String gid) {
// this.gid = gid;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<Plate> getPlates() {
// return plates;
// }
//
// public void setPlates(List<Plate> plates) {
// this.plates = plates;
// }
//
// @Override
// public String toString() {
// return "PlateGroup [gid=" + gid + ", title=" + title + ", plates=" + plates + "]";
// }
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateGroupView.java
// @EViewGroup(R.layout.layout_plate_group)
// public class PlateGroupView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// public static PlateGroupView getInstance(Context context) {
// return PlateGroupView_.build(context);
// }
//
// public PlateGroupView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(PlateGroup plateGroup) {
// textViewTitle.setText(plateGroup.getTitle());
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateItemView.java
// @EViewGroup(R.layout.layout_plate_item)
// public class PlateItemView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// @ViewById(R.id.textView_count)
// TextView textViewCount;
//
// public static PlateItemView getInstance(Context context) {
// return PlateItemView_.build(context);
// }
//
// public PlateItemView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(Plate plate) {
// textViewTitle.setText(plate.getTitle());
// textViewCount.setText(plate.getXg1());
// }
// }
| import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import com.fei_ke.chiphellclient.bean.Plate;
import com.fei_ke.chiphellclient.bean.PlateGroup;
import com.fei_ke.chiphellclient.ui.customviews.PlateGroupView;
import com.fei_ke.chiphellclient.ui.customviews.PlateItemView;
import java.util.ArrayList;
import java.util.List; | }
@Override
public PlateGroup getGroup(int groupPosition) {
return mPlateGroups.get(groupPosition);
}
@Override
public Plate getChild(int groupPosition, int childPosition) {
return getGroup(groupPosition).getPlates().get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
PlateGroup group = getGroup(groupPosition); | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateGroup.java
// public class PlateGroup extends BaseBean {
// String gid;
// String title;
// List<Plate> plates;
//
// public String getGid() {
// return gid;
// }
//
// public void setGid(String gid) {
// this.gid = gid;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<Plate> getPlates() {
// return plates;
// }
//
// public void setPlates(List<Plate> plates) {
// this.plates = plates;
// }
//
// @Override
// public String toString() {
// return "PlateGroup [gid=" + gid + ", title=" + title + ", plates=" + plates + "]";
// }
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateGroupView.java
// @EViewGroup(R.layout.layout_plate_group)
// public class PlateGroupView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// public static PlateGroupView getInstance(Context context) {
// return PlateGroupView_.build(context);
// }
//
// public PlateGroupView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(PlateGroup plateGroup) {
// textViewTitle.setText(plateGroup.getTitle());
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateItemView.java
// @EViewGroup(R.layout.layout_plate_item)
// public class PlateItemView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// @ViewById(R.id.textView_count)
// TextView textViewCount;
//
// public static PlateItemView getInstance(Context context) {
// return PlateItemView_.build(context);
// }
//
// public PlateItemView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(Plate plate) {
// textViewTitle.setText(plate.getTitle());
// textViewCount.setText(plate.getXg1());
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/PlateListAdapter.java
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import com.fei_ke.chiphellclient.bean.Plate;
import com.fei_ke.chiphellclient.bean.PlateGroup;
import com.fei_ke.chiphellclient.ui.customviews.PlateGroupView;
import com.fei_ke.chiphellclient.ui.customviews.PlateItemView;
import java.util.ArrayList;
import java.util.List;
}
@Override
public PlateGroup getGroup(int groupPosition) {
return mPlateGroups.get(groupPosition);
}
@Override
public Plate getChild(int groupPosition, int childPosition) {
return getGroup(groupPosition).getPlates().get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
PlateGroup group = getGroup(groupPosition); | PlateGroupView plateGroupView = null; |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/PlateListAdapter.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateGroup.java
// public class PlateGroup extends BaseBean {
// String gid;
// String title;
// List<Plate> plates;
//
// public String getGid() {
// return gid;
// }
//
// public void setGid(String gid) {
// this.gid = gid;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<Plate> getPlates() {
// return plates;
// }
//
// public void setPlates(List<Plate> plates) {
// this.plates = plates;
// }
//
// @Override
// public String toString() {
// return "PlateGroup [gid=" + gid + ", title=" + title + ", plates=" + plates + "]";
// }
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateGroupView.java
// @EViewGroup(R.layout.layout_plate_group)
// public class PlateGroupView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// public static PlateGroupView getInstance(Context context) {
// return PlateGroupView_.build(context);
// }
//
// public PlateGroupView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(PlateGroup plateGroup) {
// textViewTitle.setText(plateGroup.getTitle());
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateItemView.java
// @EViewGroup(R.layout.layout_plate_item)
// public class PlateItemView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// @ViewById(R.id.textView_count)
// TextView textViewCount;
//
// public static PlateItemView getInstance(Context context) {
// return PlateItemView_.build(context);
// }
//
// public PlateItemView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(Plate plate) {
// textViewTitle.setText(plate.getTitle());
// textViewCount.setText(plate.getXg1());
// }
// }
| import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import com.fei_ke.chiphellclient.bean.Plate;
import com.fei_ke.chiphellclient.bean.PlateGroup;
import com.fei_ke.chiphellclient.ui.customviews.PlateGroupView;
import com.fei_ke.chiphellclient.ui.customviews.PlateItemView;
import java.util.ArrayList;
import java.util.List; | public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
PlateGroup group = getGroup(groupPosition);
PlateGroupView plateGroupView = null;
if (convertView == null) {
plateGroupView = PlateGroupView.getInstance(parent.getContext());
} else {
plateGroupView = (PlateGroupView) convertView;
}
plateGroupView.bindValue(group);
return plateGroupView;
}
@Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) {
Plate plate = getChild(groupPosition, childPosition); | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateGroup.java
// public class PlateGroup extends BaseBean {
// String gid;
// String title;
// List<Plate> plates;
//
// public String getGid() {
// return gid;
// }
//
// public void setGid(String gid) {
// this.gid = gid;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<Plate> getPlates() {
// return plates;
// }
//
// public void setPlates(List<Plate> plates) {
// this.plates = plates;
// }
//
// @Override
// public String toString() {
// return "PlateGroup [gid=" + gid + ", title=" + title + ", plates=" + plates + "]";
// }
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateGroupView.java
// @EViewGroup(R.layout.layout_plate_group)
// public class PlateGroupView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// public static PlateGroupView getInstance(Context context) {
// return PlateGroupView_.build(context);
// }
//
// public PlateGroupView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(PlateGroup plateGroup) {
// textViewTitle.setText(plateGroup.getTitle());
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateItemView.java
// @EViewGroup(R.layout.layout_plate_item)
// public class PlateItemView extends FrameLayout {
// @ViewById(R.id.textView_title)
// TextView textViewTitle;
//
// @ViewById(R.id.textView_count)
// TextView textViewCount;
//
// public static PlateItemView getInstance(Context context) {
// return PlateItemView_.build(context);
// }
//
// public PlateItemView(Context context) {
// super(context);
// }
//
// void initViews() {
//
// }
//
// public void bindValue(Plate plate) {
// textViewTitle.setText(plate.getTitle());
// textViewCount.setText(plate.getXg1());
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/PlateListAdapter.java
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import com.fei_ke.chiphellclient.bean.Plate;
import com.fei_ke.chiphellclient.bean.PlateGroup;
import com.fei_ke.chiphellclient.ui.customviews.PlateGroupView;
import com.fei_ke.chiphellclient.ui.customviews.PlateItemView;
import java.util.ArrayList;
import java.util.List;
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
PlateGroup group = getGroup(groupPosition);
PlateGroupView plateGroupView = null;
if (convertView == null) {
plateGroupView = PlateGroupView.getInstance(parent.getContext());
} else {
plateGroupView = (PlateGroupView) convertView;
}
plateGroupView.bindValue(group);
return plateGroupView;
}
@Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) {
Plate plate = getChild(groupPosition, childPosition); | PlateItemView plateItemView = null; |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/AlbumActivity.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/AlbumAdapter.java
// public class AlbumAdapter extends FragmentStatePagerAdapter {
// List<String> mDatas;
//
// public AlbumAdapter(FragmentManager fm) {
// super(fm);
// }
//
// @Override
// public Fragment getItem(int position) {
// return PicFargment.getInstance(mDatas.get(position));
// }
//
// @Override
// public int getCount() {
// return mDatas == null ? 0 : mDatas.size();
// }
//
// public void update(List<String> list) {
// if (mDatas == null) {
// mDatas = new ArrayList<String>();
//
// }
// mDatas.addAll(list);
//
// notifyDataSetChanged();
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/GridPicFragment.java
// @EFragment(R.layout.fragment_grid_pic)
// public class GridPicFragment extends BaseFragment {
// @ViewById(R.id.gridView)
// GridView gridView;
// private GridAdapter mAdapter;
//
// @Override
// protected void onAfterViews() {
// mAdapter = new GridAdapter();
// gridView.setAdapter(mAdapter);
//
// }
//
// public void update(List<String> pics) {
// mAdapter.update(pics);
// mAdapter.notifyDataSetChanged();
// }
//
// public void setSelection(int position) {
// gridView.setSelection(position);
// }
//
// public void setOnItemClickListener(@Nullable AdapterView.OnItemClickListener listener) {
// gridView.setOnItemClickListener(listener);
// }
//
// static class GridAdapter extends BaseAdapter {
// private static DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.default_img)
// .showImageOnFail(R.drawable.default_img)
// .showImageOnLoading(R.drawable.default_img)
// .build();
// private List<String> pics = new ArrayList<>();
// private AnimateFirstDisplayListener firstDisplayListener = new AnimateFirstDisplayListener();
//
// public void update(List<String> pics) {
// this.pics.clear();
// this.pics.addAll(pics);
// }
//
// @Override
// public int getCount() {
// return pics == null ? 0 : pics.size();
// }
//
// @Override
// public String getItem(int position) {
// return pics.get(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// ImageView imageView;
// if (convertView != null) {
// imageView = (ImageView) convertView;
// } else {
// imageView = new SquareImageView(parent.getContext());
// imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// }
// ImageLoader.getInstance().displayImage(getItem(position), imageView, imageOptions, firstDisplayListener);
// return imageView;
// }
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.ui.adapter.AlbumAdapter;
import com.fei_ke.chiphellclient.ui.fragment.GridPicFragment;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.FragmentById;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List; |
package com.fei_ke.chiphellclient.ui.activity;
/**
* 相册
*
* @author fei-ke
* @2014-6-22
*/
@EActivity(R.layout.activity_album)
public class AlbumActivity extends BaseActivity {
private static final String TAG = "AlbumActivity";
@Extra
ArrayList<String> pics;
@Extra
int index;
@ViewById(R.id.viewPager)
ViewPager mViewPager;
@ViewById(R.id.textView_total)
TextView textViewTotal;
@ViewById(R.id.textView_current)
TextView textViewCurrent;
@ViewById(R.id.layout_grid)
View layoutGrid;
@ViewById(R.id.layout_viewpager)
View layoutViewpager;
@FragmentById(R.id.gridPicFragment) | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/AlbumAdapter.java
// public class AlbumAdapter extends FragmentStatePagerAdapter {
// List<String> mDatas;
//
// public AlbumAdapter(FragmentManager fm) {
// super(fm);
// }
//
// @Override
// public Fragment getItem(int position) {
// return PicFargment.getInstance(mDatas.get(position));
// }
//
// @Override
// public int getCount() {
// return mDatas == null ? 0 : mDatas.size();
// }
//
// public void update(List<String> list) {
// if (mDatas == null) {
// mDatas = new ArrayList<String>();
//
// }
// mDatas.addAll(list);
//
// notifyDataSetChanged();
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/GridPicFragment.java
// @EFragment(R.layout.fragment_grid_pic)
// public class GridPicFragment extends BaseFragment {
// @ViewById(R.id.gridView)
// GridView gridView;
// private GridAdapter mAdapter;
//
// @Override
// protected void onAfterViews() {
// mAdapter = new GridAdapter();
// gridView.setAdapter(mAdapter);
//
// }
//
// public void update(List<String> pics) {
// mAdapter.update(pics);
// mAdapter.notifyDataSetChanged();
// }
//
// public void setSelection(int position) {
// gridView.setSelection(position);
// }
//
// public void setOnItemClickListener(@Nullable AdapterView.OnItemClickListener listener) {
// gridView.setOnItemClickListener(listener);
// }
//
// static class GridAdapter extends BaseAdapter {
// private static DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.default_img)
// .showImageOnFail(R.drawable.default_img)
// .showImageOnLoading(R.drawable.default_img)
// .build();
// private List<String> pics = new ArrayList<>();
// private AnimateFirstDisplayListener firstDisplayListener = new AnimateFirstDisplayListener();
//
// public void update(List<String> pics) {
// this.pics.clear();
// this.pics.addAll(pics);
// }
//
// @Override
// public int getCount() {
// return pics == null ? 0 : pics.size();
// }
//
// @Override
// public String getItem(int position) {
// return pics.get(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// ImageView imageView;
// if (convertView != null) {
// imageView = (ImageView) convertView;
// } else {
// imageView = new SquareImageView(parent.getContext());
// imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// }
// ImageLoader.getInstance().displayImage(getItem(position), imageView, imageOptions, firstDisplayListener);
// return imageView;
// }
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/AlbumActivity.java
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.ui.adapter.AlbumAdapter;
import com.fei_ke.chiphellclient.ui.fragment.GridPicFragment;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.FragmentById;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List;
package com.fei_ke.chiphellclient.ui.activity;
/**
* 相册
*
* @author fei-ke
* @2014-6-22
*/
@EActivity(R.layout.activity_album)
public class AlbumActivity extends BaseActivity {
private static final String TAG = "AlbumActivity";
@Extra
ArrayList<String> pics;
@Extra
int index;
@ViewById(R.id.viewPager)
ViewPager mViewPager;
@ViewById(R.id.textView_total)
TextView textViewTotal;
@ViewById(R.id.textView_current)
TextView textViewCurrent;
@ViewById(R.id.layout_grid)
View layoutGrid;
@ViewById(R.id.layout_viewpager)
View layoutViewpager;
@FragmentById(R.id.gridPicFragment) | GridPicFragment gridPicFragment; |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/AlbumActivity.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/AlbumAdapter.java
// public class AlbumAdapter extends FragmentStatePagerAdapter {
// List<String> mDatas;
//
// public AlbumAdapter(FragmentManager fm) {
// super(fm);
// }
//
// @Override
// public Fragment getItem(int position) {
// return PicFargment.getInstance(mDatas.get(position));
// }
//
// @Override
// public int getCount() {
// return mDatas == null ? 0 : mDatas.size();
// }
//
// public void update(List<String> list) {
// if (mDatas == null) {
// mDatas = new ArrayList<String>();
//
// }
// mDatas.addAll(list);
//
// notifyDataSetChanged();
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/GridPicFragment.java
// @EFragment(R.layout.fragment_grid_pic)
// public class GridPicFragment extends BaseFragment {
// @ViewById(R.id.gridView)
// GridView gridView;
// private GridAdapter mAdapter;
//
// @Override
// protected void onAfterViews() {
// mAdapter = new GridAdapter();
// gridView.setAdapter(mAdapter);
//
// }
//
// public void update(List<String> pics) {
// mAdapter.update(pics);
// mAdapter.notifyDataSetChanged();
// }
//
// public void setSelection(int position) {
// gridView.setSelection(position);
// }
//
// public void setOnItemClickListener(@Nullable AdapterView.OnItemClickListener listener) {
// gridView.setOnItemClickListener(listener);
// }
//
// static class GridAdapter extends BaseAdapter {
// private static DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.default_img)
// .showImageOnFail(R.drawable.default_img)
// .showImageOnLoading(R.drawable.default_img)
// .build();
// private List<String> pics = new ArrayList<>();
// private AnimateFirstDisplayListener firstDisplayListener = new AnimateFirstDisplayListener();
//
// public void update(List<String> pics) {
// this.pics.clear();
// this.pics.addAll(pics);
// }
//
// @Override
// public int getCount() {
// return pics == null ? 0 : pics.size();
// }
//
// @Override
// public String getItem(int position) {
// return pics.get(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// ImageView imageView;
// if (convertView != null) {
// imageView = (ImageView) convertView;
// } else {
// imageView = new SquareImageView(parent.getContext());
// imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// }
// ImageLoader.getInstance().displayImage(getItem(position), imageView, imageOptions, firstDisplayListener);
// return imageView;
// }
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.ui.adapter.AlbumAdapter;
import com.fei_ke.chiphellclient.ui.fragment.GridPicFragment;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.FragmentById;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List; |
package com.fei_ke.chiphellclient.ui.activity;
/**
* 相册
*
* @author fei-ke
* @2014-6-22
*/
@EActivity(R.layout.activity_album)
public class AlbumActivity extends BaseActivity {
private static final String TAG = "AlbumActivity";
@Extra
ArrayList<String> pics;
@Extra
int index;
@ViewById(R.id.viewPager)
ViewPager mViewPager;
@ViewById(R.id.textView_total)
TextView textViewTotal;
@ViewById(R.id.textView_current)
TextView textViewCurrent;
@ViewById(R.id.layout_grid)
View layoutGrid;
@ViewById(R.id.layout_viewpager)
View layoutViewpager;
@FragmentById(R.id.gridPicFragment)
GridPicFragment gridPicFragment;
| // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/AlbumAdapter.java
// public class AlbumAdapter extends FragmentStatePagerAdapter {
// List<String> mDatas;
//
// public AlbumAdapter(FragmentManager fm) {
// super(fm);
// }
//
// @Override
// public Fragment getItem(int position) {
// return PicFargment.getInstance(mDatas.get(position));
// }
//
// @Override
// public int getCount() {
// return mDatas == null ? 0 : mDatas.size();
// }
//
// public void update(List<String> list) {
// if (mDatas == null) {
// mDatas = new ArrayList<String>();
//
// }
// mDatas.addAll(list);
//
// notifyDataSetChanged();
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/GridPicFragment.java
// @EFragment(R.layout.fragment_grid_pic)
// public class GridPicFragment extends BaseFragment {
// @ViewById(R.id.gridView)
// GridView gridView;
// private GridAdapter mAdapter;
//
// @Override
// protected void onAfterViews() {
// mAdapter = new GridAdapter();
// gridView.setAdapter(mAdapter);
//
// }
//
// public void update(List<String> pics) {
// mAdapter.update(pics);
// mAdapter.notifyDataSetChanged();
// }
//
// public void setSelection(int position) {
// gridView.setSelection(position);
// }
//
// public void setOnItemClickListener(@Nullable AdapterView.OnItemClickListener listener) {
// gridView.setOnItemClickListener(listener);
// }
//
// static class GridAdapter extends BaseAdapter {
// private static DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.default_img)
// .showImageOnFail(R.drawable.default_img)
// .showImageOnLoading(R.drawable.default_img)
// .build();
// private List<String> pics = new ArrayList<>();
// private AnimateFirstDisplayListener firstDisplayListener = new AnimateFirstDisplayListener();
//
// public void update(List<String> pics) {
// this.pics.clear();
// this.pics.addAll(pics);
// }
//
// @Override
// public int getCount() {
// return pics == null ? 0 : pics.size();
// }
//
// @Override
// public String getItem(int position) {
// return pics.get(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// ImageView imageView;
// if (convertView != null) {
// imageView = (ImageView) convertView;
// } else {
// imageView = new SquareImageView(parent.getContext());
// imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// }
// ImageLoader.getInstance().displayImage(getItem(position), imageView, imageOptions, firstDisplayListener);
// return imageView;
// }
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/AlbumActivity.java
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.ui.adapter.AlbumAdapter;
import com.fei_ke.chiphellclient.ui.fragment.GridPicFragment;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.FragmentById;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List;
package com.fei_ke.chiphellclient.ui.activity;
/**
* 相册
*
* @author fei-ke
* @2014-6-22
*/
@EActivity(R.layout.activity_album)
public class AlbumActivity extends BaseActivity {
private static final String TAG = "AlbumActivity";
@Extra
ArrayList<String> pics;
@Extra
int index;
@ViewById(R.id.viewPager)
ViewPager mViewPager;
@ViewById(R.id.textView_total)
TextView textViewTotal;
@ViewById(R.id.textView_current)
TextView textViewCurrent;
@ViewById(R.id.layout_grid)
View layoutGrid;
@ViewById(R.id.layout_viewpager)
View layoutViewpager;
@FragmentById(R.id.gridPicFragment)
GridPicFragment gridPicFragment;
| AlbumAdapter mViewPagerAdapter; |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/UserView.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/User.java
// public class User {
// private String avatarUrl = "";
// private String name = "登录";
// private String info = "";
// private String formHash;
//
// public String getAvatarUrl() {
// return avatarUrl;
// }
//
// public void setAvatarUrl(String avatarUrl) {
// this.avatarUrl = avatarUrl;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getFormHash() {
// return formHash;
// }
//
// public void setFormHash(String formHash) {
// this.formHash = formHash;
// }
//
// @Override
// public String toString() {
// return "User [avatarUrl=" + avatarUrl + ", name=" + name + ", info=" + info + "]";
// }
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/Constants.java
// public class Constants {
// /**
// * 论坛地址,注意结尾的斜杠
// */
// public static String BASE_URL = GlobalSetting.getForumAddress();
// //显示头像
// public static DisplayImageOptions avatarDisplayOption = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisc(true)
// .showImageForEmptyUri(R.drawable.noavatar)
// .showImageOnFail(R.drawable.noavatar)
// .showImageOnLoading(R.drawable.noavatar)
// .build();
// }
| import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.Html;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.User;
import com.fei_ke.chiphellclient.constant.Constants;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById; | @ViewById(R.id.button_favorite)
protected TextView buttonFavorite;
@ViewById(R.id.button_my_post)
protected TextView buttonMyPost;
@ViewById(R.id.main_frame)
protected View mainFrame;
public static UserView newInstance(Context context) {
return UserView_.build(context);
}
public UserView(Context context) {
super(context);
}
public UserView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public UserView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public UserView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
| // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/User.java
// public class User {
// private String avatarUrl = "";
// private String name = "登录";
// private String info = "";
// private String formHash;
//
// public String getAvatarUrl() {
// return avatarUrl;
// }
//
// public void setAvatarUrl(String avatarUrl) {
// this.avatarUrl = avatarUrl;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getFormHash() {
// return formHash;
// }
//
// public void setFormHash(String formHash) {
// this.formHash = formHash;
// }
//
// @Override
// public String toString() {
// return "User [avatarUrl=" + avatarUrl + ", name=" + name + ", info=" + info + "]";
// }
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/Constants.java
// public class Constants {
// /**
// * 论坛地址,注意结尾的斜杠
// */
// public static String BASE_URL = GlobalSetting.getForumAddress();
// //显示头像
// public static DisplayImageOptions avatarDisplayOption = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisc(true)
// .showImageForEmptyUri(R.drawable.noavatar)
// .showImageOnFail(R.drawable.noavatar)
// .showImageOnLoading(R.drawable.noavatar)
// .build();
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/UserView.java
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.Html;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.User;
import com.fei_ke.chiphellclient.constant.Constants;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
@ViewById(R.id.button_favorite)
protected TextView buttonFavorite;
@ViewById(R.id.button_my_post)
protected TextView buttonMyPost;
@ViewById(R.id.main_frame)
protected View mainFrame;
public static UserView newInstance(Context context) {
return UserView_.build(context);
}
public UserView(Context context) {
super(context);
}
public UserView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public UserView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public UserView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
| public void bindValue(User user) { |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/UserView.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/User.java
// public class User {
// private String avatarUrl = "";
// private String name = "登录";
// private String info = "";
// private String formHash;
//
// public String getAvatarUrl() {
// return avatarUrl;
// }
//
// public void setAvatarUrl(String avatarUrl) {
// this.avatarUrl = avatarUrl;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getFormHash() {
// return formHash;
// }
//
// public void setFormHash(String formHash) {
// this.formHash = formHash;
// }
//
// @Override
// public String toString() {
// return "User [avatarUrl=" + avatarUrl + ", name=" + name + ", info=" + info + "]";
// }
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/Constants.java
// public class Constants {
// /**
// * 论坛地址,注意结尾的斜杠
// */
// public static String BASE_URL = GlobalSetting.getForumAddress();
// //显示头像
// public static DisplayImageOptions avatarDisplayOption = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisc(true)
// .showImageForEmptyUri(R.drawable.noavatar)
// .showImageOnFail(R.drawable.noavatar)
// .showImageOnLoading(R.drawable.noavatar)
// .build();
// }
| import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.Html;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.User;
import com.fei_ke.chiphellclient.constant.Constants;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById; | protected TextView buttonFavorite;
@ViewById(R.id.button_my_post)
protected TextView buttonMyPost;
@ViewById(R.id.main_frame)
protected View mainFrame;
public static UserView newInstance(Context context) {
return UserView_.build(context);
}
public UserView(Context context) {
super(context);
}
public UserView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public UserView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public UserView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void bindValue(User user) { | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/User.java
// public class User {
// private String avatarUrl = "";
// private String name = "登录";
// private String info = "";
// private String formHash;
//
// public String getAvatarUrl() {
// return avatarUrl;
// }
//
// public void setAvatarUrl(String avatarUrl) {
// this.avatarUrl = avatarUrl;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getFormHash() {
// return formHash;
// }
//
// public void setFormHash(String formHash) {
// this.formHash = formHash;
// }
//
// @Override
// public String toString() {
// return "User [avatarUrl=" + avatarUrl + ", name=" + name + ", info=" + info + "]";
// }
//
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/Constants.java
// public class Constants {
// /**
// * 论坛地址,注意结尾的斜杠
// */
// public static String BASE_URL = GlobalSetting.getForumAddress();
// //显示头像
// public static DisplayImageOptions avatarDisplayOption = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisc(true)
// .showImageForEmptyUri(R.drawable.noavatar)
// .showImageOnFail(R.drawable.noavatar)
// .showImageOnLoading(R.drawable.noavatar)
// .build();
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/UserView.java
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.Html;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.User;
import com.fei_ke.chiphellclient.constant.Constants;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
protected TextView buttonFavorite;
@ViewById(R.id.button_my_post)
protected TextView buttonMyPost;
@ViewById(R.id.main_frame)
protected View mainFrame;
public static UserView newInstance(Context context) {
return UserView_.build(context);
}
public UserView(Context context) {
super(context);
}
public UserView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public UserView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public UserView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void bindValue(User user) { | ImageLoader.getInstance().displayImage(user.getAvatarUrl(), imageViewAvatar, Constants.avatarDisplayOption, |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/LoginActivity.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/Constants.java
// public class Constants {
// /**
// * 论坛地址,注意结尾的斜杠
// */
// public static String BASE_URL = GlobalSetting.getForumAddress();
// //显示头像
// public static DisplayImageOptions avatarDisplayOption = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisc(true)
// .showImageForEmptyUri(R.drawable.noavatar)
// .showImageOnFail(R.drawable.noavatar)
// .showImageOnLoading(R.drawable.noavatar)
// .build();
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/LogMessage.java
// public class LogMessage {
//
// // 是否打印日志
// private static boolean isDebug = true;
// // 日志标签
// public static String LOG_TAG = "frame";
//
// public static void v(String tag, Object msg) {
// if (isDebug) {
// Log.v(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void i(String tag, Object msg) {
// if (isDebug) {
// Log.i(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void d(String tag, Object msg) {
// if (isDebug) {
// Log.d(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void w(String tag, Object msg) {
// if (isDebug) {
// Log.w(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void e(String tag, Object msg) {
// if (isDebug) {
// Log.e(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void print(String tag, String msg) {
// // System.out.println("tag=="+msg);
// }
//
// /**
// * 设置debug 模式
// *
// * @param isDebug true 打印日志 false:不打印
// */
//
// public static void setDebug(boolean isDebug) {
// LogMessage.isDebug = isDebug;
// }
//
// public static boolean isDebug(){
// return isDebug;
// }
//
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.constant.Constants;
import com.fei_ke.chiphellclient.utils.LogMessage;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById; | package com.fei_ke.chiphellclient.ui.activity;
/**
* 登录页面
*
* @author fei-ke
* @2014-6-15
*/
@EActivity(R.layout.activity_login)
public class LoginActivity extends BaseActivity {
@ViewById(R.id.webView)
WebView mWebView;
@ViewById
SwipeRefreshLayout refreshLayout;
public static Intent getStartIntent(Context context) {
return LoginActivity_.intent(context).get();
}
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onAfterViews() {
setTitle("登录");
mWebView.getSettings().setJavaScriptEnabled(true); | // Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/Constants.java
// public class Constants {
// /**
// * 论坛地址,注意结尾的斜杠
// */
// public static String BASE_URL = GlobalSetting.getForumAddress();
// //显示头像
// public static DisplayImageOptions avatarDisplayOption = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisc(true)
// .showImageForEmptyUri(R.drawable.noavatar)
// .showImageOnFail(R.drawable.noavatar)
// .showImageOnLoading(R.drawable.noavatar)
// .build();
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/LogMessage.java
// public class LogMessage {
//
// // 是否打印日志
// private static boolean isDebug = true;
// // 日志标签
// public static String LOG_TAG = "frame";
//
// public static void v(String tag, Object msg) {
// if (isDebug) {
// Log.v(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void i(String tag, Object msg) {
// if (isDebug) {
// Log.i(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void d(String tag, Object msg) {
// if (isDebug) {
// Log.d(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void w(String tag, Object msg) {
// if (isDebug) {
// Log.w(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void e(String tag, Object msg) {
// if (isDebug) {
// Log.e(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void print(String tag, String msg) {
// // System.out.println("tag=="+msg);
// }
//
// /**
// * 设置debug 模式
// *
// * @param isDebug true 打印日志 false:不打印
// */
//
// public static void setDebug(boolean isDebug) {
// LogMessage.isDebug = isDebug;
// }
//
// public static boolean isDebug(){
// return isDebug;
// }
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/LoginActivity.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.constant.Constants;
import com.fei_ke.chiphellclient.utils.LogMessage;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
package com.fei_ke.chiphellclient.ui.activity;
/**
* 登录页面
*
* @author fei-ke
* @2014-6-15
*/
@EActivity(R.layout.activity_login)
public class LoginActivity extends BaseActivity {
@ViewById(R.id.webView)
WebView mWebView;
@ViewById
SwipeRefreshLayout refreshLayout;
public static Intent getStartIntent(Context context) {
return LoginActivity_.intent(context).get();
}
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onAfterViews() {
setTitle("登录");
mWebView.getSettings().setJavaScriptEnabled(true); | final String loginUrl = Constants.BASE_URL + "member.php?mod=logging&action=login&mobile=2"; |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/LoginActivity.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/Constants.java
// public class Constants {
// /**
// * 论坛地址,注意结尾的斜杠
// */
// public static String BASE_URL = GlobalSetting.getForumAddress();
// //显示头像
// public static DisplayImageOptions avatarDisplayOption = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisc(true)
// .showImageForEmptyUri(R.drawable.noavatar)
// .showImageOnFail(R.drawable.noavatar)
// .showImageOnLoading(R.drawable.noavatar)
// .build();
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/LogMessage.java
// public class LogMessage {
//
// // 是否打印日志
// private static boolean isDebug = true;
// // 日志标签
// public static String LOG_TAG = "frame";
//
// public static void v(String tag, Object msg) {
// if (isDebug) {
// Log.v(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void i(String tag, Object msg) {
// if (isDebug) {
// Log.i(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void d(String tag, Object msg) {
// if (isDebug) {
// Log.d(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void w(String tag, Object msg) {
// if (isDebug) {
// Log.w(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void e(String tag, Object msg) {
// if (isDebug) {
// Log.e(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void print(String tag, String msg) {
// // System.out.println("tag=="+msg);
// }
//
// /**
// * 设置debug 模式
// *
// * @param isDebug true 打印日志 false:不打印
// */
//
// public static void setDebug(boolean isDebug) {
// LogMessage.isDebug = isDebug;
// }
//
// public static boolean isDebug(){
// return isDebug;
// }
//
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.constant.Constants;
import com.fei_ke.chiphellclient.utils.LogMessage;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById; | package com.fei_ke.chiphellclient.ui.activity;
/**
* 登录页面
*
* @author fei-ke
* @2014-6-15
*/
@EActivity(R.layout.activity_login)
public class LoginActivity extends BaseActivity {
@ViewById(R.id.webView)
WebView mWebView;
@ViewById
SwipeRefreshLayout refreshLayout;
public static Intent getStartIntent(Context context) {
return LoginActivity_.intent(context).get();
}
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onAfterViews() {
setTitle("登录");
mWebView.getSettings().setJavaScriptEnabled(true);
final String loginUrl = Constants.BASE_URL + "member.php?mod=logging&action=login&mobile=2";
refreshLayout.setColorSchemeColors(getResources().getIntArray(R.array.gplus_colors));
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mWebView.reload();
}
});
mWebView.loadUrl(loginUrl);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) { | // Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/Constants.java
// public class Constants {
// /**
// * 论坛地址,注意结尾的斜杠
// */
// public static String BASE_URL = GlobalSetting.getForumAddress();
// //显示头像
// public static DisplayImageOptions avatarDisplayOption = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisc(true)
// .showImageForEmptyUri(R.drawable.noavatar)
// .showImageOnFail(R.drawable.noavatar)
// .showImageOnLoading(R.drawable.noavatar)
// .build();
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/LogMessage.java
// public class LogMessage {
//
// // 是否打印日志
// private static boolean isDebug = true;
// // 日志标签
// public static String LOG_TAG = "frame";
//
// public static void v(String tag, Object msg) {
// if (isDebug) {
// Log.v(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void i(String tag, Object msg) {
// if (isDebug) {
// Log.i(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void d(String tag, Object msg) {
// if (isDebug) {
// Log.d(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void w(String tag, Object msg) {
// if (isDebug) {
// Log.w(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void e(String tag, Object msg) {
// if (isDebug) {
// Log.e(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void print(String tag, String msg) {
// // System.out.println("tag=="+msg);
// }
//
// /**
// * 设置debug 模式
// *
// * @param isDebug true 打印日志 false:不打印
// */
//
// public static void setDebug(boolean isDebug) {
// LogMessage.isDebug = isDebug;
// }
//
// public static boolean isDebug(){
// return isDebug;
// }
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/LoginActivity.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.constant.Constants;
import com.fei_ke.chiphellclient.utils.LogMessage;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
package com.fei_ke.chiphellclient.ui.activity;
/**
* 登录页面
*
* @author fei-ke
* @2014-6-15
*/
@EActivity(R.layout.activity_login)
public class LoginActivity extends BaseActivity {
@ViewById(R.id.webView)
WebView mWebView;
@ViewById
SwipeRefreshLayout refreshLayout;
public static Intent getStartIntent(Context context) {
return LoginActivity_.intent(context).get();
}
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onAfterViews() {
setTitle("登录");
mWebView.getSettings().setJavaScriptEnabled(true);
final String loginUrl = Constants.BASE_URL + "member.php?mod=logging&action=login&mobile=2";
refreshLayout.setColorSchemeColors(getResources().getIntArray(R.array.gplus_colors));
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mWebView.reload();
}
});
mWebView.loadUrl(loginUrl);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) { | LogMessage.i("LoginWebView", url); |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/utils/GlobalSetting.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ChhApplication.java
// public class ChhApplication extends Application {
// private static ChhApplication instance;
// private String formHash;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// instance = this;
//
// LogMessage.setDebug(BuildConfig.DEBUG);
//
// initImageLoader();
//
// setupUpdate();
// }
//
// private void setupUpdate() {
// UmengUpdateAgent.setUpdateAutoPopup(false);
// UmengUpdateAgent.setUpdateOnlyWifi(false);
// }
//
//
// public String getFormHash() {
// return formHash;
// }
//
// public void setFormHash(String formHash) {
// this.formHash = formHash;
// }
//
// // 初始化ImageLoader
// private void initImageLoader() {
// DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true)
// .cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.logo)
// .showImageOnFail(R.drawable.logo)
// .showImageOnLoading(R.drawable.logo)
// // .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
// .build();
//
// OkHttpClient client = new OkHttpClient.Builder()
// .connectTimeout(10, TimeUnit.SECONDS)
// .readTimeout(40, TimeUnit.SECONDS)
// .cookieJar(new JavaNetCookieJar(WebViewCookieHandler.getInstance()))
// .build();
// ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
// .denyCacheImageMultipleSizesInMemory()
// .defaultDisplayImageOptions(defaultDisplayImageOptions)
// .imageDownloader(new OkHttpImageDownloader(this, client))
// .build();
// // Initialize ImageLoader with configuration.
// ImageLoader.getInstance().init(config);
//
// }
//
// static class OkHttpImageDownloader extends BaseImageDownloader {
//
//
// private OkHttpClient client;
//
//
// public OkHttpImageDownloader(Context context, OkHttpClient client) {
// super(context);
// this.client = client;
// }
//
//
// @Override
// protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
// Request request = new Request.Builder().url(imageUri).build();
// ResponseBody responseBody = client.newCall(request).execute().body();
// InputStream inputStream = responseBody.byteStream();
// int contentLength = (int) responseBody.contentLength();
// return new ContentLengthInputStream(inputStream, contentLength);
// }
// }
//
// public static ChhApplication getInstance() {
// return instance;
// }
//
// /**
// * 是否登录
// *
// * @return
// */
// public boolean isLogin() {
// return !TextUtils.isEmpty(formHash);
// }
//
//
// }
| import android.content.Context;
import android.content.SharedPreferences;
import com.fei_ke.chiphellclient.ChhApplication;
import com.fei_ke.chiphellclient.R; |
package com.fei_ke.chiphellclient.utils;
/**
* 全局设置
*
* @author fei-ke
* @2014年6月28日
*/
public class GlobalSetting {
private static final String SETTING = "setting";
public static final String SWIPE_BACK_EDGE = "swipe_back_edge";
public static final String FORUM_ADDRESS = "forum_address";
public static final String DEFAULT_FORUM_ADDRESS;
private static SharedPreferences mPreferences;
static { | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ChhApplication.java
// public class ChhApplication extends Application {
// private static ChhApplication instance;
// private String formHash;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// instance = this;
//
// LogMessage.setDebug(BuildConfig.DEBUG);
//
// initImageLoader();
//
// setupUpdate();
// }
//
// private void setupUpdate() {
// UmengUpdateAgent.setUpdateAutoPopup(false);
// UmengUpdateAgent.setUpdateOnlyWifi(false);
// }
//
//
// public String getFormHash() {
// return formHash;
// }
//
// public void setFormHash(String formHash) {
// this.formHash = formHash;
// }
//
// // 初始化ImageLoader
// private void initImageLoader() {
// DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true)
// .cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.logo)
// .showImageOnFail(R.drawable.logo)
// .showImageOnLoading(R.drawable.logo)
// // .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
// .build();
//
// OkHttpClient client = new OkHttpClient.Builder()
// .connectTimeout(10, TimeUnit.SECONDS)
// .readTimeout(40, TimeUnit.SECONDS)
// .cookieJar(new JavaNetCookieJar(WebViewCookieHandler.getInstance()))
// .build();
// ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
// .denyCacheImageMultipleSizesInMemory()
// .defaultDisplayImageOptions(defaultDisplayImageOptions)
// .imageDownloader(new OkHttpImageDownloader(this, client))
// .build();
// // Initialize ImageLoader with configuration.
// ImageLoader.getInstance().init(config);
//
// }
//
// static class OkHttpImageDownloader extends BaseImageDownloader {
//
//
// private OkHttpClient client;
//
//
// public OkHttpImageDownloader(Context context, OkHttpClient client) {
// super(context);
// this.client = client;
// }
//
//
// @Override
// protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
// Request request = new Request.Builder().url(imageUri).build();
// ResponseBody responseBody = client.newCall(request).execute().body();
// InputStream inputStream = responseBody.byteStream();
// int contentLength = (int) responseBody.contentLength();
// return new ContentLengthInputStream(inputStream, contentLength);
// }
// }
//
// public static ChhApplication getInstance() {
// return instance;
// }
//
// /**
// * 是否登录
// *
// * @return
// */
// public boolean isLogin() {
// return !TextUtils.isEmpty(formHash);
// }
//
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/GlobalSetting.java
import android.content.Context;
import android.content.SharedPreferences;
import com.fei_ke.chiphellclient.ChhApplication;
import com.fei_ke.chiphellclient.R;
package com.fei_ke.chiphellclient.utils;
/**
* 全局设置
*
* @author fei-ke
* @2014年6月28日
*/
public class GlobalSetting {
private static final String SETTING = "setting";
public static final String SWIPE_BACK_EDGE = "swipe_back_edge";
public static final String FORUM_ADDRESS = "forum_address";
public static final String DEFAULT_FORUM_ADDRESS;
private static SharedPreferences mPreferences;
static { | DEFAULT_FORUM_ADDRESS = ChhApplication.getInstance().getString(R.string.default_forum_address); |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateGroupView.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateGroup.java
// public class PlateGroup extends BaseBean {
// String gid;
// String title;
// List<Plate> plates;
//
// public String getGid() {
// return gid;
// }
//
// public void setGid(String gid) {
// this.gid = gid;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<Plate> getPlates() {
// return plates;
// }
//
// public void setPlates(List<Plate> plates) {
// this.plates = plates;
// }
//
// @Override
// public String toString() {
// return "PlateGroup [gid=" + gid + ", title=" + title + ", plates=" + plates + "]";
// }
//
// }
| import android.content.Context;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.PlateGroup;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById; |
package com.fei_ke.chiphellclient.ui.customviews;
/**
* 版块列表分组
*
* @author fei-ke
* @2014-6-15
*/
@EViewGroup(R.layout.layout_plate_group)
public class PlateGroupView extends FrameLayout {
@ViewById(R.id.textView_title)
TextView textViewTitle;
public static PlateGroupView getInstance(Context context) {
return PlateGroupView_.build(context);
}
public PlateGroupView(Context context) {
super(context);
}
void initViews() {
}
| // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateGroup.java
// public class PlateGroup extends BaseBean {
// String gid;
// String title;
// List<Plate> plates;
//
// public String getGid() {
// return gid;
// }
//
// public void setGid(String gid) {
// this.gid = gid;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<Plate> getPlates() {
// return plates;
// }
//
// public void setPlates(List<Plate> plates) {
// this.plates = plates;
// }
//
// @Override
// public String toString() {
// return "PlateGroup [gid=" + gid + ", title=" + title + ", plates=" + plates + "]";
// }
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateGroupView.java
import android.content.Context;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.PlateGroup;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
package com.fei_ke.chiphellclient.ui.customviews;
/**
* 版块列表分组
*
* @author fei-ke
* @2014-6-15
*/
@EViewGroup(R.layout.layout_plate_group)
public class PlateGroupView extends FrameLayout {
@ViewById(R.id.textView_title)
TextView textViewTitle;
public static PlateGroupView getInstance(Context context) {
return PlateGroupView_.build(context);
}
public PlateGroupView(Context context) {
super(context);
}
void initViews() {
}
| public void bindValue(PlateGroup plateGroup) { |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/UrlParamsMap.java
// public class UrlParamsMap extends HashMap<String, String> {
// public UrlParamsMap(String url) {
//
// int s = url.indexOf("?");
// if (s == -1)
// return;
// url = url.substring(s + 1);
//
// String[] params = url.split("&");
// for (String paramGroup : params) {
// String[] param = paramGroup.split("=");
// String key = param[0];
// String value;
// if (param.length > 1) {
// value = param[1];
// } else {
// value = "";
// }
// put(key, value);
// }
// }
// }
| import com.fei_ke.chiphellclient.utils.UrlParamsMap; | public String toString() {
return title;
}
public boolean isSubPlate() {
return isSubPlate;
}
public void setSubPlate(boolean isSubPlate) {
this.isSubPlate = isSubPlate;
}
public boolean isFavorite() {
return favoriteId != null;
}
public String getFavoriteId() {
return favoriteId;
}
public void setFavoriteId(String favoriteId) {
this.favoriteId = favoriteId;
}
public void setFid(String fid) {
this.fid = fid;
}
public String getFid() {
if (fid == null) { | // Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/UrlParamsMap.java
// public class UrlParamsMap extends HashMap<String, String> {
// public UrlParamsMap(String url) {
//
// int s = url.indexOf("?");
// if (s == -1)
// return;
// url = url.substring(s + 1);
//
// String[] params = url.split("&");
// for (String paramGroup : params) {
// String[] param = paramGroup.split("=");
// String key = param[0];
// String value;
// if (param.length > 1) {
// value = param[1];
// } else {
// value = "";
// }
// put(key, value);
// }
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
import com.fei_ke.chiphellclient.utils.UrlParamsMap;
public String toString() {
return title;
}
public boolean isSubPlate() {
return isSubPlate;
}
public void setSubPlate(boolean isSubPlate) {
this.isSubPlate = isSubPlate;
}
public boolean isFavorite() {
return favoriteId != null;
}
public String getFavoriteId() {
return favoriteId;
}
public void setFavoriteId(String favoriteId) {
this.favoriteId = favoriteId;
}
public void setFid(String fid) {
this.fid = fid;
}
public String getFid() {
if (fid == null) { | fid = new UrlParamsMap(url).get("fid"); |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/api/support/ApiHelper.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ChhApplication.java
// public class ChhApplication extends Application {
// private static ChhApplication instance;
// private String formHash;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// instance = this;
//
// LogMessage.setDebug(BuildConfig.DEBUG);
//
// initImageLoader();
//
// setupUpdate();
// }
//
// private void setupUpdate() {
// UmengUpdateAgent.setUpdateAutoPopup(false);
// UmengUpdateAgent.setUpdateOnlyWifi(false);
// }
//
//
// public String getFormHash() {
// return formHash;
// }
//
// public void setFormHash(String formHash) {
// this.formHash = formHash;
// }
//
// // 初始化ImageLoader
// private void initImageLoader() {
// DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true)
// .cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.logo)
// .showImageOnFail(R.drawable.logo)
// .showImageOnLoading(R.drawable.logo)
// // .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
// .build();
//
// OkHttpClient client = new OkHttpClient.Builder()
// .connectTimeout(10, TimeUnit.SECONDS)
// .readTimeout(40, TimeUnit.SECONDS)
// .cookieJar(new JavaNetCookieJar(WebViewCookieHandler.getInstance()))
// .build();
// ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
// .denyCacheImageMultipleSizesInMemory()
// .defaultDisplayImageOptions(defaultDisplayImageOptions)
// .imageDownloader(new OkHttpImageDownloader(this, client))
// .build();
// // Initialize ImageLoader with configuration.
// ImageLoader.getInstance().init(config);
//
// }
//
// static class OkHttpImageDownloader extends BaseImageDownloader {
//
//
// private OkHttpClient client;
//
//
// public OkHttpImageDownloader(Context context, OkHttpClient client) {
// super(context);
// this.client = client;
// }
//
//
// @Override
// protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
// Request request = new Request.Builder().url(imageUri).build();
// ResponseBody responseBody = client.newCall(request).execute().body();
// InputStream inputStream = responseBody.byteStream();
// int contentLength = (int) responseBody.contentLength();
// return new ContentLengthInputStream(inputStream, contentLength);
// }
// }
//
// public static ChhApplication getInstance() {
// return instance;
// }
//
// /**
// * 是否登录
// *
// * @return
// */
// public boolean isLogin() {
// return !TextUtils.isEmpty(formHash);
// }
//
//
// }
| import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.fei_ke.chiphellclient.ChhApplication;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.OkUrlFactory; | package com.fei_ke.chiphellclient.api.support;
/**
* Created by fei on 15/11/21.
*/
public class ApiHelper {
// TODO: 15/11/21 queue
static {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cookieJar(new JavaNetCookieJar(WebViewCookieHandler.getInstance()))
.build();
OkHttpStack stack = new OkHttpStack(new OkUrlFactory(okHttpClient)); | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ChhApplication.java
// public class ChhApplication extends Application {
// private static ChhApplication instance;
// private String formHash;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// instance = this;
//
// LogMessage.setDebug(BuildConfig.DEBUG);
//
// initImageLoader();
//
// setupUpdate();
// }
//
// private void setupUpdate() {
// UmengUpdateAgent.setUpdateAutoPopup(false);
// UmengUpdateAgent.setUpdateOnlyWifi(false);
// }
//
//
// public String getFormHash() {
// return formHash;
// }
//
// public void setFormHash(String formHash) {
// this.formHash = formHash;
// }
//
// // 初始化ImageLoader
// private void initImageLoader() {
// DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true)
// .cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.logo)
// .showImageOnFail(R.drawable.logo)
// .showImageOnLoading(R.drawable.logo)
// // .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
// .build();
//
// OkHttpClient client = new OkHttpClient.Builder()
// .connectTimeout(10, TimeUnit.SECONDS)
// .readTimeout(40, TimeUnit.SECONDS)
// .cookieJar(new JavaNetCookieJar(WebViewCookieHandler.getInstance()))
// .build();
// ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
// .denyCacheImageMultipleSizesInMemory()
// .defaultDisplayImageOptions(defaultDisplayImageOptions)
// .imageDownloader(new OkHttpImageDownloader(this, client))
// .build();
// // Initialize ImageLoader with configuration.
// ImageLoader.getInstance().init(config);
//
// }
//
// static class OkHttpImageDownloader extends BaseImageDownloader {
//
//
// private OkHttpClient client;
//
//
// public OkHttpImageDownloader(Context context, OkHttpClient client) {
// super(context);
// this.client = client;
// }
//
//
// @Override
// protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
// Request request = new Request.Builder().url(imageUri).build();
// ResponseBody responseBody = client.newCall(request).execute().body();
// InputStream inputStream = responseBody.byteStream();
// int contentLength = (int) responseBody.contentLength();
// return new ContentLengthInputStream(inputStream, contentLength);
// }
// }
//
// public static ChhApplication getInstance() {
// return instance;
// }
//
// /**
// * 是否登录
// *
// * @return
// */
// public boolean isLogin() {
// return !TextUtils.isEmpty(formHash);
// }
//
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/api/support/ApiHelper.java
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.fei_ke.chiphellclient.ChhApplication;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.OkUrlFactory;
package com.fei_ke.chiphellclient.api.support;
/**
* Created by fei on 15/11/21.
*/
public class ApiHelper {
// TODO: 15/11/21 queue
static {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cookieJar(new JavaNetCookieJar(WebViewCookieHandler.getInstance()))
.build();
OkHttpStack stack = new OkHttpStack(new OkUrlFactory(okHttpClient)); | requestQueue = Volley.newRequestQueue(ChhApplication.getInstance(), stack); |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/GridPicFragment.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/commen/AnimateFirstDisplayListener.java
// public class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
//
// private final List<String> displayedImages = Collections
// .synchronizedList(new LinkedList<String>());
//
// @Override
// public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// if (loadedImage != null) {
// ImageView imageView = (ImageView) view;
// boolean firstDisplay = !displayedImages.contains(imageUri);
// if (firstDisplay) {
// FadeInBitmapDisplayer.animate(imageView, 500);
// displayedImages.add(imageUri);
// }
// }
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/SquareImageView.java
// public class SquareImageView extends ImageView {
// public SquareImageView(Context context) {
// super(context);
// }
//
// public SquareImageView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @Override
// protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// int widthMode = MeasureSpec.getMode(widthMeasureSpec);
// int heightMode = MeasureSpec.getMode(heightMeasureSpec);
// if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) {
// int width = MeasureSpec.getSize(widthMeasureSpec);
// int height = width;
// if (heightMode == MeasureSpec.AT_MOST) {
// height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
// }
// setMeasuredDimension(width, height);
// } else {
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// }
// }
// }
| import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.ui.commen.AnimateFirstDisplayListener;
import com.fei_ke.chiphellclient.ui.customviews.SquareImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List; | package com.fei_ke.chiphellclient.ui.fragment;
/**
* 图片列表
* Created by fei-ke on 2016/2/17.
*/
@EFragment(R.layout.fragment_grid_pic)
public class GridPicFragment extends BaseFragment {
@ViewById(R.id.gridView)
GridView gridView;
private GridAdapter mAdapter;
@Override
protected void onAfterViews() {
mAdapter = new GridAdapter();
gridView.setAdapter(mAdapter);
}
public void update(List<String> pics) {
mAdapter.update(pics);
mAdapter.notifyDataSetChanged();
}
public void setSelection(int position) {
gridView.setSelection(position);
}
public void setOnItemClickListener(@Nullable AdapterView.OnItemClickListener listener) {
gridView.setOnItemClickListener(listener);
}
static class GridAdapter extends BaseAdapter {
private static DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true)
.showImageForEmptyUri(R.drawable.default_img)
.showImageOnFail(R.drawable.default_img)
.showImageOnLoading(R.drawable.default_img)
.build();
private List<String> pics = new ArrayList<>(); | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/commen/AnimateFirstDisplayListener.java
// public class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
//
// private final List<String> displayedImages = Collections
// .synchronizedList(new LinkedList<String>());
//
// @Override
// public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// if (loadedImage != null) {
// ImageView imageView = (ImageView) view;
// boolean firstDisplay = !displayedImages.contains(imageUri);
// if (firstDisplay) {
// FadeInBitmapDisplayer.animate(imageView, 500);
// displayedImages.add(imageUri);
// }
// }
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/SquareImageView.java
// public class SquareImageView extends ImageView {
// public SquareImageView(Context context) {
// super(context);
// }
//
// public SquareImageView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @Override
// protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// int widthMode = MeasureSpec.getMode(widthMeasureSpec);
// int heightMode = MeasureSpec.getMode(heightMeasureSpec);
// if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) {
// int width = MeasureSpec.getSize(widthMeasureSpec);
// int height = width;
// if (heightMode == MeasureSpec.AT_MOST) {
// height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
// }
// setMeasuredDimension(width, height);
// } else {
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// }
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/GridPicFragment.java
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.ui.commen.AnimateFirstDisplayListener;
import com.fei_ke.chiphellclient.ui.customviews.SquareImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List;
package com.fei_ke.chiphellclient.ui.fragment;
/**
* 图片列表
* Created by fei-ke on 2016/2/17.
*/
@EFragment(R.layout.fragment_grid_pic)
public class GridPicFragment extends BaseFragment {
@ViewById(R.id.gridView)
GridView gridView;
private GridAdapter mAdapter;
@Override
protected void onAfterViews() {
mAdapter = new GridAdapter();
gridView.setAdapter(mAdapter);
}
public void update(List<String> pics) {
mAdapter.update(pics);
mAdapter.notifyDataSetChanged();
}
public void setSelection(int position) {
gridView.setSelection(position);
}
public void setOnItemClickListener(@Nullable AdapterView.OnItemClickListener listener) {
gridView.setOnItemClickListener(listener);
}
static class GridAdapter extends BaseAdapter {
private static DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true)
.showImageForEmptyUri(R.drawable.default_img)
.showImageOnFail(R.drawable.default_img)
.showImageOnLoading(R.drawable.default_img)
.build();
private List<String> pics = new ArrayList<>(); | private AnimateFirstDisplayListener firstDisplayListener = new AnimateFirstDisplayListener(); |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/GridPicFragment.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/commen/AnimateFirstDisplayListener.java
// public class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
//
// private final List<String> displayedImages = Collections
// .synchronizedList(new LinkedList<String>());
//
// @Override
// public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// if (loadedImage != null) {
// ImageView imageView = (ImageView) view;
// boolean firstDisplay = !displayedImages.contains(imageUri);
// if (firstDisplay) {
// FadeInBitmapDisplayer.animate(imageView, 500);
// displayedImages.add(imageUri);
// }
// }
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/SquareImageView.java
// public class SquareImageView extends ImageView {
// public SquareImageView(Context context) {
// super(context);
// }
//
// public SquareImageView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @Override
// protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// int widthMode = MeasureSpec.getMode(widthMeasureSpec);
// int heightMode = MeasureSpec.getMode(heightMeasureSpec);
// if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) {
// int width = MeasureSpec.getSize(widthMeasureSpec);
// int height = width;
// if (heightMode == MeasureSpec.AT_MOST) {
// height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
// }
// setMeasuredDimension(width, height);
// } else {
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// }
// }
// }
| import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.ui.commen.AnimateFirstDisplayListener;
import com.fei_ke.chiphellclient.ui.customviews.SquareImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List; | .build();
private List<String> pics = new ArrayList<>();
private AnimateFirstDisplayListener firstDisplayListener = new AnimateFirstDisplayListener();
public void update(List<String> pics) {
this.pics.clear();
this.pics.addAll(pics);
}
@Override
public int getCount() {
return pics == null ? 0 : pics.size();
}
@Override
public String getItem(int position) {
return pics.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView != null) {
imageView = (ImageView) convertView;
} else { | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/commen/AnimateFirstDisplayListener.java
// public class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
//
// private final List<String> displayedImages = Collections
// .synchronizedList(new LinkedList<String>());
//
// @Override
// public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// if (loadedImage != null) {
// ImageView imageView = (ImageView) view;
// boolean firstDisplay = !displayedImages.contains(imageUri);
// if (firstDisplay) {
// FadeInBitmapDisplayer.animate(imageView, 500);
// displayedImages.add(imageUri);
// }
// }
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/SquareImageView.java
// public class SquareImageView extends ImageView {
// public SquareImageView(Context context) {
// super(context);
// }
//
// public SquareImageView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @Override
// protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// int widthMode = MeasureSpec.getMode(widthMeasureSpec);
// int heightMode = MeasureSpec.getMode(heightMeasureSpec);
// if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) {
// int width = MeasureSpec.getSize(widthMeasureSpec);
// int height = width;
// if (heightMode == MeasureSpec.AT_MOST) {
// height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
// }
// setMeasuredDimension(width, height);
// } else {
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// }
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/GridPicFragment.java
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.ui.commen.AnimateFirstDisplayListener;
import com.fei_ke.chiphellclient.ui.customviews.SquareImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List;
.build();
private List<String> pics = new ArrayList<>();
private AnimateFirstDisplayListener firstDisplayListener = new AnimateFirstDisplayListener();
public void update(List<String> pics) {
this.pics.clear();
this.pics.addAll(pics);
}
@Override
public int getCount() {
return pics == null ? 0 : pics.size();
}
@Override
public String getItem(int position) {
return pics.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView != null) {
imageView = (ImageView) convertView;
} else { | imageView = new SquareImageView(parent.getContext()); |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/PostListAdapter.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Post.java
// public class Post extends BaseBean {
// private String avatarUrl;
// private String replyUrl;
// private String content;
// private String authi;// 名字,楼层,时间 html
// private String imgList;// 图片附件列表
// private List<String> images;//图片列表
//
// public String getAvatarUrl() {
// return avatarUrl;
// }
//
// public void setAvatarUrl(String avatarUrl) {
// this.avatarUrl = avatarUrl;
// }
//
// public String getReplyUrl() {
// return replyUrl;
// }
//
// public void setReplyUrl(String replyUrl) {
// this.replyUrl = replyUrl;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public String getAuthi() {
// return authi;
// }
//
// public void setAuthi(String authi) {
// this.authi = authi;
// }
//
// public String getImgList() {
// return imgList;
// }
//
// public void setImgList(String imgList) {
// this.imgList = imgList;
// }
//
// @Override
// public String toString() {
// return "Post [avatarUrl=" + avatarUrl + ", replyUrl=" + replyUrl + ", content=" + content + ", authi=" + authi + "]";
// }
//
// public List<String> getImages() {
// return images;
// }
//
// public void setImages(List<String> images) {
// this.images = images;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PostItemView.java
// @EViewGroup(R.layout.layout_post_item)
// public class PostItemView extends FrameLayout {
// @ViewById(R.id.imageView_avatar)
// ImageView imageViewAvatar;
//
// @ViewById(R.id.textView_content)
// TextView textViewContent;
//
// @ViewById(R.id.textView_authi)
// TextView textViewAuthi;
//
// private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
//
// public static PostItemView newInstance(Context context) {
// return PostItemView_.build(context);
// }
//
// public PostItemView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public PostItemView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public PostItemView(Context context) {
// super(context);
// }
//
// public void bindValue(Post post) {
// ImageLoader.getInstance().displayImage(post.getAvatarUrl(), imageViewAvatar, Constants.avatarDisplayOption, animateFirstListener);
// textViewAuthi.setText(Html.fromHtml(post.getAuthi()));
// String content = post.getContent();
// if (post.getImgList() != null) {
// content += post.getImgList();
// }
// textViewContent.setText(Html.fromHtml(content, new ImageGetter() {
//
// @Override
// public Drawable getDrawable(String source) {
// if (!source.startsWith("http:")) {
// source = Constants.BASE_URL + source;
// }
// LogMessage.i("PostItemView", source);
// return new UrlDrawable(source, textViewContent);
// }
// }, null));
// }
//
// }
| import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.fei_ke.chiphellclient.bean.Post;
import com.fei_ke.chiphellclient.ui.customviews.PostItemView;
import java.util.LinkedList;
import java.util.List; |
package com.fei_ke.chiphellclient.ui.adapter;
/**
* 回帖列表适配器
*
* @author fei-ke
* @2014-6-15
*/
public class PostListAdapter extends BaseAdapter {
private List<Post> mPosts;
@Override
public int getCount() {
return mPosts == null ? 0 : mPosts.size();
}
@Override
public Post getItem(int position) {
return mPosts.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) { | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Post.java
// public class Post extends BaseBean {
// private String avatarUrl;
// private String replyUrl;
// private String content;
// private String authi;// 名字,楼层,时间 html
// private String imgList;// 图片附件列表
// private List<String> images;//图片列表
//
// public String getAvatarUrl() {
// return avatarUrl;
// }
//
// public void setAvatarUrl(String avatarUrl) {
// this.avatarUrl = avatarUrl;
// }
//
// public String getReplyUrl() {
// return replyUrl;
// }
//
// public void setReplyUrl(String replyUrl) {
// this.replyUrl = replyUrl;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public String getAuthi() {
// return authi;
// }
//
// public void setAuthi(String authi) {
// this.authi = authi;
// }
//
// public String getImgList() {
// return imgList;
// }
//
// public void setImgList(String imgList) {
// this.imgList = imgList;
// }
//
// @Override
// public String toString() {
// return "Post [avatarUrl=" + avatarUrl + ", replyUrl=" + replyUrl + ", content=" + content + ", authi=" + authi + "]";
// }
//
// public List<String> getImages() {
// return images;
// }
//
// public void setImages(List<String> images) {
// this.images = images;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PostItemView.java
// @EViewGroup(R.layout.layout_post_item)
// public class PostItemView extends FrameLayout {
// @ViewById(R.id.imageView_avatar)
// ImageView imageViewAvatar;
//
// @ViewById(R.id.textView_content)
// TextView textViewContent;
//
// @ViewById(R.id.textView_authi)
// TextView textViewAuthi;
//
// private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
//
// public static PostItemView newInstance(Context context) {
// return PostItemView_.build(context);
// }
//
// public PostItemView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public PostItemView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public PostItemView(Context context) {
// super(context);
// }
//
// public void bindValue(Post post) {
// ImageLoader.getInstance().displayImage(post.getAvatarUrl(), imageViewAvatar, Constants.avatarDisplayOption, animateFirstListener);
// textViewAuthi.setText(Html.fromHtml(post.getAuthi()));
// String content = post.getContent();
// if (post.getImgList() != null) {
// content += post.getImgList();
// }
// textViewContent.setText(Html.fromHtml(content, new ImageGetter() {
//
// @Override
// public Drawable getDrawable(String source) {
// if (!source.startsWith("http:")) {
// source = Constants.BASE_URL + source;
// }
// LogMessage.i("PostItemView", source);
// return new UrlDrawable(source, textViewContent);
// }
// }, null));
// }
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/PostListAdapter.java
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.fei_ke.chiphellclient.bean.Post;
import com.fei_ke.chiphellclient.ui.customviews.PostItemView;
import java.util.LinkedList;
import java.util.List;
package com.fei_ke.chiphellclient.ui.adapter;
/**
* 回帖列表适配器
*
* @author fei-ke
* @2014-6-15
*/
public class PostListAdapter extends BaseAdapter {
private List<Post> mPosts;
@Override
public int getCount() {
return mPosts == null ? 0 : mPosts.size();
}
@Override
public Post getItem(int position) {
return mPosts.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) { | PostItemView postItemView = null; |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/SmileFragment.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/SmileTable.java
// public class SmileTable {
// public static final Map<String, String> smilis = new HashMap<String, String>();
// static {
// smilis.put("[睡觉]", "sleep.gif");
// smilis.put("[晕倒]", "ft.gif");
// smilis.put("[谩骂]", "abuse.gif");
// smilis.put("[愤怒]", "angry.gif");
// smilis.put("[生病]", "6.gif");
// smilis.put("[再见]", "j.gif");
// smilis.put("[吐槽]", "2.gif");
// smilis.put("[失望]", "5.gif");
//
// smilis.put("[困惑]", "confused.gif");
// smilis.put("[震惊]", "98.gif");
// smilis.put("[可爱]", "lovely.gif");
// smilis.put("[狂笑]", "96.gif");
// smilis.put("[无奈]", "10.gif");
// smilis.put("[吃惊]", "eek.gif");
// smilis.put("[流汗]", "97.gif");
// smilis.put("[流泪]", "99.gif");
//
// smilis.put("[雷人]", "cattle.gif");
// smilis.put("[偷笑]", "fd.gif");
// smilis.put("[傻笑]", "e.gif");
// smilis.put("[高傲]", "shame.gif");
// smilis.put("[怪脸]", "tong.gif");
// smilis.put("[音乐]", "music.gif");
// smilis.put("[喜欢]", "heart.gif");
// smilis.put("[恶魔]", "belial.gif");
//
// }
//
// public static String get(String key) {
// return smilis.get(key);
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/SmileAdapter.java
// public class SmileAdapter extends BaseAdapter {
// List<Entry<String, String>> mDatas;
//
// @Override
// public int getCount() {
// return mDatas == null ? 0 : mDatas.size();
// }
//
// @Override
// public Entry<String, String> getItem(int position) {
// return mDatas.get(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// Entry<String, String> item = getItem(position);
// GifImageView gifImageView = new GifImageView(parent.getContext());
// LayoutParams params = new AbsListView.LayoutParams(120, 120);
// gifImageView.setLayoutParams(params);
// GifDrawable gifDrawable;
// try {
// gifDrawable = new GifDrawable(parent.getContext().getAssets(), item.getValue());
// gifImageView.setImageDrawable(gifDrawable);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return gifImageView;
// }
//
// public void update(List<Entry<String, String>> list) {
// if (mDatas == null) {
// mDatas = new ArrayList<Map.Entry<String, String>>();
// }
// mDatas.addAll(list);
//
// notifyDataSetChanged();
// }
// }
| import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.constant.SmileTable;
import com.fei_ke.chiphellclient.ui.adapter.SmileAdapter;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; |
package com.fei_ke.chiphellclient.ui.fragment;
/**
* 表情
*
* @author fei-ke
* @2014-6-21
*/
@EFragment(R.layout.fragment_smile)
public class SmileFragment extends BaseFragment {
@ViewById(R.id.gridView)
GridView mGridView;
| // Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/SmileTable.java
// public class SmileTable {
// public static final Map<String, String> smilis = new HashMap<String, String>();
// static {
// smilis.put("[睡觉]", "sleep.gif");
// smilis.put("[晕倒]", "ft.gif");
// smilis.put("[谩骂]", "abuse.gif");
// smilis.put("[愤怒]", "angry.gif");
// smilis.put("[生病]", "6.gif");
// smilis.put("[再见]", "j.gif");
// smilis.put("[吐槽]", "2.gif");
// smilis.put("[失望]", "5.gif");
//
// smilis.put("[困惑]", "confused.gif");
// smilis.put("[震惊]", "98.gif");
// smilis.put("[可爱]", "lovely.gif");
// smilis.put("[狂笑]", "96.gif");
// smilis.put("[无奈]", "10.gif");
// smilis.put("[吃惊]", "eek.gif");
// smilis.put("[流汗]", "97.gif");
// smilis.put("[流泪]", "99.gif");
//
// smilis.put("[雷人]", "cattle.gif");
// smilis.put("[偷笑]", "fd.gif");
// smilis.put("[傻笑]", "e.gif");
// smilis.put("[高傲]", "shame.gif");
// smilis.put("[怪脸]", "tong.gif");
// smilis.put("[音乐]", "music.gif");
// smilis.put("[喜欢]", "heart.gif");
// smilis.put("[恶魔]", "belial.gif");
//
// }
//
// public static String get(String key) {
// return smilis.get(key);
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/SmileAdapter.java
// public class SmileAdapter extends BaseAdapter {
// List<Entry<String, String>> mDatas;
//
// @Override
// public int getCount() {
// return mDatas == null ? 0 : mDatas.size();
// }
//
// @Override
// public Entry<String, String> getItem(int position) {
// return mDatas.get(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// Entry<String, String> item = getItem(position);
// GifImageView gifImageView = new GifImageView(parent.getContext());
// LayoutParams params = new AbsListView.LayoutParams(120, 120);
// gifImageView.setLayoutParams(params);
// GifDrawable gifDrawable;
// try {
// gifDrawable = new GifDrawable(parent.getContext().getAssets(), item.getValue());
// gifImageView.setImageDrawable(gifDrawable);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return gifImageView;
// }
//
// public void update(List<Entry<String, String>> list) {
// if (mDatas == null) {
// mDatas = new ArrayList<Map.Entry<String, String>>();
// }
// mDatas.addAll(list);
//
// notifyDataSetChanged();
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/SmileFragment.java
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.constant.SmileTable;
import com.fei_ke.chiphellclient.ui.adapter.SmileAdapter;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
package com.fei_ke.chiphellclient.ui.fragment;
/**
* 表情
*
* @author fei-ke
* @2014-6-21
*/
@EFragment(R.layout.fragment_smile)
public class SmileFragment extends BaseFragment {
@ViewById(R.id.gridView)
GridView mGridView;
| SmileAdapter mAdapter; |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/SmileFragment.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/SmileTable.java
// public class SmileTable {
// public static final Map<String, String> smilis = new HashMap<String, String>();
// static {
// smilis.put("[睡觉]", "sleep.gif");
// smilis.put("[晕倒]", "ft.gif");
// smilis.put("[谩骂]", "abuse.gif");
// smilis.put("[愤怒]", "angry.gif");
// smilis.put("[生病]", "6.gif");
// smilis.put("[再见]", "j.gif");
// smilis.put("[吐槽]", "2.gif");
// smilis.put("[失望]", "5.gif");
//
// smilis.put("[困惑]", "confused.gif");
// smilis.put("[震惊]", "98.gif");
// smilis.put("[可爱]", "lovely.gif");
// smilis.put("[狂笑]", "96.gif");
// smilis.put("[无奈]", "10.gif");
// smilis.put("[吃惊]", "eek.gif");
// smilis.put("[流汗]", "97.gif");
// smilis.put("[流泪]", "99.gif");
//
// smilis.put("[雷人]", "cattle.gif");
// smilis.put("[偷笑]", "fd.gif");
// smilis.put("[傻笑]", "e.gif");
// smilis.put("[高傲]", "shame.gif");
// smilis.put("[怪脸]", "tong.gif");
// smilis.put("[音乐]", "music.gif");
// smilis.put("[喜欢]", "heart.gif");
// smilis.put("[恶魔]", "belial.gif");
//
// }
//
// public static String get(String key) {
// return smilis.get(key);
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/SmileAdapter.java
// public class SmileAdapter extends BaseAdapter {
// List<Entry<String, String>> mDatas;
//
// @Override
// public int getCount() {
// return mDatas == null ? 0 : mDatas.size();
// }
//
// @Override
// public Entry<String, String> getItem(int position) {
// return mDatas.get(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// Entry<String, String> item = getItem(position);
// GifImageView gifImageView = new GifImageView(parent.getContext());
// LayoutParams params = new AbsListView.LayoutParams(120, 120);
// gifImageView.setLayoutParams(params);
// GifDrawable gifDrawable;
// try {
// gifDrawable = new GifDrawable(parent.getContext().getAssets(), item.getValue());
// gifImageView.setImageDrawable(gifDrawable);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return gifImageView;
// }
//
// public void update(List<Entry<String, String>> list) {
// if (mDatas == null) {
// mDatas = new ArrayList<Map.Entry<String, String>>();
// }
// mDatas.addAll(list);
//
// notifyDataSetChanged();
// }
// }
| import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.constant.SmileTable;
import com.fei_ke.chiphellclient.ui.adapter.SmileAdapter;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; |
package com.fei_ke.chiphellclient.ui.fragment;
/**
* 表情
*
* @author fei-ke
* @2014-6-21
*/
@EFragment(R.layout.fragment_smile)
public class SmileFragment extends BaseFragment {
@ViewById(R.id.gridView)
GridView mGridView;
SmileAdapter mAdapter;
OnSmileChoose mOnSmileChoose;
public static SmileFragment getInstance() {
return SmileFragment_.builder().build();
}
@Override
protected void onAfterViews() {
mAdapter = new SmileAdapter();
mGridView.setAdapter(mAdapter);
List<Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(); | // Path: chh/src/main/java/com/fei_ke/chiphellclient/constant/SmileTable.java
// public class SmileTable {
// public static final Map<String, String> smilis = new HashMap<String, String>();
// static {
// smilis.put("[睡觉]", "sleep.gif");
// smilis.put("[晕倒]", "ft.gif");
// smilis.put("[谩骂]", "abuse.gif");
// smilis.put("[愤怒]", "angry.gif");
// smilis.put("[生病]", "6.gif");
// smilis.put("[再见]", "j.gif");
// smilis.put("[吐槽]", "2.gif");
// smilis.put("[失望]", "5.gif");
//
// smilis.put("[困惑]", "confused.gif");
// smilis.put("[震惊]", "98.gif");
// smilis.put("[可爱]", "lovely.gif");
// smilis.put("[狂笑]", "96.gif");
// smilis.put("[无奈]", "10.gif");
// smilis.put("[吃惊]", "eek.gif");
// smilis.put("[流汗]", "97.gif");
// smilis.put("[流泪]", "99.gif");
//
// smilis.put("[雷人]", "cattle.gif");
// smilis.put("[偷笑]", "fd.gif");
// smilis.put("[傻笑]", "e.gif");
// smilis.put("[高傲]", "shame.gif");
// smilis.put("[怪脸]", "tong.gif");
// smilis.put("[音乐]", "music.gif");
// smilis.put("[喜欢]", "heart.gif");
// smilis.put("[恶魔]", "belial.gif");
//
// }
//
// public static String get(String key) {
// return smilis.get(key);
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/SmileAdapter.java
// public class SmileAdapter extends BaseAdapter {
// List<Entry<String, String>> mDatas;
//
// @Override
// public int getCount() {
// return mDatas == null ? 0 : mDatas.size();
// }
//
// @Override
// public Entry<String, String> getItem(int position) {
// return mDatas.get(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// Entry<String, String> item = getItem(position);
// GifImageView gifImageView = new GifImageView(parent.getContext());
// LayoutParams params = new AbsListView.LayoutParams(120, 120);
// gifImageView.setLayoutParams(params);
// GifDrawable gifDrawable;
// try {
// gifDrawable = new GifDrawable(parent.getContext().getAssets(), item.getValue());
// gifImageView.setImageDrawable(gifDrawable);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return gifImageView;
// }
//
// public void update(List<Entry<String, String>> list) {
// if (mDatas == null) {
// mDatas = new ArrayList<Map.Entry<String, String>>();
// }
// mDatas.addAll(list);
//
// notifyDataSetChanged();
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/SmileFragment.java
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.constant.SmileTable;
import com.fei_ke.chiphellclient.ui.adapter.SmileAdapter;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
package com.fei_ke.chiphellclient.ui.fragment;
/**
* 表情
*
* @author fei-ke
* @2014-6-21
*/
@EFragment(R.layout.fragment_smile)
public class SmileFragment extends BaseFragment {
@ViewById(R.id.gridView)
GridView mGridView;
SmileAdapter mAdapter;
OnSmileChoose mOnSmileChoose;
public static SmileFragment getInstance() {
return SmileFragment_.builder().build();
}
@Override
protected void onAfterViews() {
mAdapter = new SmileAdapter();
mGridView.setAdapter(mAdapter);
List<Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(); | for (Entry<String, String> entry : SmileTable.smilis.entrySet()) { |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/SettingActivity.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/SettingFragment.java
// public class SettingFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener {
//
// private MultiSelectListPreference mSwipeEdge;
// private EditTextPreference mForumAddress;
//
// @Override
// public void onDisplayPreferenceDialog(Preference preference) {
// if (!PreferenceFragmentCompatHack.onDisplayPreferenceDialog(this, preference)) {
// super.onDisplayPreferenceDialog(preference);
// }
// }
//
// @Override
// public void onCreatePreferences(Bundle bundle, String s) {
// addPreferencesFromResource(R.xml.setting);
// //getListView().setBackgroundResource(R.color.background_light);
//
// setSwipeEdge();
// setForumAddress();
// }
//
// private void setForumAddress() {
// mForumAddress = (EditTextPreference) findPreference(GlobalSetting.FORUM_ADDRESS);
// String forumAddress = GlobalSetting.getForumAddress();
// mForumAddress.setSummary(forumAddress);
// mForumAddress.setText(forumAddress);
// mForumAddress.setOnPreferenceChangeListener(this);
// }
//
// private void setSwipeEdge() {
// mSwipeEdge = (MultiSelectListPreference) findPreference(GlobalSetting.SWIPE_BACK_EDGE);
// int edge = GlobalSetting.getSwipeBackEdge();
//
// Set<String> edges = new HashSet<String>();
// StringBuilder summary = new StringBuilder();
// if ((edge & SwipeBackLayout.EDGE_LEFT) != 0) {
// edges.add(String.valueOf(SwipeBackLayout.EDGE_LEFT));
// summary.append(getResources().getString(R.string.swipe_edge_left)).append(" ");
// }
// if ((edge & SwipeBackLayout.EDGE_RIGHT) != 0) {
// edges.add(String.valueOf(SwipeBackLayout.EDGE_RIGHT));
// summary.append(getResources().getString(R.string.swipe_edge_right)).append(" ");
// }
// if ((edge & SwipeBackLayout.EDGE_BOTTOM) != 0) {
// edges.add(String.valueOf(SwipeBackLayout.EDGE_BOTTOM));
// summary.append(getResources().getString(R.string.swipe_edge_bottom)).append(" ");
// }
// mSwipeEdge.setValues(edges);
// mSwipeEdge.setSummary(summary.toString());
// mSwipeEdge.setOnPreferenceChangeListener(this);
// }
//
//
// @Override
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// if (preference == mSwipeEdge) {
// Set<String> newValues = (Set<String>) newValue;
// int edge = 0;
// StringBuilder summary = new StringBuilder();
// for (String value : newValues) {
// switch (Integer.parseInt(value)) {
// case SwipeBackLayout.EDGE_LEFT:
// edge |= SwipeBackLayout.EDGE_LEFT;
// summary.append(getResources().getString(R.string.swipe_edge_left)).append(" ");
// break;
// case SwipeBackLayout.EDGE_RIGHT:
// edge |= SwipeBackLayout.EDGE_RIGHT;
// summary.append(getResources().getString(R.string.swipe_edge_right)).append(" ");
// break;
// case SwipeBackLayout.EDGE_BOTTOM:
// edge |= SwipeBackLayout.EDGE_BOTTOM;
// summary.append(getResources().getString(R.string.swipe_edge_bottom)).append(" ");
// break;
// }
// }
// GlobalSetting.putSwipeBackEdge(edge);
// mSwipeEdge.setSummary(summary.toString());
// return true;
// } else if (preference == mForumAddress) {
// String newAddress = (String) newValue;
// if (TextUtils.isEmpty(newAddress)) {
// newAddress = GlobalSetting.DEFAULT_FORUM_ADDRESS;
// }
// if (!newAddress.startsWith("http")) {
// newAddress = "http://" + newAddress;
// }
// if (!newAddress.endsWith("/")) {
// newAddress += "/";
// }
// GlobalSetting.setForumAddress(newAddress);
// mForumAddress.setSummary(newAddress);
// ToastUtil.show(getActivity(), "需重新启动应用生效");
// return true;
// }
// return false;
// }
// }
| import android.os.Bundle;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.ui.fragment.SettingFragment; |
package com.fei_ke.chiphellclient.ui.activity;
/**
* 设置页面
*
* @author fei-ke
* @2014年6月28日
*/
public class SettingActivity extends BaseActivity {
@Override
protected void onAfterViews() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
setTitle(R.string.action_settings);
getSupportFragmentManager().beginTransaction() | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/SettingFragment.java
// public class SettingFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener {
//
// private MultiSelectListPreference mSwipeEdge;
// private EditTextPreference mForumAddress;
//
// @Override
// public void onDisplayPreferenceDialog(Preference preference) {
// if (!PreferenceFragmentCompatHack.onDisplayPreferenceDialog(this, preference)) {
// super.onDisplayPreferenceDialog(preference);
// }
// }
//
// @Override
// public void onCreatePreferences(Bundle bundle, String s) {
// addPreferencesFromResource(R.xml.setting);
// //getListView().setBackgroundResource(R.color.background_light);
//
// setSwipeEdge();
// setForumAddress();
// }
//
// private void setForumAddress() {
// mForumAddress = (EditTextPreference) findPreference(GlobalSetting.FORUM_ADDRESS);
// String forumAddress = GlobalSetting.getForumAddress();
// mForumAddress.setSummary(forumAddress);
// mForumAddress.setText(forumAddress);
// mForumAddress.setOnPreferenceChangeListener(this);
// }
//
// private void setSwipeEdge() {
// mSwipeEdge = (MultiSelectListPreference) findPreference(GlobalSetting.SWIPE_BACK_EDGE);
// int edge = GlobalSetting.getSwipeBackEdge();
//
// Set<String> edges = new HashSet<String>();
// StringBuilder summary = new StringBuilder();
// if ((edge & SwipeBackLayout.EDGE_LEFT) != 0) {
// edges.add(String.valueOf(SwipeBackLayout.EDGE_LEFT));
// summary.append(getResources().getString(R.string.swipe_edge_left)).append(" ");
// }
// if ((edge & SwipeBackLayout.EDGE_RIGHT) != 0) {
// edges.add(String.valueOf(SwipeBackLayout.EDGE_RIGHT));
// summary.append(getResources().getString(R.string.swipe_edge_right)).append(" ");
// }
// if ((edge & SwipeBackLayout.EDGE_BOTTOM) != 0) {
// edges.add(String.valueOf(SwipeBackLayout.EDGE_BOTTOM));
// summary.append(getResources().getString(R.string.swipe_edge_bottom)).append(" ");
// }
// mSwipeEdge.setValues(edges);
// mSwipeEdge.setSummary(summary.toString());
// mSwipeEdge.setOnPreferenceChangeListener(this);
// }
//
//
// @Override
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// if (preference == mSwipeEdge) {
// Set<String> newValues = (Set<String>) newValue;
// int edge = 0;
// StringBuilder summary = new StringBuilder();
// for (String value : newValues) {
// switch (Integer.parseInt(value)) {
// case SwipeBackLayout.EDGE_LEFT:
// edge |= SwipeBackLayout.EDGE_LEFT;
// summary.append(getResources().getString(R.string.swipe_edge_left)).append(" ");
// break;
// case SwipeBackLayout.EDGE_RIGHT:
// edge |= SwipeBackLayout.EDGE_RIGHT;
// summary.append(getResources().getString(R.string.swipe_edge_right)).append(" ");
// break;
// case SwipeBackLayout.EDGE_BOTTOM:
// edge |= SwipeBackLayout.EDGE_BOTTOM;
// summary.append(getResources().getString(R.string.swipe_edge_bottom)).append(" ");
// break;
// }
// }
// GlobalSetting.putSwipeBackEdge(edge);
// mSwipeEdge.setSummary(summary.toString());
// return true;
// } else if (preference == mForumAddress) {
// String newAddress = (String) newValue;
// if (TextUtils.isEmpty(newAddress)) {
// newAddress = GlobalSetting.DEFAULT_FORUM_ADDRESS;
// }
// if (!newAddress.startsWith("http")) {
// newAddress = "http://" + newAddress;
// }
// if (!newAddress.endsWith("/")) {
// newAddress += "/";
// }
// GlobalSetting.setForumAddress(newAddress);
// mForumAddress.setSummary(newAddress);
// ToastUtil.show(getActivity(), "需重新启动应用生效");
// return true;
// }
// return false;
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/activity/SettingActivity.java
import android.os.Bundle;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.ui.fragment.SettingFragment;
package com.fei_ke.chiphellclient.ui.activity;
/**
* 设置页面
*
* @author fei-ke
* @2014年6月28日
*/
public class SettingActivity extends BaseActivity {
@Override
protected void onAfterViews() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
setTitle(R.string.action_settings);
getSupportFragmentManager().beginTransaction() | .add(R.id.root_layout, new SettingFragment()) |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/bean/Thread.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/UrlParamsMap.java
// public class UrlParamsMap extends HashMap<String, String> {
// public UrlParamsMap(String url) {
//
// int s = url.indexOf("?");
// if (s == -1)
// return;
// url = url.substring(s + 1);
//
// String[] params = url.split("&");
// for (String paramGroup : params) {
// String[] param = paramGroup.split("=");
// String key = param[0];
// String value;
// if (param.length > 1) {
// value = param[1];
// } else {
// value = "";
// }
// put(key, value);
// }
// }
// }
| import com.fei_ke.chiphellclient.utils.UrlParamsMap; | }
public String getCount() {
calcDateAndCount();
return count;
}
public void setCount(String count) {
this.count = count;
}
public void setTimeAndCount(String timeAndCount) {
this.timeAndCount = timeAndCount;
}
public int getTitleColor() {
return titleColor;
}
public void setTitleColor(int titleColor) {
this.titleColor = titleColor;
}
@Override
public String toString() {
return "Thread [title=" + title + ", url=" + url + ", by=" + by + ", timeAndCount=" + timeAndCount + "]";
}
public String getTid() {
if (tid == null) { | // Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/UrlParamsMap.java
// public class UrlParamsMap extends HashMap<String, String> {
// public UrlParamsMap(String url) {
//
// int s = url.indexOf("?");
// if (s == -1)
// return;
// url = url.substring(s + 1);
//
// String[] params = url.split("&");
// for (String paramGroup : params) {
// String[] param = paramGroup.split("=");
// String key = param[0];
// String value;
// if (param.length > 1) {
// value = param[1];
// } else {
// value = "";
// }
// put(key, value);
// }
// }
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Thread.java
import com.fei_ke.chiphellclient.utils.UrlParamsMap;
}
public String getCount() {
calcDateAndCount();
return count;
}
public void setCount(String count) {
this.count = count;
}
public void setTimeAndCount(String timeAndCount) {
this.timeAndCount = timeAndCount;
}
public int getTitleColor() {
return titleColor;
}
public void setTitleColor(int titleColor) {
this.titleColor = titleColor;
}
@Override
public String toString() {
return "Thread [title=" + title + ", url=" + url + ", by=" + by + ", timeAndCount=" + timeAndCount + "]";
}
public String getTid() {
if (tid == null) { | tid = new UrlParamsMap(url).get("tid"); |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ChhApplication.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/api/support/WebViewCookieHandler.java
// public class WebViewCookieHandler extends CookieHandler {
// private static WebViewCookieHandler singleton;
//
// private CookieManager cookieManager = CookieManager.getInstance();
//
// public static WebViewCookieHandler getInstance() {
// if (singleton == null) {
// synchronized (WebViewCookieHandler.class) {
// if (singleton == null) {
// singleton = new WebViewCookieHandler();
// }
// }
// }
// return singleton;
// }
//
// private WebViewCookieHandler() {
// }
//
// @Override
// public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
// String url = uri.toString();
// String cookieValue = cookieManager.getCookie(url);
// Map<String, List<String>> cookies = new HashMap<>();
// if (!TextUtils.isEmpty(cookieValue)) {
// cookies.put("Cookie", Arrays.asList(cookieValue));
// }
// return cookies;
// }
//
// @Override
// public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
// String url = uri.toString();
// for (String header : responseHeaders.keySet()) {
// if (header.equalsIgnoreCase("Set-Cookie") || header.equalsIgnoreCase("Set-Cookie2")) {
// for (String value : responseHeaders.get(header)) {
// //if (!TextUtils.isEmpty(value))
// cookieManager.setCookie(url, value);
// }
// }
// }
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/LogMessage.java
// public class LogMessage {
//
// // 是否打印日志
// private static boolean isDebug = true;
// // 日志标签
// public static String LOG_TAG = "frame";
//
// public static void v(String tag, Object msg) {
// if (isDebug) {
// Log.v(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void i(String tag, Object msg) {
// if (isDebug) {
// Log.i(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void d(String tag, Object msg) {
// if (isDebug) {
// Log.d(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void w(String tag, Object msg) {
// if (isDebug) {
// Log.w(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void e(String tag, Object msg) {
// if (isDebug) {
// Log.e(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void print(String tag, String msg) {
// // System.out.println("tag=="+msg);
// }
//
// /**
// * 设置debug 模式
// *
// * @param isDebug true 打印日志 false:不打印
// */
//
// public static void setDebug(boolean isDebug) {
// LogMessage.isDebug = isDebug;
// }
//
// public static boolean isDebug(){
// return isDebug;
// }
//
// }
| import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieSyncManager;
import com.fei_ke.chiphellclient.api.support.WebViewCookieHandler;
import com.fei_ke.chiphellclient.utils.LogMessage;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ContentLengthInputStream;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.umeng.update.UmengUpdateAgent;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody; | package com.fei_ke.chiphellclient;
public class ChhApplication extends Application {
private static ChhApplication instance;
private String formHash;
@Override
public void onCreate() {
super.onCreate();
instance = this;
| // Path: chh/src/main/java/com/fei_ke/chiphellclient/api/support/WebViewCookieHandler.java
// public class WebViewCookieHandler extends CookieHandler {
// private static WebViewCookieHandler singleton;
//
// private CookieManager cookieManager = CookieManager.getInstance();
//
// public static WebViewCookieHandler getInstance() {
// if (singleton == null) {
// synchronized (WebViewCookieHandler.class) {
// if (singleton == null) {
// singleton = new WebViewCookieHandler();
// }
// }
// }
// return singleton;
// }
//
// private WebViewCookieHandler() {
// }
//
// @Override
// public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
// String url = uri.toString();
// String cookieValue = cookieManager.getCookie(url);
// Map<String, List<String>> cookies = new HashMap<>();
// if (!TextUtils.isEmpty(cookieValue)) {
// cookies.put("Cookie", Arrays.asList(cookieValue));
// }
// return cookies;
// }
//
// @Override
// public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
// String url = uri.toString();
// for (String header : responseHeaders.keySet()) {
// if (header.equalsIgnoreCase("Set-Cookie") || header.equalsIgnoreCase("Set-Cookie2")) {
// for (String value : responseHeaders.get(header)) {
// //if (!TextUtils.isEmpty(value))
// cookieManager.setCookie(url, value);
// }
// }
// }
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/LogMessage.java
// public class LogMessage {
//
// // 是否打印日志
// private static boolean isDebug = true;
// // 日志标签
// public static String LOG_TAG = "frame";
//
// public static void v(String tag, Object msg) {
// if (isDebug) {
// Log.v(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void i(String tag, Object msg) {
// if (isDebug) {
// Log.i(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void d(String tag, Object msg) {
// if (isDebug) {
// Log.d(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void w(String tag, Object msg) {
// if (isDebug) {
// Log.w(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void e(String tag, Object msg) {
// if (isDebug) {
// Log.e(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void print(String tag, String msg) {
// // System.out.println("tag=="+msg);
// }
//
// /**
// * 设置debug 模式
// *
// * @param isDebug true 打印日志 false:不打印
// */
//
// public static void setDebug(boolean isDebug) {
// LogMessage.isDebug = isDebug;
// }
//
// public static boolean isDebug(){
// return isDebug;
// }
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ChhApplication.java
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieSyncManager;
import com.fei_ke.chiphellclient.api.support.WebViewCookieHandler;
import com.fei_ke.chiphellclient.utils.LogMessage;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ContentLengthInputStream;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.umeng.update.UmengUpdateAgent;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
package com.fei_ke.chiphellclient;
public class ChhApplication extends Application {
private static ChhApplication instance;
private String formHash;
@Override
public void onCreate() {
super.onCreate();
instance = this;
| LogMessage.setDebug(BuildConfig.DEBUG); |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ChhApplication.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/api/support/WebViewCookieHandler.java
// public class WebViewCookieHandler extends CookieHandler {
// private static WebViewCookieHandler singleton;
//
// private CookieManager cookieManager = CookieManager.getInstance();
//
// public static WebViewCookieHandler getInstance() {
// if (singleton == null) {
// synchronized (WebViewCookieHandler.class) {
// if (singleton == null) {
// singleton = new WebViewCookieHandler();
// }
// }
// }
// return singleton;
// }
//
// private WebViewCookieHandler() {
// }
//
// @Override
// public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
// String url = uri.toString();
// String cookieValue = cookieManager.getCookie(url);
// Map<String, List<String>> cookies = new HashMap<>();
// if (!TextUtils.isEmpty(cookieValue)) {
// cookies.put("Cookie", Arrays.asList(cookieValue));
// }
// return cookies;
// }
//
// @Override
// public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
// String url = uri.toString();
// for (String header : responseHeaders.keySet()) {
// if (header.equalsIgnoreCase("Set-Cookie") || header.equalsIgnoreCase("Set-Cookie2")) {
// for (String value : responseHeaders.get(header)) {
// //if (!TextUtils.isEmpty(value))
// cookieManager.setCookie(url, value);
// }
// }
// }
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/LogMessage.java
// public class LogMessage {
//
// // 是否打印日志
// private static boolean isDebug = true;
// // 日志标签
// public static String LOG_TAG = "frame";
//
// public static void v(String tag, Object msg) {
// if (isDebug) {
// Log.v(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void i(String tag, Object msg) {
// if (isDebug) {
// Log.i(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void d(String tag, Object msg) {
// if (isDebug) {
// Log.d(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void w(String tag, Object msg) {
// if (isDebug) {
// Log.w(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void e(String tag, Object msg) {
// if (isDebug) {
// Log.e(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void print(String tag, String msg) {
// // System.out.println("tag=="+msg);
// }
//
// /**
// * 设置debug 模式
// *
// * @param isDebug true 打印日志 false:不打印
// */
//
// public static void setDebug(boolean isDebug) {
// LogMessage.isDebug = isDebug;
// }
//
// public static boolean isDebug(){
// return isDebug;
// }
//
// }
| import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieSyncManager;
import com.fei_ke.chiphellclient.api.support.WebViewCookieHandler;
import com.fei_ke.chiphellclient.utils.LogMessage;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ContentLengthInputStream;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.umeng.update.UmengUpdateAgent;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody; | }
private void setupUpdate() {
UmengUpdateAgent.setUpdateAutoPopup(false);
UmengUpdateAgent.setUpdateOnlyWifi(false);
}
public String getFormHash() {
return formHash;
}
public void setFormHash(String formHash) {
this.formHash = formHash;
}
// 初始化ImageLoader
private void initImageLoader() {
DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.showImageForEmptyUri(R.drawable.logo)
.showImageOnFail(R.drawable.logo)
.showImageOnLoading(R.drawable.logo)
// .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.build();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(40, TimeUnit.SECONDS) | // Path: chh/src/main/java/com/fei_ke/chiphellclient/api/support/WebViewCookieHandler.java
// public class WebViewCookieHandler extends CookieHandler {
// private static WebViewCookieHandler singleton;
//
// private CookieManager cookieManager = CookieManager.getInstance();
//
// public static WebViewCookieHandler getInstance() {
// if (singleton == null) {
// synchronized (WebViewCookieHandler.class) {
// if (singleton == null) {
// singleton = new WebViewCookieHandler();
// }
// }
// }
// return singleton;
// }
//
// private WebViewCookieHandler() {
// }
//
// @Override
// public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
// String url = uri.toString();
// String cookieValue = cookieManager.getCookie(url);
// Map<String, List<String>> cookies = new HashMap<>();
// if (!TextUtils.isEmpty(cookieValue)) {
// cookies.put("Cookie", Arrays.asList(cookieValue));
// }
// return cookies;
// }
//
// @Override
// public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
// String url = uri.toString();
// for (String header : responseHeaders.keySet()) {
// if (header.equalsIgnoreCase("Set-Cookie") || header.equalsIgnoreCase("Set-Cookie2")) {
// for (String value : responseHeaders.get(header)) {
// //if (!TextUtils.isEmpty(value))
// cookieManager.setCookie(url, value);
// }
// }
// }
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/utils/LogMessage.java
// public class LogMessage {
//
// // 是否打印日志
// private static boolean isDebug = true;
// // 日志标签
// public static String LOG_TAG = "frame";
//
// public static void v(String tag, Object msg) {
// if (isDebug) {
// Log.v(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void i(String tag, Object msg) {
// if (isDebug) {
// Log.i(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void d(String tag, Object msg) {
// if (isDebug) {
// Log.d(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void w(String tag, Object msg) {
// if (isDebug) {
// Log.w(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void e(String tag, Object msg) {
// if (isDebug) {
// Log.e(tag, msg != null ? msg.toString() : "null");
// }
// }
//
// public static void print(String tag, String msg) {
// // System.out.println("tag=="+msg);
// }
//
// /**
// * 设置debug 模式
// *
// * @param isDebug true 打印日志 false:不打印
// */
//
// public static void setDebug(boolean isDebug) {
// LogMessage.isDebug = isDebug;
// }
//
// public static boolean isDebug(){
// return isDebug;
// }
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ChhApplication.java
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieSyncManager;
import com.fei_ke.chiphellclient.api.support.WebViewCookieHandler;
import com.fei_ke.chiphellclient.utils.LogMessage;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ContentLengthInputStream;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.umeng.update.UmengUpdateAgent;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
}
private void setupUpdate() {
UmengUpdateAgent.setUpdateAutoPopup(false);
UmengUpdateAgent.setUpdateOnlyWifi(false);
}
public String getFormHash() {
return formHash;
}
public void setFormHash(String formHash) {
this.formHash = formHash;
}
// 初始化ImageLoader
private void initImageLoader() {
DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.showImageForEmptyUri(R.drawable.logo)
.showImageOnFail(R.drawable.logo)
.showImageOnLoading(R.drawable.logo)
// .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.build();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(40, TimeUnit.SECONDS) | .cookieJar(new JavaNetCookieJar(WebViewCookieHandler.getInstance())) |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateHead.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateClass.java
// public class PlateClass extends Plate {
// String title;
// String url;
// String fid;// 版块id
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.Spinner;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.Plate;
import com.fei_ke.chiphellclient.bean.PlateClass;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List; | package com.fei_ke.chiphellclient.ui.customviews;
/**
* 版块顶部视图
*
* @author fei-ke
* @2014年7月5日
*/
@EViewGroup(R.layout.layout_plate_head)
public class PlateHead extends FrameLayout {
@ViewById(R.id.spinnerClass)
protected Spinner spinnerClass;
@ViewById(R.id.spinnerOrderBy)
protected Spinner spinnerOrderBy;
@ViewById
protected View btnFavorite;
| // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateClass.java
// public class PlateClass extends Plate {
// String title;
// String url;
// String fid;// 版块id
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateHead.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.Spinner;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.Plate;
import com.fei_ke.chiphellclient.bean.PlateClass;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List;
package com.fei_ke.chiphellclient.ui.customviews;
/**
* 版块顶部视图
*
* @author fei-ke
* @2014年7月5日
*/
@EViewGroup(R.layout.layout_plate_head)
public class PlateHead extends FrameLayout {
@ViewById(R.id.spinnerClass)
protected Spinner spinnerClass;
@ViewById(R.id.spinnerOrderBy)
protected Spinner spinnerOrderBy;
@ViewById
protected View btnFavorite;
| private ArrayAdapter<PlateClass> mAdapter; |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateHead.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateClass.java
// public class PlateClass extends Plate {
// String title;
// String url;
// String fid;// 版块id
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.Spinner;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.Plate;
import com.fei_ke.chiphellclient.bean.PlateClass;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List; |
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerOrderBy.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, new String[]{"默认排序", "新帖排序"}));
spinnerOrderBy.setTag(0);
spinnerOrderBy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if ((Integer) spinnerOrderBy.getTag() == position) return;
if (mOnOrderBySelectedListener != null) {
mOnOrderBySelectedListener.onOrderBySelected(position);
}
spinnerOrderBy.setTag(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
| // Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/Plate.java
// public class Plate extends BaseBean {
// private String title;
// private String url;
// private String xg1;// 今日帖数
// private String fid;// 版块id
// private String favoriteId;
// private boolean isSubPlate;// 是否是子版块
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getXg1() {
// return xg1 == null ? "(0)" : xg1;
// }
//
// public void setXg1(String xg1) {
// this.xg1 = xg1;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public boolean isSubPlate() {
// return isSubPlate;
// }
//
// public void setSubPlate(boolean isSubPlate) {
// this.isSubPlate = isSubPlate;
// }
//
// public boolean isFavorite() {
// return favoriteId != null;
// }
//
// public String getFavoriteId() {
// return favoriteId;
// }
//
// public void setFavoriteId(String favoriteId) {
// this.favoriteId = favoriteId;
// }
//
// public void setFid(String fid) {
// this.fid = fid;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Plate) {
// if (((Plate) o).getFid().equals(this.getFid())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: chh/src/main/java/com/fei_ke/chiphellclient/bean/PlateClass.java
// public class PlateClass extends Plate {
// String title;
// String url;
// String fid;// 版块id
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @Override
// public String toString() {
// return title;
// }
//
// public String getFid() {
// if (fid == null) {
// fid = new UrlParamsMap(url).get("fid");
// }
// return fid;
// }
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/customviews/PlateHead.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.Spinner;
import com.fei_ke.chiphellclient.R;
import com.fei_ke.chiphellclient.bean.Plate;
import com.fei_ke.chiphellclient.bean.PlateClass;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List;
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerOrderBy.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, new String[]{"默认排序", "新帖排序"}));
spinnerOrderBy.setTag(0);
spinnerOrderBy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if ((Integer) spinnerOrderBy.getTag() == position) return;
if (mOnOrderBySelectedListener != null) {
mOnOrderBySelectedListener.onOrderBySelected(position);
}
spinnerOrderBy.setTag(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
| public void bindValue(Plate plate, List<PlateClass> plateClasses) { |
fei-ke/ChipHellClient | chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/AlbumAdapter.java | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/PicFargment.java
// @EFragment(R.layout.fragment_pic)
// public class PicFargment extends BaseFragment {
// private static final String TAG = "PicFargment";
//
// private static DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.default_img)
// .showImageOnFail(R.drawable.default_img)
// .build();
//
// private OnViewTapListener mViewTapListener;
// PhotoViewAttacher mPhotoViewAttacher;
// @FragmentArg
// protected String mUrl;
//
// @ViewById(R.id.imageView_pic)
// GifImageView mImageView;
//
// @ViewById(R.id.progressBar)
// ProgressBar mProgressBar;
//
// @ViewById
// View mainFrame;
//
// public static PicFargment getInstance(String url) {
// return PicFargment_.builder().mUrl(url).build();
// }
//
// public void setOnViewTapListener(OnViewTapListener mViewTapListener) {
// this.mViewTapListener = mViewTapListener;
// }
//
// @Override
// protected void onAfterViews() {
// Log.i(TAG, "onAfterViews: url "+mUrl);
// mPhotoViewAttacher = new PhotoViewAttacher(mImageView);
// ImageLoader.getInstance().displayImage(mUrl, mImageView, imageOptions, new SimpleImageLoadingListener() {
// final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
//
// @Override
// public void onLoadingComplete(String url, View view, Bitmap bitmap) {
// if (bitmap == null) return;
//
// if (url.endsWith(".gif") || url.endsWith(".GIF")) {
// File file = ImageLoader.getInstance().getDiscCache().get(url);
// try {
// GifDrawable drawable = new GifDrawable(file);
// mImageView.setImageDrawable(drawable);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// boolean firstDisplay = !displayedImages.contains(url);
// if (firstDisplay) {
// FadeInBitmapDisplayer.animate(mImageView, 500);
// displayedImages.add(url);
// }
//
// mPhotoViewAttacher.update();
// mProgressBar.setVisibility(View.GONE);
//
// Palette p = Palette.from(bitmap).generate();
// //mainFrame.setBackgroundColor(p.getLightMutedColor(Color.BLACK));
//
// ColorDrawable background = (ColorDrawable) mainFrame.getBackground();
// ObjectAnimator animator = ObjectAnimator.ofInt(mainFrame, "backgroundColor", background.getColor(), p.getLightMutedColor(Color.BLACK));
// animator.setEvaluator(new ArgbEvaluator());
// animator.setDuration(500);
// animator.start();
// }
// });
//
// mPhotoViewAttacher.setOnPhotoTapListener(new OnPhotoTapListener() {
//
// @Override
// public void onPhotoTap(View arg0, float arg1, float arg2) {
// getActivity().finish();
// }
// });
// }
//
// @Override
// public void onDestroyView() {
// mPhotoViewAttacher.cleanup();
// System.gc();
// super.onDestroyView();
// }
//
// public static interface OnViewTapListener {
// void OnViewTap();
// }
//
//
// }
| import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.fei_ke.chiphellclient.ui.fragment.PicFargment;
import java.util.ArrayList;
import java.util.List; |
package com.fei_ke.chiphellclient.ui.adapter;
/**
* 相册适配器
*
* @author fei-ke
* @2014-6-22
*/
public class AlbumAdapter extends FragmentStatePagerAdapter {
List<String> mDatas;
public AlbumAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) { | // Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/fragment/PicFargment.java
// @EFragment(R.layout.fragment_pic)
// public class PicFargment extends BaseFragment {
// private static final String TAG = "PicFargment";
//
// private static DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
// .cacheInMemory(true).cacheOnDisk(true)
// .showImageForEmptyUri(R.drawable.default_img)
// .showImageOnFail(R.drawable.default_img)
// .build();
//
// private OnViewTapListener mViewTapListener;
// PhotoViewAttacher mPhotoViewAttacher;
// @FragmentArg
// protected String mUrl;
//
// @ViewById(R.id.imageView_pic)
// GifImageView mImageView;
//
// @ViewById(R.id.progressBar)
// ProgressBar mProgressBar;
//
// @ViewById
// View mainFrame;
//
// public static PicFargment getInstance(String url) {
// return PicFargment_.builder().mUrl(url).build();
// }
//
// public void setOnViewTapListener(OnViewTapListener mViewTapListener) {
// this.mViewTapListener = mViewTapListener;
// }
//
// @Override
// protected void onAfterViews() {
// Log.i(TAG, "onAfterViews: url "+mUrl);
// mPhotoViewAttacher = new PhotoViewAttacher(mImageView);
// ImageLoader.getInstance().displayImage(mUrl, mImageView, imageOptions, new SimpleImageLoadingListener() {
// final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
//
// @Override
// public void onLoadingComplete(String url, View view, Bitmap bitmap) {
// if (bitmap == null) return;
//
// if (url.endsWith(".gif") || url.endsWith(".GIF")) {
// File file = ImageLoader.getInstance().getDiscCache().get(url);
// try {
// GifDrawable drawable = new GifDrawable(file);
// mImageView.setImageDrawable(drawable);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// boolean firstDisplay = !displayedImages.contains(url);
// if (firstDisplay) {
// FadeInBitmapDisplayer.animate(mImageView, 500);
// displayedImages.add(url);
// }
//
// mPhotoViewAttacher.update();
// mProgressBar.setVisibility(View.GONE);
//
// Palette p = Palette.from(bitmap).generate();
// //mainFrame.setBackgroundColor(p.getLightMutedColor(Color.BLACK));
//
// ColorDrawable background = (ColorDrawable) mainFrame.getBackground();
// ObjectAnimator animator = ObjectAnimator.ofInt(mainFrame, "backgroundColor", background.getColor(), p.getLightMutedColor(Color.BLACK));
// animator.setEvaluator(new ArgbEvaluator());
// animator.setDuration(500);
// animator.start();
// }
// });
//
// mPhotoViewAttacher.setOnPhotoTapListener(new OnPhotoTapListener() {
//
// @Override
// public void onPhotoTap(View arg0, float arg1, float arg2) {
// getActivity().finish();
// }
// });
// }
//
// @Override
// public void onDestroyView() {
// mPhotoViewAttacher.cleanup();
// System.gc();
// super.onDestroyView();
// }
//
// public static interface OnViewTapListener {
// void OnViewTap();
// }
//
//
// }
// Path: chh/src/main/java/com/fei_ke/chiphellclient/ui/adapter/AlbumAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.fei_ke.chiphellclient.ui.fragment.PicFargment;
import java.util.ArrayList;
import java.util.List;
package com.fei_ke.chiphellclient.ui.adapter;
/**
* 相册适配器
*
* @author fei-ke
* @2014-6-22
*/
public class AlbumAdapter extends FragmentStatePagerAdapter {
List<String> mDatas;
public AlbumAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) { | return PicFargment.getInstance(mDatas.get(position)); |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6/src/test/java/eu/chargetime/ocpp/feature/profile/test/ClientFirmwareManagementProfileTest.java | // Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ClientFirmwareManagementProfile.java
// public class ClientFirmwareManagementProfile implements Profile {
//
// private HashSet<Feature> features;
// private ClientFirmwareManagementEventHandler eventHandler;
//
// public ClientFirmwareManagementProfile(ClientFirmwareManagementEventHandler eventHandler) {
// this.eventHandler = eventHandler;
// features = new HashSet<>();
// features.add(new GetDiagnosticsFeature(this));
// features.add(new UpdateFirmwareFeature(this));
// }
//
// /**
// * Create a {@link DiagnosticsStatusNotificationRequest} with required values.
// *
// * @param status required. Identification of the {@link DiagnosticsStatus}.
// * @return an instance of {@link DiagnosticsStatusNotificationRequest}.
// * @see DiagnosticsStatusNotificationRequest
// * @see DiagnosticsStatusNotificationFeature
// */
// public DiagnosticsStatusNotificationRequest createDiagnosticsStatusNotificationRequest(
// DiagnosticsStatus status) {
// return new DiagnosticsStatusNotificationRequest(status);
// }
//
// /**
// * Create a {@link FirmwareStatusNotificationRequest} with required values.
// *
// * @param status required. Identification of the {@link FirmwareStatus}.
// * @return an instance of {@link FirmwareStatusNotificationRequest}.
// * @see FirmwareStatusNotificationRequest
// * @see FirmwareStatusNotificationFeature
// */
// public FirmwareStatusNotificationRequest createFirmwareStatusNotificationRequest(
// FirmwareStatus status) {
// return new FirmwareStatusNotificationRequest(status);
// }
//
// @Override
// public ProfileFeature[] getFeatureList() {
// return features.toArray(new ProfileFeature[0]);
// }
//
// @Override
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// Confirmation result = null;
//
// if (request instanceof GetDiagnosticsRequest) {
// result = eventHandler.handleGetDiagnosticsRequest((GetDiagnosticsRequest) request);
// } else if (request instanceof UpdateFirmwareRequest) {
// result = eventHandler.handleUpdateFirmwareRequest((UpdateFirmwareRequest) request);
// }
//
// return result;
// }
// }
| import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import eu.chargetime.ocpp.feature.*;
import eu.chargetime.ocpp.feature.profile.ClientFirmwareManagementEventHandler;
import eu.chargetime.ocpp.feature.profile.ClientFirmwareManagementProfile;
import eu.chargetime.ocpp.model.firmware.*;
import java.time.ZonedDateTime;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq; | package eu.chargetime.ocpp.feature.profile.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
@RunWith(MockitoJUnitRunner.class)
public class ClientFirmwareManagementProfileTest extends ProfileTest {
private static final UUID SESSION_NULL = null; | // Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ClientFirmwareManagementProfile.java
// public class ClientFirmwareManagementProfile implements Profile {
//
// private HashSet<Feature> features;
// private ClientFirmwareManagementEventHandler eventHandler;
//
// public ClientFirmwareManagementProfile(ClientFirmwareManagementEventHandler eventHandler) {
// this.eventHandler = eventHandler;
// features = new HashSet<>();
// features.add(new GetDiagnosticsFeature(this));
// features.add(new UpdateFirmwareFeature(this));
// }
//
// /**
// * Create a {@link DiagnosticsStatusNotificationRequest} with required values.
// *
// * @param status required. Identification of the {@link DiagnosticsStatus}.
// * @return an instance of {@link DiagnosticsStatusNotificationRequest}.
// * @see DiagnosticsStatusNotificationRequest
// * @see DiagnosticsStatusNotificationFeature
// */
// public DiagnosticsStatusNotificationRequest createDiagnosticsStatusNotificationRequest(
// DiagnosticsStatus status) {
// return new DiagnosticsStatusNotificationRequest(status);
// }
//
// /**
// * Create a {@link FirmwareStatusNotificationRequest} with required values.
// *
// * @param status required. Identification of the {@link FirmwareStatus}.
// * @return an instance of {@link FirmwareStatusNotificationRequest}.
// * @see FirmwareStatusNotificationRequest
// * @see FirmwareStatusNotificationFeature
// */
// public FirmwareStatusNotificationRequest createFirmwareStatusNotificationRequest(
// FirmwareStatus status) {
// return new FirmwareStatusNotificationRequest(status);
// }
//
// @Override
// public ProfileFeature[] getFeatureList() {
// return features.toArray(new ProfileFeature[0]);
// }
//
// @Override
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// Confirmation result = null;
//
// if (request instanceof GetDiagnosticsRequest) {
// result = eventHandler.handleGetDiagnosticsRequest((GetDiagnosticsRequest) request);
// } else if (request instanceof UpdateFirmwareRequest) {
// result = eventHandler.handleUpdateFirmwareRequest((UpdateFirmwareRequest) request);
// }
//
// return result;
// }
// }
// Path: ocpp-v1_6/src/test/java/eu/chargetime/ocpp/feature/profile/test/ClientFirmwareManagementProfileTest.java
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import eu.chargetime.ocpp.feature.*;
import eu.chargetime.ocpp.feature.profile.ClientFirmwareManagementEventHandler;
import eu.chargetime.ocpp.feature.profile.ClientFirmwareManagementProfile;
import eu.chargetime.ocpp.model.firmware.*;
import java.time.ZonedDateTime;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq;
package eu.chargetime.ocpp.feature.profile.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
@RunWith(MockitoJUnitRunner.class)
public class ClientFirmwareManagementProfileTest extends ProfileTest {
private static final UUID SESSION_NULL = null; | ClientFirmwareManagementProfile profile; |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v2_0/src/test/java/eu/chargetime/ocpp/model/basic/test/StatusNotificationRequestTest.java | // Path: ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/StatusNotificationRequest.java
// public class StatusNotificationRequest implements Request {
//
// private transient RequiredValidator validator = new RequiredValidator();
//
// private ZonedDateTime timestamp;
//
// private ConnectorStatusEnumType connectorStatus;
//
// private Integer evseId;
//
// private Integer connectorId;
//
// /**
// * This is the time for which the status is reported
// *
// * @return {@link ZonedDateTime}
// */
// public ZonedDateTime getTimestamp() {
// return timestamp;
// }
//
// /**
// * Required. Time the status is reported.
// *
// * @param timestamp {@link ZonedDateTime}
// */
// public void setTimestamp(ZonedDateTime timestamp) {
// validator.validate(timestamp);
// this.timestamp = timestamp;
// }
//
// /**
// * This contains the current status of the Connector.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public ConnectorStatusEnumType getConnectorStatus() {
// return connectorStatus;
// }
//
// /**
// * Required. The current status of the Connector.
// *
// * @param connectorStatus {@link ConnectorStatusEnumType}
// */
// public void setConnectorStatus(ConnectorStatusEnumType connectorStatus) {
// validator.validate(connectorStatus);
// this.connectorStatus = connectorStatus;
// }
//
// /**
// * This is the id of the EVSE to which the connector belongs for which the status is reported.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public Integer getEvseId() {
// return evseId;
// }
//
// /**
// * Required. The id of the EVSE to which the connector belongs for which the status is reported.
// *
// * @param evseId integer, evse id
// */
// public void setEvseId(Integer evseId) {
// validator.validate(evseId);
// this.evseId = evseId;
// }
//
// /**
// * This is the id of the connector within the EVSE for which the status is reported.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public Integer getConnectorId() {
// return connectorId;
// }
//
// /**
// * Required. The id of the connector within the EVSE for which the status is reported.
// *
// * @param connectorId integer, connector id
// */
// public void setConnectorId(Integer connectorId) {
// validator.validate(connectorId);
// this.connectorId = connectorId;
// }
//
// @Override
// public boolean transactionRelated() {
// return false;
// }
//
// @Override
// public boolean validate() {
// return validator.safeValidate(timestamp)
// && validator.safeValidate(connectorStatus)
// && validator.safeValidate(evseId)
// && validator.safeValidate(connectorId);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// StatusNotificationRequest that = (StatusNotificationRequest) o;
// return Objects.equals(connectorStatus, that.connectorStatus)
// && Objects.equals(evseId, that.evseId)
// && Objects.equals(connectorId, that.connectorId);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(timestamp, connectorStatus, evseId, connectorId);
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("timestamp", timestamp)
// .add("connectorStatus", connectorStatus)
// .add("evseId", evseId)
// .add("connectorId", connectorId)
// .toString();
// }
// }
//
// Path: ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/types/ConnectorStatusEnumType.java
// public enum ConnectorStatusEnumType {
// Available,
// Occupied,
// Reserved,
// Unavailable,
// Faulted
// }
| import org.junit.Test;
import eu.chargetime.ocpp.PropertyConstraintException;
import eu.chargetime.ocpp.model.basic.StatusNotificationRequest;
import eu.chargetime.ocpp.model.basic.types.ConnectorStatusEnumType;
import java.time.ZonedDateTime;
import org.junit.Assert; | package eu.chargetime.ocpp.model.basic.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2021 John Michael Luy <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class StatusNotificationRequestTest {
@Test(expected = PropertyConstraintException.class)
public void setTimestamp_null_throwsPropertyConstraintException() { | // Path: ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/StatusNotificationRequest.java
// public class StatusNotificationRequest implements Request {
//
// private transient RequiredValidator validator = new RequiredValidator();
//
// private ZonedDateTime timestamp;
//
// private ConnectorStatusEnumType connectorStatus;
//
// private Integer evseId;
//
// private Integer connectorId;
//
// /**
// * This is the time for which the status is reported
// *
// * @return {@link ZonedDateTime}
// */
// public ZonedDateTime getTimestamp() {
// return timestamp;
// }
//
// /**
// * Required. Time the status is reported.
// *
// * @param timestamp {@link ZonedDateTime}
// */
// public void setTimestamp(ZonedDateTime timestamp) {
// validator.validate(timestamp);
// this.timestamp = timestamp;
// }
//
// /**
// * This contains the current status of the Connector.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public ConnectorStatusEnumType getConnectorStatus() {
// return connectorStatus;
// }
//
// /**
// * Required. The current status of the Connector.
// *
// * @param connectorStatus {@link ConnectorStatusEnumType}
// */
// public void setConnectorStatus(ConnectorStatusEnumType connectorStatus) {
// validator.validate(connectorStatus);
// this.connectorStatus = connectorStatus;
// }
//
// /**
// * This is the id of the EVSE to which the connector belongs for which the status is reported.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public Integer getEvseId() {
// return evseId;
// }
//
// /**
// * Required. The id of the EVSE to which the connector belongs for which the status is reported.
// *
// * @param evseId integer, evse id
// */
// public void setEvseId(Integer evseId) {
// validator.validate(evseId);
// this.evseId = evseId;
// }
//
// /**
// * This is the id of the connector within the EVSE for which the status is reported.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public Integer getConnectorId() {
// return connectorId;
// }
//
// /**
// * Required. The id of the connector within the EVSE for which the status is reported.
// *
// * @param connectorId integer, connector id
// */
// public void setConnectorId(Integer connectorId) {
// validator.validate(connectorId);
// this.connectorId = connectorId;
// }
//
// @Override
// public boolean transactionRelated() {
// return false;
// }
//
// @Override
// public boolean validate() {
// return validator.safeValidate(timestamp)
// && validator.safeValidate(connectorStatus)
// && validator.safeValidate(evseId)
// && validator.safeValidate(connectorId);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// StatusNotificationRequest that = (StatusNotificationRequest) o;
// return Objects.equals(connectorStatus, that.connectorStatus)
// && Objects.equals(evseId, that.evseId)
// && Objects.equals(connectorId, that.connectorId);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(timestamp, connectorStatus, evseId, connectorId);
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("timestamp", timestamp)
// .add("connectorStatus", connectorStatus)
// .add("evseId", evseId)
// .add("connectorId", connectorId)
// .toString();
// }
// }
//
// Path: ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/types/ConnectorStatusEnumType.java
// public enum ConnectorStatusEnumType {
// Available,
// Occupied,
// Reserved,
// Unavailable,
// Faulted
// }
// Path: ocpp-v2_0/src/test/java/eu/chargetime/ocpp/model/basic/test/StatusNotificationRequestTest.java
import org.junit.Test;
import eu.chargetime.ocpp.PropertyConstraintException;
import eu.chargetime.ocpp.model.basic.StatusNotificationRequest;
import eu.chargetime.ocpp.model.basic.types.ConnectorStatusEnumType;
import java.time.ZonedDateTime;
import org.junit.Assert;
package eu.chargetime.ocpp.model.basic.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2021 John Michael Luy <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class StatusNotificationRequestTest {
@Test(expected = PropertyConstraintException.class)
public void setTimestamp_null_throwsPropertyConstraintException() { | StatusNotificationRequest sut = new StatusNotificationRequest(); |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v2_0/src/test/java/eu/chargetime/ocpp/model/basic/test/StatusNotificationRequestTest.java | // Path: ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/StatusNotificationRequest.java
// public class StatusNotificationRequest implements Request {
//
// private transient RequiredValidator validator = new RequiredValidator();
//
// private ZonedDateTime timestamp;
//
// private ConnectorStatusEnumType connectorStatus;
//
// private Integer evseId;
//
// private Integer connectorId;
//
// /**
// * This is the time for which the status is reported
// *
// * @return {@link ZonedDateTime}
// */
// public ZonedDateTime getTimestamp() {
// return timestamp;
// }
//
// /**
// * Required. Time the status is reported.
// *
// * @param timestamp {@link ZonedDateTime}
// */
// public void setTimestamp(ZonedDateTime timestamp) {
// validator.validate(timestamp);
// this.timestamp = timestamp;
// }
//
// /**
// * This contains the current status of the Connector.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public ConnectorStatusEnumType getConnectorStatus() {
// return connectorStatus;
// }
//
// /**
// * Required. The current status of the Connector.
// *
// * @param connectorStatus {@link ConnectorStatusEnumType}
// */
// public void setConnectorStatus(ConnectorStatusEnumType connectorStatus) {
// validator.validate(connectorStatus);
// this.connectorStatus = connectorStatus;
// }
//
// /**
// * This is the id of the EVSE to which the connector belongs for which the status is reported.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public Integer getEvseId() {
// return evseId;
// }
//
// /**
// * Required. The id of the EVSE to which the connector belongs for which the status is reported.
// *
// * @param evseId integer, evse id
// */
// public void setEvseId(Integer evseId) {
// validator.validate(evseId);
// this.evseId = evseId;
// }
//
// /**
// * This is the id of the connector within the EVSE for which the status is reported.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public Integer getConnectorId() {
// return connectorId;
// }
//
// /**
// * Required. The id of the connector within the EVSE for which the status is reported.
// *
// * @param connectorId integer, connector id
// */
// public void setConnectorId(Integer connectorId) {
// validator.validate(connectorId);
// this.connectorId = connectorId;
// }
//
// @Override
// public boolean transactionRelated() {
// return false;
// }
//
// @Override
// public boolean validate() {
// return validator.safeValidate(timestamp)
// && validator.safeValidate(connectorStatus)
// && validator.safeValidate(evseId)
// && validator.safeValidate(connectorId);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// StatusNotificationRequest that = (StatusNotificationRequest) o;
// return Objects.equals(connectorStatus, that.connectorStatus)
// && Objects.equals(evseId, that.evseId)
// && Objects.equals(connectorId, that.connectorId);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(timestamp, connectorStatus, evseId, connectorId);
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("timestamp", timestamp)
// .add("connectorStatus", connectorStatus)
// .add("evseId", evseId)
// .add("connectorId", connectorId)
// .toString();
// }
// }
//
// Path: ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/types/ConnectorStatusEnumType.java
// public enum ConnectorStatusEnumType {
// Available,
// Occupied,
// Reserved,
// Unavailable,
// Faulted
// }
| import org.junit.Test;
import eu.chargetime.ocpp.PropertyConstraintException;
import eu.chargetime.ocpp.model.basic.StatusNotificationRequest;
import eu.chargetime.ocpp.model.basic.types.ConnectorStatusEnumType;
import java.time.ZonedDateTime;
import org.junit.Assert; | @Test(expected = PropertyConstraintException.class)
public void setEvseId_null_throwsPropertyConstraintException() {
StatusNotificationRequest sut = new StatusNotificationRequest();
sut.setEvseId(null);
}
@Test(expected = PropertyConstraintException.class)
public void setConnectorId_null_throwsPropertyConstraintException() {
StatusNotificationRequest sut = new StatusNotificationRequest();
sut.setConnectorId(null);
}
@Test
public void validate_nothingIsSet_returnsFalse() {
boolean expected = false;
StatusNotificationRequest sut = new StatusNotificationRequest();
boolean result = sut.validate();
Assert.assertEquals(expected, result);
}
@Test
public void validate_dataIsSet_returnsTrue() {
boolean expected = true;
StatusNotificationRequest sut = new StatusNotificationRequest();
sut.setTimestamp(ZonedDateTime.now()); | // Path: ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/StatusNotificationRequest.java
// public class StatusNotificationRequest implements Request {
//
// private transient RequiredValidator validator = new RequiredValidator();
//
// private ZonedDateTime timestamp;
//
// private ConnectorStatusEnumType connectorStatus;
//
// private Integer evseId;
//
// private Integer connectorId;
//
// /**
// * This is the time for which the status is reported
// *
// * @return {@link ZonedDateTime}
// */
// public ZonedDateTime getTimestamp() {
// return timestamp;
// }
//
// /**
// * Required. Time the status is reported.
// *
// * @param timestamp {@link ZonedDateTime}
// */
// public void setTimestamp(ZonedDateTime timestamp) {
// validator.validate(timestamp);
// this.timestamp = timestamp;
// }
//
// /**
// * This contains the current status of the Connector.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public ConnectorStatusEnumType getConnectorStatus() {
// return connectorStatus;
// }
//
// /**
// * Required. The current status of the Connector.
// *
// * @param connectorStatus {@link ConnectorStatusEnumType}
// */
// public void setConnectorStatus(ConnectorStatusEnumType connectorStatus) {
// validator.validate(connectorStatus);
// this.connectorStatus = connectorStatus;
// }
//
// /**
// * This is the id of the EVSE to which the connector belongs for which the status is reported.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public Integer getEvseId() {
// return evseId;
// }
//
// /**
// * Required. The id of the EVSE to which the connector belongs for which the status is reported.
// *
// * @param evseId integer, evse id
// */
// public void setEvseId(Integer evseId) {
// validator.validate(evseId);
// this.evseId = evseId;
// }
//
// /**
// * This is the id of the connector within the EVSE for which the status is reported.
// *
// * @return {@link ConnectorStatusEnumType}
// */
// public Integer getConnectorId() {
// return connectorId;
// }
//
// /**
// * Required. The id of the connector within the EVSE for which the status is reported.
// *
// * @param connectorId integer, connector id
// */
// public void setConnectorId(Integer connectorId) {
// validator.validate(connectorId);
// this.connectorId = connectorId;
// }
//
// @Override
// public boolean transactionRelated() {
// return false;
// }
//
// @Override
// public boolean validate() {
// return validator.safeValidate(timestamp)
// && validator.safeValidate(connectorStatus)
// && validator.safeValidate(evseId)
// && validator.safeValidate(connectorId);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// StatusNotificationRequest that = (StatusNotificationRequest) o;
// return Objects.equals(connectorStatus, that.connectorStatus)
// && Objects.equals(evseId, that.evseId)
// && Objects.equals(connectorId, that.connectorId);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(timestamp, connectorStatus, evseId, connectorId);
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("timestamp", timestamp)
// .add("connectorStatus", connectorStatus)
// .add("evseId", evseId)
// .add("connectorId", connectorId)
// .toString();
// }
// }
//
// Path: ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/types/ConnectorStatusEnumType.java
// public enum ConnectorStatusEnumType {
// Available,
// Occupied,
// Reserved,
// Unavailable,
// Faulted
// }
// Path: ocpp-v2_0/src/test/java/eu/chargetime/ocpp/model/basic/test/StatusNotificationRequestTest.java
import org.junit.Test;
import eu.chargetime.ocpp.PropertyConstraintException;
import eu.chargetime.ocpp.model.basic.StatusNotificationRequest;
import eu.chargetime.ocpp.model.basic.types.ConnectorStatusEnumType;
import java.time.ZonedDateTime;
import org.junit.Assert;
@Test(expected = PropertyConstraintException.class)
public void setEvseId_null_throwsPropertyConstraintException() {
StatusNotificationRequest sut = new StatusNotificationRequest();
sut.setEvseId(null);
}
@Test(expected = PropertyConstraintException.class)
public void setConnectorId_null_throwsPropertyConstraintException() {
StatusNotificationRequest sut = new StatusNotificationRequest();
sut.setConnectorId(null);
}
@Test
public void validate_nothingIsSet_returnsFalse() {
boolean expected = false;
StatusNotificationRequest sut = new StatusNotificationRequest();
boolean result = sut.validate();
Assert.assertEquals(expected, result);
}
@Test
public void validate_dataIsSet_returnsTrue() {
boolean expected = true;
StatusNotificationRequest sut = new StatusNotificationRequest();
sut.setTimestamp(ZonedDateTime.now()); | sut.setConnectorStatus(ConnectorStatusEnumType.Available); |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/SendLocalListFeature.java | // Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/model/localauthlist/SendLocalListRequest.java
// public class SendLocalListRequest implements Request {
//
// private Integer listVersion = 0;
// private AuthorizationData[] localAuthorizationList = null;
// private UpdateType updateType = null;
//
// /**
// * @deprecated use {@link #SendLocalListRequest(Integer, UpdateType)} to be sure to set required
// * fields
// */
// @Deprecated
// public SendLocalListRequest() {}
//
// /**
// * Handle required fields.
// *
// * @param listVersion, the version number of the list, see {@link #setListVersion(Integer)}
// * @param updateType, {@link UpdateType}}, see {@link #setUpdateType(UpdateType)}
// */
// public SendLocalListRequest(Integer listVersion, UpdateType updateType) {
// this.listVersion = listVersion;
// this.updateType = updateType;
// }
//
// /**
// * In case of a full update this is the version number of the full list. In case of a differential
// * update it is the version number of the list after the update has been applied.
// *
// * @return Integer, the version number of the list
// */
// public Integer getListVersion() {
// return listVersion;
// }
//
// /**
// * Required. In case of a full update this is the version number of the full list. In case of a
// * differential update it is the version number of the list after the update has been applied.
// *
// * @param listVersion, the version number of the list
// */
// public void setListVersion(Integer listVersion) {
// if (listVersion < 1) {
// throw new PropertyConstraintException(listVersion, "listVersion must be > 0");
// }
// this.listVersion = listVersion;
// }
//
// /**
// * In case of a full update this contains the list of values that form the new local authorization
// * list. In case of a differential update it contains the changes to be applied to the local
// * authorization list in the Charge Point.
// *
// * @return Array of {@link AuthorizationData}
// */
// public AuthorizationData[] getLocalAuthorizationList() {
// return localAuthorizationList;
// }
//
// /**
// * Optional. In case of a full update this contains the list of values that form the new local
// * authorization list. In case of a differential update it contains the changes to be applied to
// * the local authorization list in the Charge Point.
// *
// * @param localAuthorizationList, Array of {@link AuthorizationData}
// */
// public void setLocalAuthorizationList(AuthorizationData[] localAuthorizationList) {
// this.localAuthorizationList = localAuthorizationList;
// }
//
// /**
// * Required. This contains the type of update (full or differential) of this request.
// *
// * @return {@link UpdateType}
// */
// public UpdateType getUpdateType() {
// return updateType;
// }
//
// /**
// * Required. This contains the type of update (full or differential) of this request.
// *
// * @param updateType, {@link UpdateType}}
// */
// public void setUpdateType(UpdateType updateType) {
// this.updateType = updateType;
// }
//
// @Override
// public boolean validate() {
// boolean valid = listVersion != null && (listVersion >= 1) && (updateType != null);
//
// if (localAuthorizationList != null) {
// for (AuthorizationData data : localAuthorizationList) {
// valid &= data.validate();
//
// if (updateType == UpdateType.Full) {
// valid &= data.getIdTagInfo() != null;
// }
// }
// }
//
// return valid;
// }
//
// @Override
// public boolean transactionRelated() {
// return false;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// SendLocalListRequest that = (SendLocalListRequest) o;
// return Objects.equals(listVersion, that.listVersion)
// && Arrays.equals(localAuthorizationList, that.localAuthorizationList)
// && updateType == that.updateType;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(listVersion, localAuthorizationList, updateType);
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("listVersion", listVersion)
// .add("localAuthorizationList", localAuthorizationList)
// .add("updateType", updateType)
// .add("isValid", validate())
// .toString();
// }
// }
| import eu.chargetime.ocpp.model.localauthlist.SendLocalListConfirmation;
import eu.chargetime.ocpp.model.localauthlist.SendLocalListRequest;
import eu.chargetime.ocpp.feature.profile.Profile;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request; | package eu.chargetime.ocpp.feature;
/*
ChargeTime.eu - Java-OCA-OCPP
Copyright (C) 2015-2018 Thomas Volden <[email protected]>
MIT License
Copyright (c) 2016-2018 Thomas Volden
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class SendLocalListFeature extends ProfileFeature {
public SendLocalListFeature(Profile ownerProfile) {
super(ownerProfile);
}
@Override
public Class<? extends Request> getRequestType() { | // Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/model/localauthlist/SendLocalListRequest.java
// public class SendLocalListRequest implements Request {
//
// private Integer listVersion = 0;
// private AuthorizationData[] localAuthorizationList = null;
// private UpdateType updateType = null;
//
// /**
// * @deprecated use {@link #SendLocalListRequest(Integer, UpdateType)} to be sure to set required
// * fields
// */
// @Deprecated
// public SendLocalListRequest() {}
//
// /**
// * Handle required fields.
// *
// * @param listVersion, the version number of the list, see {@link #setListVersion(Integer)}
// * @param updateType, {@link UpdateType}}, see {@link #setUpdateType(UpdateType)}
// */
// public SendLocalListRequest(Integer listVersion, UpdateType updateType) {
// this.listVersion = listVersion;
// this.updateType = updateType;
// }
//
// /**
// * In case of a full update this is the version number of the full list. In case of a differential
// * update it is the version number of the list after the update has been applied.
// *
// * @return Integer, the version number of the list
// */
// public Integer getListVersion() {
// return listVersion;
// }
//
// /**
// * Required. In case of a full update this is the version number of the full list. In case of a
// * differential update it is the version number of the list after the update has been applied.
// *
// * @param listVersion, the version number of the list
// */
// public void setListVersion(Integer listVersion) {
// if (listVersion < 1) {
// throw new PropertyConstraintException(listVersion, "listVersion must be > 0");
// }
// this.listVersion = listVersion;
// }
//
// /**
// * In case of a full update this contains the list of values that form the new local authorization
// * list. In case of a differential update it contains the changes to be applied to the local
// * authorization list in the Charge Point.
// *
// * @return Array of {@link AuthorizationData}
// */
// public AuthorizationData[] getLocalAuthorizationList() {
// return localAuthorizationList;
// }
//
// /**
// * Optional. In case of a full update this contains the list of values that form the new local
// * authorization list. In case of a differential update it contains the changes to be applied to
// * the local authorization list in the Charge Point.
// *
// * @param localAuthorizationList, Array of {@link AuthorizationData}
// */
// public void setLocalAuthorizationList(AuthorizationData[] localAuthorizationList) {
// this.localAuthorizationList = localAuthorizationList;
// }
//
// /**
// * Required. This contains the type of update (full or differential) of this request.
// *
// * @return {@link UpdateType}
// */
// public UpdateType getUpdateType() {
// return updateType;
// }
//
// /**
// * Required. This contains the type of update (full or differential) of this request.
// *
// * @param updateType, {@link UpdateType}}
// */
// public void setUpdateType(UpdateType updateType) {
// this.updateType = updateType;
// }
//
// @Override
// public boolean validate() {
// boolean valid = listVersion != null && (listVersion >= 1) && (updateType != null);
//
// if (localAuthorizationList != null) {
// for (AuthorizationData data : localAuthorizationList) {
// valid &= data.validate();
//
// if (updateType == UpdateType.Full) {
// valid &= data.getIdTagInfo() != null;
// }
// }
// }
//
// return valid;
// }
//
// @Override
// public boolean transactionRelated() {
// return false;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// SendLocalListRequest that = (SendLocalListRequest) o;
// return Objects.equals(listVersion, that.listVersion)
// && Arrays.equals(localAuthorizationList, that.localAuthorizationList)
// && updateType == that.updateType;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(listVersion, localAuthorizationList, updateType);
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("listVersion", listVersion)
// .add("localAuthorizationList", localAuthorizationList)
// .add("updateType", updateType)
// .add("isValid", validate())
// .toString();
// }
// }
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/SendLocalListFeature.java
import eu.chargetime.ocpp.model.localauthlist.SendLocalListConfirmation;
import eu.chargetime.ocpp.model.localauthlist.SendLocalListRequest;
import eu.chargetime.ocpp.feature.profile.Profile;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
package eu.chargetime.ocpp.feature;
/*
ChargeTime.eu - Java-OCA-OCPP
Copyright (C) 2015-2018 Thomas Volden <[email protected]>
MIT License
Copyright (c) 2016-2018 Thomas Volden
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class SendLocalListFeature extends ProfileFeature {
public SendLocalListFeature(Profile ownerProfile) {
super(ownerProfile);
}
@Override
public Class<? extends Request> getRequestType() { | return SendLocalListRequest.class; |
ChargeTimeEU/Java-OCA-OCPP | ocpp-common/src/test/java/eu/chargetime/ocpp/test/FeatureRepositoryTest.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/TestRequest.java
// public class TestRequest implements Request {
// @Override
// public boolean validate() {
// return true;
// }
//
// @Override
// public boolean transactionRelated() {
// return false;
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import eu.chargetime.ocpp.FeatureRepository;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.TestConfirmation;
import eu.chargetime.ocpp.model.TestRequest;
import java.util.Optional;
import java.util.UUID;
import org.junit.Test; | package eu.chargetime.ocpp.test;
public class FeatureRepositoryTest {
private final TestFeature feature = new TestFeature();
private static final String ACTION_NAME = "TestFeature";
@Test
public void testFind() {
FeatureRepository f = new FeatureRepository();
f.addFeature(feature);
assertFalse(f.findFeature("TestFeatureFail").isPresent());
assertFalse(f.findFeature(3).isPresent());
assertWhenFound(f.findFeature(ACTION_NAME)); | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/TestRequest.java
// public class TestRequest implements Request {
// @Override
// public boolean validate() {
// return true;
// }
//
// @Override
// public boolean transactionRelated() {
// return false;
// }
// }
// Path: ocpp-common/src/test/java/eu/chargetime/ocpp/test/FeatureRepositoryTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import eu.chargetime.ocpp.FeatureRepository;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.TestConfirmation;
import eu.chargetime.ocpp.model.TestRequest;
import java.util.Optional;
import java.util.UUID;
import org.junit.Test;
package eu.chargetime.ocpp.test;
public class FeatureRepositoryTest {
private final TestFeature feature = new TestFeature();
private static final String ACTION_NAME = "TestFeature";
@Test
public void testFind() {
FeatureRepository f = new FeatureRepository();
f.addFeature(feature);
assertFalse(f.findFeature("TestFeatureFail").isPresent());
assertFalse(f.findFeature(3).isPresent());
assertWhenFound(f.findFeature(ACTION_NAME)); | assertWhenFound(f.findFeature(new TestRequest())); |
ChargeTimeEU/Java-OCA-OCPP | ocpp-common/src/main/java/eu/chargetime/ocpp/Server.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
| import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.SessionInformation;
import java.util.Map; | package eu.chargetime.ocpp;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* Handles basic server logic: Holds a list of supported features. Keeps track of outgoing requests.
* Calls back when a confirmation is received.
*/
public class Server {
private static final Logger logger = LoggerFactory.getLogger(Server.class);
public static final int INITIAL_SESSIONS_NUMBER = 1000;
private Map<UUID, ISession> sessions;
private Listener listener;
private final IFeatureRepository featureRepository;
private final IPromiseRepository promiseRepository;
/**
* Constructor. Handles the required injections.
*
* @param listener injected listener.
*/
public Server(
Listener listener,
IFeatureRepository featureRepository,
IPromiseRepository promiseRepository) {
this.listener = listener;
this.featureRepository = featureRepository;
this.promiseRepository = promiseRepository;
this.sessions = new ConcurrentHashMap<>(INITIAL_SESSIONS_NUMBER);
}
/**
* Start listening for clients.
*
* @param hostname Url or IP of the server as String.
* @param port the port number of the server.
* @param serverEvents Callback handler for server specific events.
*/
public void open(String hostname, int port, ServerEvents serverEvents) {
listener.open(
hostname,
port,
new ListenerEvents() {
@Override
public void authenticateSession( | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/Server.java
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.SessionInformation;
import java.util.Map;
package eu.chargetime.ocpp;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* Handles basic server logic: Holds a list of supported features. Keeps track of outgoing requests.
* Calls back when a confirmation is received.
*/
public class Server {
private static final Logger logger = LoggerFactory.getLogger(Server.class);
public static final int INITIAL_SESSIONS_NUMBER = 1000;
private Map<UUID, ISession> sessions;
private Listener listener;
private final IFeatureRepository featureRepository;
private final IPromiseRepository promiseRepository;
/**
* Constructor. Handles the required injections.
*
* @param listener injected listener.
*/
public Server(
Listener listener,
IFeatureRepository featureRepository,
IPromiseRepository promiseRepository) {
this.listener = listener;
this.featureRepository = featureRepository;
this.promiseRepository = promiseRepository;
this.sessions = new ConcurrentHashMap<>(INITIAL_SESSIONS_NUMBER);
}
/**
* Start listening for clients.
*
* @param hostname Url or IP of the server as String.
* @param port the port number of the server.
* @param serverEvents Callback handler for server specific events.
*/
public void open(String hostname, int port, ServerEvents serverEvents) {
listener.open(
hostname,
port,
new ListenerEvents() {
@Override
public void authenticateSession( | SessionInformation information, String username, byte[] password) |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/handler/AuthorizeHandlerTest.java | // Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerCoreProfileConfig.java
// @TestConfiguration
// @Getter
// @Slf4j
// public class TestServerCoreProfileConfig {
//
// @Bean
// public ServerCoreEventHandler getCoreEventHandler() {
// return new ServerCoreEventHandler() {
// @Override
// public AuthorizeConfirmation handleAuthorizeRequest(UUID sessionIndex, AuthorizeRequest request) {
//
// System.out.println(request);
// // ... handle event
// IdTagInfo idTagInfo = new IdTagInfo();
// idTagInfo.setExpiryDate(ZonedDateTime.now());
// idTagInfo.setParentIdTag("test");
// idTagInfo.setStatus(AuthorizationStatus.Accepted);
//
// return new AuthorizeConfirmation(idTagInfo);
// }
//
// @Override
// public BootNotificationConfirmation handleBootNotificationRequest(UUID sessionIndex, BootNotificationRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public DataTransferConfirmation handleDataTransferRequest(UUID sessionIndex, DataTransferRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public HeartbeatConfirmation handleHeartbeatRequest(UUID sessionIndex, HeartbeatRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public MeterValuesConfirmation handleMeterValuesRequest(UUID sessionIndex, MeterValuesRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StartTransactionConfirmation handleStartTransactionRequest(UUID sessionIndex, StartTransactionRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StatusNotificationConfirmation handleStatusNotificationRequest(UUID sessionIndex, StatusNotificationRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StopTransactionConfirmation handleStopTransactionRequest(UUID sessionIndex, StopTransactionRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
// };
// }
//
// @Bean
// public ServerCoreProfile createCore(ServerCoreEventHandler serverCoreEventHandler) {
// return new ServerCoreProfile(serverCoreEventHandler);
// }
// }
//
// Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerEventConfig.java
// @TestConfiguration
// @Getter
// @Slf4j
// public class TestServerEventConfig {
//
// @Bean
// public ServerEvents createServerCoreImpl() {
// return getNewServerEventsImpl();
// }
//
// private ServerEvents getNewServerEventsImpl() {
// return new ServerEvents() {
//
// @Override
// public void newSession(UUID sessionIndex, SessionInformation information) {
//
// // sessionIndex is used to send messages.
// System.out.println("New session " + sessionIndex + ": " + information.getIdentifier());
// }
//
// @Override
// public void lostSession(UUID sessionIndex) {
//
// System.out.println("Session " + sessionIndex + " lost connection");
// }
// };
// }
// }
| import eu.chargetime.ocpp.feature.profile.ServerCoreEventHandler;
import eu.chargetime.ocpp.jsonserverimplementation.config.TestServerCoreProfileConfig;
import eu.chargetime.ocpp.jsonserverimplementation.config.TestServerEventConfig;
import eu.chargetime.ocpp.model.core.AuthorizationStatus;
import eu.chargetime.ocpp.model.core.AuthorizeConfirmation;
import eu.chargetime.ocpp.model.core.AuthorizeRequest;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals; | package eu.chargetime.ocpp.jsonserverimplementation.handler;
@RunWith(SpringRunner.class)
@Slf4j | // Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerCoreProfileConfig.java
// @TestConfiguration
// @Getter
// @Slf4j
// public class TestServerCoreProfileConfig {
//
// @Bean
// public ServerCoreEventHandler getCoreEventHandler() {
// return new ServerCoreEventHandler() {
// @Override
// public AuthorizeConfirmation handleAuthorizeRequest(UUID sessionIndex, AuthorizeRequest request) {
//
// System.out.println(request);
// // ... handle event
// IdTagInfo idTagInfo = new IdTagInfo();
// idTagInfo.setExpiryDate(ZonedDateTime.now());
// idTagInfo.setParentIdTag("test");
// idTagInfo.setStatus(AuthorizationStatus.Accepted);
//
// return new AuthorizeConfirmation(idTagInfo);
// }
//
// @Override
// public BootNotificationConfirmation handleBootNotificationRequest(UUID sessionIndex, BootNotificationRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public DataTransferConfirmation handleDataTransferRequest(UUID sessionIndex, DataTransferRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public HeartbeatConfirmation handleHeartbeatRequest(UUID sessionIndex, HeartbeatRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public MeterValuesConfirmation handleMeterValuesRequest(UUID sessionIndex, MeterValuesRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StartTransactionConfirmation handleStartTransactionRequest(UUID sessionIndex, StartTransactionRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StatusNotificationConfirmation handleStatusNotificationRequest(UUID sessionIndex, StatusNotificationRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StopTransactionConfirmation handleStopTransactionRequest(UUID sessionIndex, StopTransactionRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
// };
// }
//
// @Bean
// public ServerCoreProfile createCore(ServerCoreEventHandler serverCoreEventHandler) {
// return new ServerCoreProfile(serverCoreEventHandler);
// }
// }
//
// Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerEventConfig.java
// @TestConfiguration
// @Getter
// @Slf4j
// public class TestServerEventConfig {
//
// @Bean
// public ServerEvents createServerCoreImpl() {
// return getNewServerEventsImpl();
// }
//
// private ServerEvents getNewServerEventsImpl() {
// return new ServerEvents() {
//
// @Override
// public void newSession(UUID sessionIndex, SessionInformation information) {
//
// // sessionIndex is used to send messages.
// System.out.println("New session " + sessionIndex + ": " + information.getIdentifier());
// }
//
// @Override
// public void lostSession(UUID sessionIndex) {
//
// System.out.println("Session " + sessionIndex + " lost connection");
// }
// };
// }
// }
// Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/handler/AuthorizeHandlerTest.java
import eu.chargetime.ocpp.feature.profile.ServerCoreEventHandler;
import eu.chargetime.ocpp.jsonserverimplementation.config.TestServerCoreProfileConfig;
import eu.chargetime.ocpp.jsonserverimplementation.config.TestServerEventConfig;
import eu.chargetime.ocpp.model.core.AuthorizationStatus;
import eu.chargetime.ocpp.model.core.AuthorizeConfirmation;
import eu.chargetime.ocpp.model.core.AuthorizeRequest;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
package eu.chargetime.ocpp.jsonserverimplementation.handler;
@RunWith(SpringRunner.class)
@Slf4j | @Import({TestServerCoreProfileConfig.class, TestServerEventConfig.class}) |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/handler/AuthorizeHandlerTest.java | // Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerCoreProfileConfig.java
// @TestConfiguration
// @Getter
// @Slf4j
// public class TestServerCoreProfileConfig {
//
// @Bean
// public ServerCoreEventHandler getCoreEventHandler() {
// return new ServerCoreEventHandler() {
// @Override
// public AuthorizeConfirmation handleAuthorizeRequest(UUID sessionIndex, AuthorizeRequest request) {
//
// System.out.println(request);
// // ... handle event
// IdTagInfo idTagInfo = new IdTagInfo();
// idTagInfo.setExpiryDate(ZonedDateTime.now());
// idTagInfo.setParentIdTag("test");
// idTagInfo.setStatus(AuthorizationStatus.Accepted);
//
// return new AuthorizeConfirmation(idTagInfo);
// }
//
// @Override
// public BootNotificationConfirmation handleBootNotificationRequest(UUID sessionIndex, BootNotificationRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public DataTransferConfirmation handleDataTransferRequest(UUID sessionIndex, DataTransferRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public HeartbeatConfirmation handleHeartbeatRequest(UUID sessionIndex, HeartbeatRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public MeterValuesConfirmation handleMeterValuesRequest(UUID sessionIndex, MeterValuesRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StartTransactionConfirmation handleStartTransactionRequest(UUID sessionIndex, StartTransactionRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StatusNotificationConfirmation handleStatusNotificationRequest(UUID sessionIndex, StatusNotificationRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StopTransactionConfirmation handleStopTransactionRequest(UUID sessionIndex, StopTransactionRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
// };
// }
//
// @Bean
// public ServerCoreProfile createCore(ServerCoreEventHandler serverCoreEventHandler) {
// return new ServerCoreProfile(serverCoreEventHandler);
// }
// }
//
// Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerEventConfig.java
// @TestConfiguration
// @Getter
// @Slf4j
// public class TestServerEventConfig {
//
// @Bean
// public ServerEvents createServerCoreImpl() {
// return getNewServerEventsImpl();
// }
//
// private ServerEvents getNewServerEventsImpl() {
// return new ServerEvents() {
//
// @Override
// public void newSession(UUID sessionIndex, SessionInformation information) {
//
// // sessionIndex is used to send messages.
// System.out.println("New session " + sessionIndex + ": " + information.getIdentifier());
// }
//
// @Override
// public void lostSession(UUID sessionIndex) {
//
// System.out.println("Session " + sessionIndex + " lost connection");
// }
// };
// }
// }
| import eu.chargetime.ocpp.feature.profile.ServerCoreEventHandler;
import eu.chargetime.ocpp.jsonserverimplementation.config.TestServerCoreProfileConfig;
import eu.chargetime.ocpp.jsonserverimplementation.config.TestServerEventConfig;
import eu.chargetime.ocpp.model.core.AuthorizationStatus;
import eu.chargetime.ocpp.model.core.AuthorizeConfirmation;
import eu.chargetime.ocpp.model.core.AuthorizeRequest;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals; | package eu.chargetime.ocpp.jsonserverimplementation.handler;
@RunWith(SpringRunner.class)
@Slf4j | // Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerCoreProfileConfig.java
// @TestConfiguration
// @Getter
// @Slf4j
// public class TestServerCoreProfileConfig {
//
// @Bean
// public ServerCoreEventHandler getCoreEventHandler() {
// return new ServerCoreEventHandler() {
// @Override
// public AuthorizeConfirmation handleAuthorizeRequest(UUID sessionIndex, AuthorizeRequest request) {
//
// System.out.println(request);
// // ... handle event
// IdTagInfo idTagInfo = new IdTagInfo();
// idTagInfo.setExpiryDate(ZonedDateTime.now());
// idTagInfo.setParentIdTag("test");
// idTagInfo.setStatus(AuthorizationStatus.Accepted);
//
// return new AuthorizeConfirmation(idTagInfo);
// }
//
// @Override
// public BootNotificationConfirmation handleBootNotificationRequest(UUID sessionIndex, BootNotificationRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public DataTransferConfirmation handleDataTransferRequest(UUID sessionIndex, DataTransferRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public HeartbeatConfirmation handleHeartbeatRequest(UUID sessionIndex, HeartbeatRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public MeterValuesConfirmation handleMeterValuesRequest(UUID sessionIndex, MeterValuesRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StartTransactionConfirmation handleStartTransactionRequest(UUID sessionIndex, StartTransactionRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StatusNotificationConfirmation handleStatusNotificationRequest(UUID sessionIndex, StatusNotificationRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
//
// @Override
// public StopTransactionConfirmation handleStopTransactionRequest(UUID sessionIndex, StopTransactionRequest request) {
//
// System.out.println(request);
// // ... handle event
//
// return null; // returning null means unsupported feature
// }
// };
// }
//
// @Bean
// public ServerCoreProfile createCore(ServerCoreEventHandler serverCoreEventHandler) {
// return new ServerCoreProfile(serverCoreEventHandler);
// }
// }
//
// Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerEventConfig.java
// @TestConfiguration
// @Getter
// @Slf4j
// public class TestServerEventConfig {
//
// @Bean
// public ServerEvents createServerCoreImpl() {
// return getNewServerEventsImpl();
// }
//
// private ServerEvents getNewServerEventsImpl() {
// return new ServerEvents() {
//
// @Override
// public void newSession(UUID sessionIndex, SessionInformation information) {
//
// // sessionIndex is used to send messages.
// System.out.println("New session " + sessionIndex + ": " + information.getIdentifier());
// }
//
// @Override
// public void lostSession(UUID sessionIndex) {
//
// System.out.println("Session " + sessionIndex + " lost connection");
// }
// };
// }
// }
// Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/handler/AuthorizeHandlerTest.java
import eu.chargetime.ocpp.feature.profile.ServerCoreEventHandler;
import eu.chargetime.ocpp.jsonserverimplementation.config.TestServerCoreProfileConfig;
import eu.chargetime.ocpp.jsonserverimplementation.config.TestServerEventConfig;
import eu.chargetime.ocpp.model.core.AuthorizationStatus;
import eu.chargetime.ocpp.model.core.AuthorizeConfirmation;
import eu.chargetime.ocpp.model.core.AuthorizeRequest;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
package eu.chargetime.ocpp.jsonserverimplementation.handler;
@RunWith(SpringRunner.class)
@Slf4j | @Import({TestServerCoreProfileConfig.class, TestServerEventConfig.class}) |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6/src/test/java/eu/chargetime/ocpp/feature/profile/test/ServerRemoteTriggerProfileTest.java | // Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerRemoteTriggerProfile.java
// public class ServerRemoteTriggerProfile implements Profile {
//
// private HashSet<Feature> features;
//
// public ServerRemoteTriggerProfile() {
//
// features = new HashSet<>();
// features.add(new TriggerMessageFeature(this));
// }
//
// @Override
// public ProfileFeature[] getFeatureList() {
// return features.toArray(new ProfileFeature[0]);
// }
//
// @Override
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// return null;
// }
//
// /**
// * Create a client {@link TriggerMessageRequest} with required values.
// *
// * @param triggerMessageRequestType {@link TriggerMessageRequestType}
// * @return an instance of {@link TriggerMessageRequest}
// * @see TriggerMessageRequest
// * @see TriggerMessageFeature
// */
// public TriggerMessageRequest createTriggerMessageRequest(
// TriggerMessageRequestType triggerMessageRequestType) {
// return createTriggerMessageRequest(triggerMessageRequestType, null);
// }
//
// /**
// * Create a client {@link TriggerMessageRequest} with required values.
// *
// * @param triggerMessageRequestType {@link TriggerMessageRequestType}
// * @param connectorId integer. value > 0
// * @return an instance of {@link TriggerMessageRequest}
// * @see TriggerMessageRequest
// * @see TriggerMessageFeature
// */
// public TriggerMessageRequest createTriggerMessageRequest(
// TriggerMessageRequestType triggerMessageRequestType, Integer connectorId) {
// TriggerMessageRequest request = new TriggerMessageRequest(triggerMessageRequestType);
// request.setConnectorId(connectorId);
// return request;
// }
// }
| import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.feature.TriggerMessageFeature;
import eu.chargetime.ocpp.feature.profile.ServerRemoteTriggerProfile;
import eu.chargetime.ocpp.model.remotetrigger.TriggerMessageRequest;
import eu.chargetime.ocpp.model.remotetrigger.TriggerMessageRequestType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner; | package eu.chargetime.ocpp.feature.profile.test;
/*
* ChargeTime.eu - Java-OCA-OCPP
*
* MIT License
*
* Copyright (C) 2017 Emil Christopher Solli Melar <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@RunWith(MockitoJUnitRunner.class)
public class ServerRemoteTriggerProfileTest extends ProfileTest {
| // Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerRemoteTriggerProfile.java
// public class ServerRemoteTriggerProfile implements Profile {
//
// private HashSet<Feature> features;
//
// public ServerRemoteTriggerProfile() {
//
// features = new HashSet<>();
// features.add(new TriggerMessageFeature(this));
// }
//
// @Override
// public ProfileFeature[] getFeatureList() {
// return features.toArray(new ProfileFeature[0]);
// }
//
// @Override
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// return null;
// }
//
// /**
// * Create a client {@link TriggerMessageRequest} with required values.
// *
// * @param triggerMessageRequestType {@link TriggerMessageRequestType}
// * @return an instance of {@link TriggerMessageRequest}
// * @see TriggerMessageRequest
// * @see TriggerMessageFeature
// */
// public TriggerMessageRequest createTriggerMessageRequest(
// TriggerMessageRequestType triggerMessageRequestType) {
// return createTriggerMessageRequest(triggerMessageRequestType, null);
// }
//
// /**
// * Create a client {@link TriggerMessageRequest} with required values.
// *
// * @param triggerMessageRequestType {@link TriggerMessageRequestType}
// * @param connectorId integer. value > 0
// * @return an instance of {@link TriggerMessageRequest}
// * @see TriggerMessageRequest
// * @see TriggerMessageFeature
// */
// public TriggerMessageRequest createTriggerMessageRequest(
// TriggerMessageRequestType triggerMessageRequestType, Integer connectorId) {
// TriggerMessageRequest request = new TriggerMessageRequest(triggerMessageRequestType);
// request.setConnectorId(connectorId);
// return request;
// }
// }
// Path: ocpp-v1_6/src/test/java/eu/chargetime/ocpp/feature/profile/test/ServerRemoteTriggerProfileTest.java
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.feature.TriggerMessageFeature;
import eu.chargetime.ocpp.feature.profile.ServerRemoteTriggerProfile;
import eu.chargetime.ocpp.model.remotetrigger.TriggerMessageRequest;
import eu.chargetime.ocpp.model.remotetrigger.TriggerMessageRequestType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
package eu.chargetime.ocpp.feature.profile.test;
/*
* ChargeTime.eu - Java-OCA-OCPP
*
* MIT License
*
* Copyright (C) 2017 Emil Christopher Solli Melar <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@RunWith(MockitoJUnitRunner.class)
public class ServerRemoteTriggerProfileTest extends ProfileTest {
| private ServerRemoteTriggerProfile profile; |
ChargeTimeEU/Java-OCA-OCPP | OCPP-J/src/main/java/eu/chargetime/ocpp/JSONCommunicator.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/Message.java
// public class Message {
// private String id;
// private Object payload;
// private String action;
//
// /**
// * Get unique id for message.
// *
// * @return message id.
// */
// public String getId() {
// return id;
// }
//
// /**
// * Set unique id for message.
// *
// * @param id String, message id.
// */
// public void setId(String id) {
// this.id = id;
// }
//
// /**
// * Get attached payload.
// *
// * @return payload.
// */
// public Object getPayload() {
// return payload;
// }
//
// /**
// * Attach payload to message.
// *
// * @param payload payload object.
// */
// public void setPayload(Object payload) {
// this.payload = payload;
// }
//
// /**
// * Get the action.
// *
// * @return String, action.
// */
// public String getAction() {
// return action;
// }
//
// /**
// * Set the action.
// *
// * @param action String, action.
// */
// public void setAction(String action) {
// this.action = action;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("id", id)
// .add("payload", payload)
// .add("action", action)
// .toString();
// }
// }
| import com.google.gson.*;
import eu.chargetime.ocpp.model.CallErrorMessage;
import eu.chargetime.ocpp.model.CallMessage;
import eu.chargetime.ocpp.model.CallResultMessage;
import eu.chargetime.ocpp.model.Message;
import java.lang.reflect.Type;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | gson = builder.create();
}
@Override
public <T> T unpackPayload(Object payload, Class<T> type) throws Exception {
return gson.fromJson(payload.toString(), type);
}
@Override
public Object packPayload(Object payload) {
return gson.toJson(payload);
}
@Override
protected Object makeCallResult(String uniqueId, String action, Object payload) {
return String.format(CALLRESULT_FORMAT, uniqueId, payload);
}
@Override
protected Object makeCall(String uniqueId, String action, Object payload) {
return String.format(CALL_FORMAT, uniqueId, action, payload);
}
@Override
protected Object makeCallError(
String uniqueId, String action, String errorCode, String errorDescription) {
return String.format(CALLERROR_FORMAT, uniqueId, errorCode, errorDescription, "{}");
}
@Override | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/Message.java
// public class Message {
// private String id;
// private Object payload;
// private String action;
//
// /**
// * Get unique id for message.
// *
// * @return message id.
// */
// public String getId() {
// return id;
// }
//
// /**
// * Set unique id for message.
// *
// * @param id String, message id.
// */
// public void setId(String id) {
// this.id = id;
// }
//
// /**
// * Get attached payload.
// *
// * @return payload.
// */
// public Object getPayload() {
// return payload;
// }
//
// /**
// * Attach payload to message.
// *
// * @param payload payload object.
// */
// public void setPayload(Object payload) {
// this.payload = payload;
// }
//
// /**
// * Get the action.
// *
// * @return String, action.
// */
// public String getAction() {
// return action;
// }
//
// /**
// * Set the action.
// *
// * @param action String, action.
// */
// public void setAction(String action) {
// this.action = action;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("id", id)
// .add("payload", payload)
// .add("action", action)
// .toString();
// }
// }
// Path: OCPP-J/src/main/java/eu/chargetime/ocpp/JSONCommunicator.java
import com.google.gson.*;
import eu.chargetime.ocpp.model.CallErrorMessage;
import eu.chargetime.ocpp.model.CallMessage;
import eu.chargetime.ocpp.model.CallResultMessage;
import eu.chargetime.ocpp.model.Message;
import java.lang.reflect.Type;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
gson = builder.create();
}
@Override
public <T> T unpackPayload(Object payload, Class<T> type) throws Exception {
return gson.fromJson(payload.toString(), type);
}
@Override
public Object packPayload(Object payload) {
return gson.toJson(payload);
}
@Override
protected Object makeCallResult(String uniqueId, String action, Object payload) {
return String.format(CALLRESULT_FORMAT, uniqueId, payload);
}
@Override
protected Object makeCall(String uniqueId, String action, Object payload) {
return String.format(CALL_FORMAT, uniqueId, action, payload);
}
@Override
protected Object makeCallError(
String uniqueId, String action, String errorCode, String errorDescription) {
return String.format(CALLERROR_FORMAT, uniqueId, errorCode, errorDescription, "{}");
}
@Override | protected Message parse(Object json) { |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerEventConfig.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
| import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.model.SessionInformation;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import java.util.UUID; | package eu.chargetime.ocpp.jsonserverimplementation.config;
@TestConfiguration
@Getter
@Slf4j
public class TestServerEventConfig {
@Bean | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
// Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerEventConfig.java
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.model.SessionInformation;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import java.util.UUID;
package eu.chargetime.ocpp.jsonserverimplementation.config;
@TestConfiguration
@Getter
@Slf4j
public class TestServerEventConfig {
@Bean | public ServerEvents createServerCoreImpl() { |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerEventConfig.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
| import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.model.SessionInformation;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import java.util.UUID; | package eu.chargetime.ocpp.jsonserverimplementation.config;
@TestConfiguration
@Getter
@Slf4j
public class TestServerEventConfig {
@Bean
public ServerEvents createServerCoreImpl() {
return getNewServerEventsImpl();
}
private ServerEvents getNewServerEventsImpl() {
return new ServerEvents() {
@Override | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
// Path: ocpp-v1_6-example/json_server_example/src/test/java/eu/chargetime/ocpp/jsonserverimplementation/config/TestServerEventConfig.java
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.model.SessionInformation;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import java.util.UUID;
package eu.chargetime.ocpp.jsonserverimplementation.config;
@TestConfiguration
@Getter
@Slf4j
public class TestServerEventConfig {
@Bean
public ServerEvents createServerCoreImpl() {
return getNewServerEventsImpl();
}
private ServerEvents getNewServerEventsImpl() {
return new ServerEvents() {
@Override | public void newSession(UUID sessionIndex, SessionInformation information) { |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6/src/test/java/eu/chargetime/ocpp/feature/profile/test/ServerFirmwareManagementProfileTest.java | // Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerFirmwareManagementEventHandler.java
// public interface ServerFirmwareManagementEventHandler {
// DiagnosticsStatusNotificationConfirmation handleDiagnosticsStatusNotificationRequest(
// UUID sessionIndex, DiagnosticsStatusNotificationRequest request);
//
// FirmwareStatusNotificationConfirmation handleFirmwareStatusNotificationRequest(
// UUID sessionIndex, FirmwareStatusNotificationRequest request);
// }
//
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerFirmwareManagementProfile.java
// public class ServerFirmwareManagementProfile implements Profile {
//
// private final ServerFirmwareManagementEventHandler eventHandler;
// private HashSet<Feature> features;
//
// public ServerFirmwareManagementProfile(ServerFirmwareManagementEventHandler eventHandler) {
// this.eventHandler = eventHandler;
// features = new HashSet<>();
// features.add(new DiagnosticsStatusNotificationFeature(this));
// features.add(new FirmwareStatusNotificationFeature(this));
// }
//
// @Override
// public ProfileFeature[] getFeatureList() {
// return features.toArray(new ProfileFeature[0]);
// }
//
// @Override
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// Confirmation result = null;
//
// if (request instanceof DiagnosticsStatusNotificationRequest) {
// result =
// eventHandler.handleDiagnosticsStatusNotificationRequest(
// sessionIndex, (DiagnosticsStatusNotificationRequest) request);
// } else if (request instanceof FirmwareStatusNotificationRequest) {
// result =
// eventHandler.handleFirmwareStatusNotificationRequest(
// sessionIndex, (FirmwareStatusNotificationRequest) request);
// }
//
// return result;
// }
//
// /**
// * Create a client {@link GetDiagnosticsRequest} with required values.
// *
// * @param location String, the destination folder
// * @return an instance of {@link GetDiagnosticsRequest}
// * @see GetDiagnosticsRequest
// * @see GetDiagnosticsFeature
// */
// public GetDiagnosticsRequest createGetDiagnosticsRequest(String location) {
// return new GetDiagnosticsRequest(location);
// }
//
// /**
// * Create a client {@link UpdateFirmwareRequest} with required values.
// *
// * @param location String, a URI with the firmware * @param retrieveDate ZonedDateTime, date and
// * time of retrieving
// * @return an instance of {@link UpdateFirmwareRequest}
// * @see UpdateFirmwareRequest
// * @see UpdateFirmwareFeature
// */
// public UpdateFirmwareRequest createUpdateFirmwareRequest(
// String location, ZonedDateTime retrieveDate) {
// return new UpdateFirmwareRequest(location, retrieveDate);
// }
// }
| import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import eu.chargetime.ocpp.feature.*;
import eu.chargetime.ocpp.feature.profile.ServerFirmwareManagementEventHandler;
import eu.chargetime.ocpp.feature.profile.ServerFirmwareManagementProfile;
import eu.chargetime.ocpp.model.firmware.DiagnosticsStatus;
import eu.chargetime.ocpp.model.firmware.DiagnosticsStatusNotificationRequest;
import eu.chargetime.ocpp.model.firmware.FirmwareStatus;
import eu.chargetime.ocpp.model.firmware.FirmwareStatusNotificationRequest;
import java.util.UUID;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; | package eu.chargetime.ocpp.feature.profile.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
@RunWith(MockitoJUnitRunner.class)
public class ServerFirmwareManagementProfileTest extends ProfileTest { | // Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerFirmwareManagementEventHandler.java
// public interface ServerFirmwareManagementEventHandler {
// DiagnosticsStatusNotificationConfirmation handleDiagnosticsStatusNotificationRequest(
// UUID sessionIndex, DiagnosticsStatusNotificationRequest request);
//
// FirmwareStatusNotificationConfirmation handleFirmwareStatusNotificationRequest(
// UUID sessionIndex, FirmwareStatusNotificationRequest request);
// }
//
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerFirmwareManagementProfile.java
// public class ServerFirmwareManagementProfile implements Profile {
//
// private final ServerFirmwareManagementEventHandler eventHandler;
// private HashSet<Feature> features;
//
// public ServerFirmwareManagementProfile(ServerFirmwareManagementEventHandler eventHandler) {
// this.eventHandler = eventHandler;
// features = new HashSet<>();
// features.add(new DiagnosticsStatusNotificationFeature(this));
// features.add(new FirmwareStatusNotificationFeature(this));
// }
//
// @Override
// public ProfileFeature[] getFeatureList() {
// return features.toArray(new ProfileFeature[0]);
// }
//
// @Override
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// Confirmation result = null;
//
// if (request instanceof DiagnosticsStatusNotificationRequest) {
// result =
// eventHandler.handleDiagnosticsStatusNotificationRequest(
// sessionIndex, (DiagnosticsStatusNotificationRequest) request);
// } else if (request instanceof FirmwareStatusNotificationRequest) {
// result =
// eventHandler.handleFirmwareStatusNotificationRequest(
// sessionIndex, (FirmwareStatusNotificationRequest) request);
// }
//
// return result;
// }
//
// /**
// * Create a client {@link GetDiagnosticsRequest} with required values.
// *
// * @param location String, the destination folder
// * @return an instance of {@link GetDiagnosticsRequest}
// * @see GetDiagnosticsRequest
// * @see GetDiagnosticsFeature
// */
// public GetDiagnosticsRequest createGetDiagnosticsRequest(String location) {
// return new GetDiagnosticsRequest(location);
// }
//
// /**
// * Create a client {@link UpdateFirmwareRequest} with required values.
// *
// * @param location String, a URI with the firmware * @param retrieveDate ZonedDateTime, date and
// * time of retrieving
// * @return an instance of {@link UpdateFirmwareRequest}
// * @see UpdateFirmwareRequest
// * @see UpdateFirmwareFeature
// */
// public UpdateFirmwareRequest createUpdateFirmwareRequest(
// String location, ZonedDateTime retrieveDate) {
// return new UpdateFirmwareRequest(location, retrieveDate);
// }
// }
// Path: ocpp-v1_6/src/test/java/eu/chargetime/ocpp/feature/profile/test/ServerFirmwareManagementProfileTest.java
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import eu.chargetime.ocpp.feature.*;
import eu.chargetime.ocpp.feature.profile.ServerFirmwareManagementEventHandler;
import eu.chargetime.ocpp.feature.profile.ServerFirmwareManagementProfile;
import eu.chargetime.ocpp.model.firmware.DiagnosticsStatus;
import eu.chargetime.ocpp.model.firmware.DiagnosticsStatusNotificationRequest;
import eu.chargetime.ocpp.model.firmware.FirmwareStatus;
import eu.chargetime.ocpp.model.firmware.FirmwareStatusNotificationRequest;
import java.util.UUID;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
package eu.chargetime.ocpp.feature.profile.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
@RunWith(MockitoJUnitRunner.class)
public class ServerFirmwareManagementProfileTest extends ProfileTest { | ServerFirmwareManagementProfile profile; |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6/src/test/java/eu/chargetime/ocpp/feature/profile/test/ServerFirmwareManagementProfileTest.java | // Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerFirmwareManagementEventHandler.java
// public interface ServerFirmwareManagementEventHandler {
// DiagnosticsStatusNotificationConfirmation handleDiagnosticsStatusNotificationRequest(
// UUID sessionIndex, DiagnosticsStatusNotificationRequest request);
//
// FirmwareStatusNotificationConfirmation handleFirmwareStatusNotificationRequest(
// UUID sessionIndex, FirmwareStatusNotificationRequest request);
// }
//
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerFirmwareManagementProfile.java
// public class ServerFirmwareManagementProfile implements Profile {
//
// private final ServerFirmwareManagementEventHandler eventHandler;
// private HashSet<Feature> features;
//
// public ServerFirmwareManagementProfile(ServerFirmwareManagementEventHandler eventHandler) {
// this.eventHandler = eventHandler;
// features = new HashSet<>();
// features.add(new DiagnosticsStatusNotificationFeature(this));
// features.add(new FirmwareStatusNotificationFeature(this));
// }
//
// @Override
// public ProfileFeature[] getFeatureList() {
// return features.toArray(new ProfileFeature[0]);
// }
//
// @Override
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// Confirmation result = null;
//
// if (request instanceof DiagnosticsStatusNotificationRequest) {
// result =
// eventHandler.handleDiagnosticsStatusNotificationRequest(
// sessionIndex, (DiagnosticsStatusNotificationRequest) request);
// } else if (request instanceof FirmwareStatusNotificationRequest) {
// result =
// eventHandler.handleFirmwareStatusNotificationRequest(
// sessionIndex, (FirmwareStatusNotificationRequest) request);
// }
//
// return result;
// }
//
// /**
// * Create a client {@link GetDiagnosticsRequest} with required values.
// *
// * @param location String, the destination folder
// * @return an instance of {@link GetDiagnosticsRequest}
// * @see GetDiagnosticsRequest
// * @see GetDiagnosticsFeature
// */
// public GetDiagnosticsRequest createGetDiagnosticsRequest(String location) {
// return new GetDiagnosticsRequest(location);
// }
//
// /**
// * Create a client {@link UpdateFirmwareRequest} with required values.
// *
// * @param location String, a URI with the firmware * @param retrieveDate ZonedDateTime, date and
// * time of retrieving
// * @return an instance of {@link UpdateFirmwareRequest}
// * @see UpdateFirmwareRequest
// * @see UpdateFirmwareFeature
// */
// public UpdateFirmwareRequest createUpdateFirmwareRequest(
// String location, ZonedDateTime retrieveDate) {
// return new UpdateFirmwareRequest(location, retrieveDate);
// }
// }
| import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import eu.chargetime.ocpp.feature.*;
import eu.chargetime.ocpp.feature.profile.ServerFirmwareManagementEventHandler;
import eu.chargetime.ocpp.feature.profile.ServerFirmwareManagementProfile;
import eu.chargetime.ocpp.model.firmware.DiagnosticsStatus;
import eu.chargetime.ocpp.model.firmware.DiagnosticsStatusNotificationRequest;
import eu.chargetime.ocpp.model.firmware.FirmwareStatus;
import eu.chargetime.ocpp.model.firmware.FirmwareStatusNotificationRequest;
import java.util.UUID;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; | package eu.chargetime.ocpp.feature.profile.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
@RunWith(MockitoJUnitRunner.class)
public class ServerFirmwareManagementProfileTest extends ProfileTest {
ServerFirmwareManagementProfile profile;
| // Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerFirmwareManagementEventHandler.java
// public interface ServerFirmwareManagementEventHandler {
// DiagnosticsStatusNotificationConfirmation handleDiagnosticsStatusNotificationRequest(
// UUID sessionIndex, DiagnosticsStatusNotificationRequest request);
//
// FirmwareStatusNotificationConfirmation handleFirmwareStatusNotificationRequest(
// UUID sessionIndex, FirmwareStatusNotificationRequest request);
// }
//
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerFirmwareManagementProfile.java
// public class ServerFirmwareManagementProfile implements Profile {
//
// private final ServerFirmwareManagementEventHandler eventHandler;
// private HashSet<Feature> features;
//
// public ServerFirmwareManagementProfile(ServerFirmwareManagementEventHandler eventHandler) {
// this.eventHandler = eventHandler;
// features = new HashSet<>();
// features.add(new DiagnosticsStatusNotificationFeature(this));
// features.add(new FirmwareStatusNotificationFeature(this));
// }
//
// @Override
// public ProfileFeature[] getFeatureList() {
// return features.toArray(new ProfileFeature[0]);
// }
//
// @Override
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// Confirmation result = null;
//
// if (request instanceof DiagnosticsStatusNotificationRequest) {
// result =
// eventHandler.handleDiagnosticsStatusNotificationRequest(
// sessionIndex, (DiagnosticsStatusNotificationRequest) request);
// } else if (request instanceof FirmwareStatusNotificationRequest) {
// result =
// eventHandler.handleFirmwareStatusNotificationRequest(
// sessionIndex, (FirmwareStatusNotificationRequest) request);
// }
//
// return result;
// }
//
// /**
// * Create a client {@link GetDiagnosticsRequest} with required values.
// *
// * @param location String, the destination folder
// * @return an instance of {@link GetDiagnosticsRequest}
// * @see GetDiagnosticsRequest
// * @see GetDiagnosticsFeature
// */
// public GetDiagnosticsRequest createGetDiagnosticsRequest(String location) {
// return new GetDiagnosticsRequest(location);
// }
//
// /**
// * Create a client {@link UpdateFirmwareRequest} with required values.
// *
// * @param location String, a URI with the firmware * @param retrieveDate ZonedDateTime, date and
// * time of retrieving
// * @return an instance of {@link UpdateFirmwareRequest}
// * @see UpdateFirmwareRequest
// * @see UpdateFirmwareFeature
// */
// public UpdateFirmwareRequest createUpdateFirmwareRequest(
// String location, ZonedDateTime retrieveDate) {
// return new UpdateFirmwareRequest(location, retrieveDate);
// }
// }
// Path: ocpp-v1_6/src/test/java/eu/chargetime/ocpp/feature/profile/test/ServerFirmwareManagementProfileTest.java
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import eu.chargetime.ocpp.feature.*;
import eu.chargetime.ocpp.feature.profile.ServerFirmwareManagementEventHandler;
import eu.chargetime.ocpp.feature.profile.ServerFirmwareManagementProfile;
import eu.chargetime.ocpp.model.firmware.DiagnosticsStatus;
import eu.chargetime.ocpp.model.firmware.DiagnosticsStatusNotificationRequest;
import eu.chargetime.ocpp.model.firmware.FirmwareStatus;
import eu.chargetime.ocpp.model.firmware.FirmwareStatusNotificationRequest;
import java.util.UUID;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
package eu.chargetime.ocpp.feature.profile.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
@RunWith(MockitoJUnitRunner.class)
public class ServerFirmwareManagementProfileTest extends ProfileTest {
ServerFirmwareManagementProfile profile;
| @Mock private ServerFirmwareManagementEventHandler handler; |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/config/ServerEventConfig.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
| import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.model.SessionInformation;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.UUID; | package eu.chargetime.ocpp.jsonserverimplementation.config;
@Configuration
@Getter
@Slf4j
public class ServerEventConfig {
@Bean | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
// Path: ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/config/ServerEventConfig.java
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.model.SessionInformation;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.UUID;
package eu.chargetime.ocpp.jsonserverimplementation.config;
@Configuration
@Getter
@Slf4j
public class ServerEventConfig {
@Bean | public ServerEvents createServerCoreImpl() { |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/config/ServerEventConfig.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
| import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.model.SessionInformation;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.UUID; | package eu.chargetime.ocpp.jsonserverimplementation.config;
@Configuration
@Getter
@Slf4j
public class ServerEventConfig {
@Bean
public ServerEvents createServerCoreImpl() {
return getNewServerEventsImpl();
}
private ServerEvents getNewServerEventsImpl() {
return new ServerEvents() {
@Override | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
// Path: ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/config/ServerEventConfig.java
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.model.SessionInformation;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.UUID;
package eu.chargetime.ocpp.jsonserverimplementation.config;
@Configuration
@Getter
@Slf4j
public class ServerEventConfig {
@Bean
public ServerEvents createServerCoreImpl() {
return getNewServerEventsImpl();
}
private ServerEvents getNewServerEventsImpl() {
return new ServerEvents() {
@Override | public void newSession(UUID sessionIndex, SessionInformation information) { |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerRemoteTriggerProfile.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/feature/ProfileFeature.java
// public abstract class ProfileFeature implements Feature {
//
// private Profile profile;
//
// /**
// * Creates link back to the {@link Profile}.
// *
// * @param ownerProfile the {@link Profile} that owns the function.
// */
// public ProfileFeature(Profile ownerProfile) {
// if (ownerProfile == null) {
// throw new IllegalArgumentException("need non-null profile");
// }
// profile = ownerProfile;
// }
//
// /**
// * Calls {@link Profile} to handle a {@link Request}.
// *
// * @param sessionIndex source of the request.
// * @param request the {@link Request} to be handled.
// * @return the {@link Confirmation} to be send back.
// */
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// return profile.handleRequest(sessionIndex, request);
// }
// }
| import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.feature.ProfileFeature;
import eu.chargetime.ocpp.feature.TriggerMessageFeature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.remotetrigger.TriggerMessageRequest;
import eu.chargetime.ocpp.model.remotetrigger.TriggerMessageRequestType;
import java.util.HashSet;
import java.util.UUID; | package eu.chargetime.ocpp.feature.profile;
/*
ChargeTime.eu - Java-OCA-OCPP
Copyright (C) 2017 Emil Christopher Solli Melar <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
MIT License
Copyright (C) 2017 Emil Christopher Solli Melar
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class ServerRemoteTriggerProfile implements Profile {
private HashSet<Feature> features;
public ServerRemoteTriggerProfile() {
features = new HashSet<>();
features.add(new TriggerMessageFeature(this));
}
@Override | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/feature/ProfileFeature.java
// public abstract class ProfileFeature implements Feature {
//
// private Profile profile;
//
// /**
// * Creates link back to the {@link Profile}.
// *
// * @param ownerProfile the {@link Profile} that owns the function.
// */
// public ProfileFeature(Profile ownerProfile) {
// if (ownerProfile == null) {
// throw new IllegalArgumentException("need non-null profile");
// }
// profile = ownerProfile;
// }
//
// /**
// * Calls {@link Profile} to handle a {@link Request}.
// *
// * @param sessionIndex source of the request.
// * @param request the {@link Request} to be handled.
// * @return the {@link Confirmation} to be send back.
// */
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// return profile.handleRequest(sessionIndex, request);
// }
// }
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerRemoteTriggerProfile.java
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.feature.ProfileFeature;
import eu.chargetime.ocpp.feature.TriggerMessageFeature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.remotetrigger.TriggerMessageRequest;
import eu.chargetime.ocpp.model.remotetrigger.TriggerMessageRequestType;
import java.util.HashSet;
import java.util.UUID;
package eu.chargetime.ocpp.feature.profile;
/*
ChargeTime.eu - Java-OCA-OCPP
Copyright (C) 2017 Emil Christopher Solli Melar <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
MIT License
Copyright (C) 2017 Emil Christopher Solli Melar
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class ServerRemoteTriggerProfile implements Profile {
private HashSet<Feature> features;
public ServerRemoteTriggerProfile() {
features = new HashSet<>();
features.add(new TriggerMessageFeature(this));
}
@Override | public ProfileFeature[] getFeatureList() { |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerLocalAuthListProfile.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/feature/ProfileFeature.java
// public abstract class ProfileFeature implements Feature {
//
// private Profile profile;
//
// /**
// * Creates link back to the {@link Profile}.
// *
// * @param ownerProfile the {@link Profile} that owns the function.
// */
// public ProfileFeature(Profile ownerProfile) {
// if (ownerProfile == null) {
// throw new IllegalArgumentException("need non-null profile");
// }
// profile = ownerProfile;
// }
//
// /**
// * Calls {@link Profile} to handle a {@link Request}.
// *
// * @param sessionIndex source of the request.
// * @param request the {@link Request} to be handled.
// * @return the {@link Confirmation} to be send back.
// */
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// return profile.handleRequest(sessionIndex, request);
// }
// }
//
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/SendLocalListFeature.java
// public class SendLocalListFeature extends ProfileFeature {
//
// public SendLocalListFeature(Profile ownerProfile) {
// super(ownerProfile);
// }
//
// @Override
// public Class<? extends Request> getRequestType() {
// return SendLocalListRequest.class;
// }
//
// @Override
// public Class<? extends Confirmation> getConfirmationType() {
// return SendLocalListConfirmation.class;
// }
//
// @Override
// public String getAction() {
// return "SendLocalList";
// }
// }
| import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.localauthlist.*;
import java.util.HashSet;
import java.util.UUID;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.feature.GetLocalListVersionFeature;
import eu.chargetime.ocpp.feature.ProfileFeature;
import eu.chargetime.ocpp.feature.SendLocalListFeature; | package eu.chargetime.ocpp.feature.profile;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class ServerLocalAuthListProfile implements Profile {
private HashSet<Feature> featureList;
public ServerLocalAuthListProfile() {
featureList = new HashSet<>();
featureList.add(new GetLocalListVersionFeature(this)); | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/feature/ProfileFeature.java
// public abstract class ProfileFeature implements Feature {
//
// private Profile profile;
//
// /**
// * Creates link back to the {@link Profile}.
// *
// * @param ownerProfile the {@link Profile} that owns the function.
// */
// public ProfileFeature(Profile ownerProfile) {
// if (ownerProfile == null) {
// throw new IllegalArgumentException("need non-null profile");
// }
// profile = ownerProfile;
// }
//
// /**
// * Calls {@link Profile} to handle a {@link Request}.
// *
// * @param sessionIndex source of the request.
// * @param request the {@link Request} to be handled.
// * @return the {@link Confirmation} to be send back.
// */
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// return profile.handleRequest(sessionIndex, request);
// }
// }
//
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/SendLocalListFeature.java
// public class SendLocalListFeature extends ProfileFeature {
//
// public SendLocalListFeature(Profile ownerProfile) {
// super(ownerProfile);
// }
//
// @Override
// public Class<? extends Request> getRequestType() {
// return SendLocalListRequest.class;
// }
//
// @Override
// public Class<? extends Confirmation> getConfirmationType() {
// return SendLocalListConfirmation.class;
// }
//
// @Override
// public String getAction() {
// return "SendLocalList";
// }
// }
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerLocalAuthListProfile.java
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.localauthlist.*;
import java.util.HashSet;
import java.util.UUID;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.feature.GetLocalListVersionFeature;
import eu.chargetime.ocpp.feature.ProfileFeature;
import eu.chargetime.ocpp.feature.SendLocalListFeature;
package eu.chargetime.ocpp.feature.profile;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class ServerLocalAuthListProfile implements Profile {
private HashSet<Feature> featureList;
public ServerLocalAuthListProfile() {
featureList = new HashSet<>();
featureList.add(new GetLocalListVersionFeature(this)); | featureList.add(new SendLocalListFeature(this)); |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerLocalAuthListProfile.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/feature/ProfileFeature.java
// public abstract class ProfileFeature implements Feature {
//
// private Profile profile;
//
// /**
// * Creates link back to the {@link Profile}.
// *
// * @param ownerProfile the {@link Profile} that owns the function.
// */
// public ProfileFeature(Profile ownerProfile) {
// if (ownerProfile == null) {
// throw new IllegalArgumentException("need non-null profile");
// }
// profile = ownerProfile;
// }
//
// /**
// * Calls {@link Profile} to handle a {@link Request}.
// *
// * @param sessionIndex source of the request.
// * @param request the {@link Request} to be handled.
// * @return the {@link Confirmation} to be send back.
// */
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// return profile.handleRequest(sessionIndex, request);
// }
// }
//
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/SendLocalListFeature.java
// public class SendLocalListFeature extends ProfileFeature {
//
// public SendLocalListFeature(Profile ownerProfile) {
// super(ownerProfile);
// }
//
// @Override
// public Class<? extends Request> getRequestType() {
// return SendLocalListRequest.class;
// }
//
// @Override
// public Class<? extends Confirmation> getConfirmationType() {
// return SendLocalListConfirmation.class;
// }
//
// @Override
// public String getAction() {
// return "SendLocalList";
// }
// }
| import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.localauthlist.*;
import java.util.HashSet;
import java.util.UUID;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.feature.GetLocalListVersionFeature;
import eu.chargetime.ocpp.feature.ProfileFeature;
import eu.chargetime.ocpp.feature.SendLocalListFeature; | package eu.chargetime.ocpp.feature.profile;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class ServerLocalAuthListProfile implements Profile {
private HashSet<Feature> featureList;
public ServerLocalAuthListProfile() {
featureList = new HashSet<>();
featureList.add(new GetLocalListVersionFeature(this));
featureList.add(new SendLocalListFeature(this));
}
@Override | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/feature/ProfileFeature.java
// public abstract class ProfileFeature implements Feature {
//
// private Profile profile;
//
// /**
// * Creates link back to the {@link Profile}.
// *
// * @param ownerProfile the {@link Profile} that owns the function.
// */
// public ProfileFeature(Profile ownerProfile) {
// if (ownerProfile == null) {
// throw new IllegalArgumentException("need non-null profile");
// }
// profile = ownerProfile;
// }
//
// /**
// * Calls {@link Profile} to handle a {@link Request}.
// *
// * @param sessionIndex source of the request.
// * @param request the {@link Request} to be handled.
// * @return the {@link Confirmation} to be send back.
// */
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// return profile.handleRequest(sessionIndex, request);
// }
// }
//
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/SendLocalListFeature.java
// public class SendLocalListFeature extends ProfileFeature {
//
// public SendLocalListFeature(Profile ownerProfile) {
// super(ownerProfile);
// }
//
// @Override
// public Class<? extends Request> getRequestType() {
// return SendLocalListRequest.class;
// }
//
// @Override
// public Class<? extends Confirmation> getConfirmationType() {
// return SendLocalListConfirmation.class;
// }
//
// @Override
// public String getAction() {
// return "SendLocalList";
// }
// }
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerLocalAuthListProfile.java
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.localauthlist.*;
import java.util.HashSet;
import java.util.UUID;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.feature.GetLocalListVersionFeature;
import eu.chargetime.ocpp.feature.ProfileFeature;
import eu.chargetime.ocpp.feature.SendLocalListFeature;
package eu.chargetime.ocpp.feature.profile;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class ServerLocalAuthListProfile implements Profile {
private HashSet<Feature> featureList;
public ServerLocalAuthListProfile() {
featureList = new HashSet<>();
featureList.add(new GetLocalListVersionFeature(this));
featureList.add(new SendLocalListFeature(this));
}
@Override | public ProfileFeature[] getFeatureList() { |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerReservationProfile.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/feature/ProfileFeature.java
// public abstract class ProfileFeature implements Feature {
//
// private Profile profile;
//
// /**
// * Creates link back to the {@link Profile}.
// *
// * @param ownerProfile the {@link Profile} that owns the function.
// */
// public ProfileFeature(Profile ownerProfile) {
// if (ownerProfile == null) {
// throw new IllegalArgumentException("need non-null profile");
// }
// profile = ownerProfile;
// }
//
// /**
// * Calls {@link Profile} to handle a {@link Request}.
// *
// * @param sessionIndex source of the request.
// * @param request the {@link Request} to be handled.
// * @return the {@link Confirmation} to be send back.
// */
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// return profile.handleRequest(sessionIndex, request);
// }
// }
| import eu.chargetime.ocpp.feature.ReserveNowFeature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.reservation.CancelReservationRequest;
import eu.chargetime.ocpp.model.reservation.ReserveNowRequest;
import java.time.ZonedDateTime;
import java.util.HashSet;
import java.util.UUID;
import eu.chargetime.ocpp.feature.CancelReservationFeature;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.feature.ProfileFeature; | package eu.chargetime.ocpp.feature.profile;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2018 Mikhail Kladkevich <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class ServerReservationProfile implements Profile {
private HashSet<Feature> features;
public ServerReservationProfile() {
features = new HashSet<>();
features.add(new ReserveNowFeature(this));
features.add(new CancelReservationFeature(this));
}
@Override | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/feature/ProfileFeature.java
// public abstract class ProfileFeature implements Feature {
//
// private Profile profile;
//
// /**
// * Creates link back to the {@link Profile}.
// *
// * @param ownerProfile the {@link Profile} that owns the function.
// */
// public ProfileFeature(Profile ownerProfile) {
// if (ownerProfile == null) {
// throw new IllegalArgumentException("need non-null profile");
// }
// profile = ownerProfile;
// }
//
// /**
// * Calls {@link Profile} to handle a {@link Request}.
// *
// * @param sessionIndex source of the request.
// * @param request the {@link Request} to be handled.
// * @return the {@link Confirmation} to be send back.
// */
// public Confirmation handleRequest(UUID sessionIndex, Request request) {
// return profile.handleRequest(sessionIndex, request);
// }
// }
// Path: ocpp-v1_6/src/main/java/eu/chargetime/ocpp/feature/profile/ServerReservationProfile.java
import eu.chargetime.ocpp.feature.ReserveNowFeature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.reservation.CancelReservationRequest;
import eu.chargetime.ocpp.model.reservation.ReserveNowRequest;
import java.time.ZonedDateTime;
import java.util.HashSet;
import java.util.UUID;
import eu.chargetime.ocpp.feature.CancelReservationFeature;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.feature.ProfileFeature;
package eu.chargetime.ocpp.feature.profile;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <[email protected]>
Copyright (C) 2018 Mikhail Kladkevich <[email protected]>
Copyright (C) 2019 Kevin Raddatz <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class ServerReservationProfile implements Profile {
private HashSet<Feature> features;
public ServerReservationProfile() {
features = new HashSet<>();
features.add(new ReserveNowFeature(this));
features.add(new CancelReservationFeature(this));
}
@Override | public ProfileFeature[] getFeatureList() { |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/server/JsonServerImpl.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/config/ApplicationConfiguration.java
// @Configuration
// @EnableConfigurationProperties
// @Getter
// public class ApplicationConfiguration {
//
// @Value("${server.port}")
// private Integer serverPort;
// }
| import eu.chargetime.ocpp.JSONServer;
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.jsonserverimplementation.config.ApplicationConfiguration;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct; | package eu.chargetime.ocpp.jsonserverimplementation.server;
@Slf4j
@Component
@AllArgsConstructor
public class JsonServerImpl {
| // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/config/ApplicationConfiguration.java
// @Configuration
// @EnableConfigurationProperties
// @Getter
// public class ApplicationConfiguration {
//
// @Value("${server.port}")
// private Integer serverPort;
// }
// Path: ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/server/JsonServerImpl.java
import eu.chargetime.ocpp.JSONServer;
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.jsonserverimplementation.config.ApplicationConfiguration;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
package eu.chargetime.ocpp.jsonserverimplementation.server;
@Slf4j
@Component
@AllArgsConstructor
public class JsonServerImpl {
| private final ServerEvents serverEvents; |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/server/JsonServerImpl.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/config/ApplicationConfiguration.java
// @Configuration
// @EnableConfigurationProperties
// @Getter
// public class ApplicationConfiguration {
//
// @Value("${server.port}")
// private Integer serverPort;
// }
| import eu.chargetime.ocpp.JSONServer;
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.jsonserverimplementation.config.ApplicationConfiguration;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct; | package eu.chargetime.ocpp.jsonserverimplementation.server;
@Slf4j
@Component
@AllArgsConstructor
public class JsonServerImpl {
private final ServerEvents serverEvents;
private final JSONServer server; | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/config/ApplicationConfiguration.java
// @Configuration
// @EnableConfigurationProperties
// @Getter
// public class ApplicationConfiguration {
//
// @Value("${server.port}")
// private Integer serverPort;
// }
// Path: ocpp-v1_6-example/json_server_example/src/main/java/eu/chargetime/ocpp/jsonserverimplementation/server/JsonServerImpl.java
import eu.chargetime.ocpp.JSONServer;
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.jsonserverimplementation.config.ApplicationConfiguration;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
package eu.chargetime.ocpp.jsonserverimplementation.server;
@Slf4j
@Component
@AllArgsConstructor
public class JsonServerImpl {
private final ServerEvents serverEvents;
private final JSONServer server; | private final ApplicationConfiguration applicationConfiguration; |
ChargeTimeEU/Java-OCA-OCPP | OCPP-J/src/main/java/eu/chargetime/ocpp/WebSocketListener.java | // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
| import eu.chargetime.ocpp.model.SessionInformation;
import eu.chargetime.ocpp.wss.WssFactoryBuilder;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.handshake.ServerHandshakeBuilder;
import org.java_websocket.server.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | clientHandshake.getResourceDescriptor());
WebSocketReceiver receiver =
new WebSocketReceiver(
new WebSocketReceiverEvents() {
@Override
public boolean isClosed() {
return closed;
}
@Override
public void close() {
webSocket.close();
}
@Override
public void relay(String message) {
webSocket.send(message);
}
});
sockets.put(webSocket, receiver);
String proxiedAddress = clientHandshake.getFieldValue(HTTP_HEADER_PROXIED_ADDRESS);
logger.debug(
"New web-socket connection opened from address: {} proxied for: {}",
webSocket.getRemoteSocketAddress(),
proxiedAddress);
| // Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
// Path: OCPP-J/src/main/java/eu/chargetime/ocpp/WebSocketListener.java
import eu.chargetime.ocpp.model.SessionInformation;
import eu.chargetime.ocpp.wss.WssFactoryBuilder;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.handshake.ServerHandshakeBuilder;
import org.java_websocket.server.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
clientHandshake.getResourceDescriptor());
WebSocketReceiver receiver =
new WebSocketReceiver(
new WebSocketReceiverEvents() {
@Override
public boolean isClosed() {
return closed;
}
@Override
public void close() {
webSocket.close();
}
@Override
public void relay(String message) {
webSocket.send(message);
}
});
sockets.put(webSocket, receiver);
String proxiedAddress = clientHandshake.getFieldValue(HTTP_HEADER_PROXIED_ADDRESS);
logger.debug(
"New web-socket connection opened from address: {} proxied for: {}",
webSocket.getRemoteSocketAddress(),
proxiedAddress);
| SessionInformation information = |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/StatusNotificationRequest.java | // Path: ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/types/ConnectorStatusEnumType.java
// public enum ConnectorStatusEnumType {
// Available,
// Occupied,
// Reserved,
// Unavailable,
// Faulted
// }
| import java.util.Objects;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.basic.types.ConnectorStatusEnumType;
import eu.chargetime.ocpp.model.validation.RequiredValidator;
import eu.chargetime.ocpp.utilities.MoreObjects;
import java.time.ZonedDateTime; | package eu.chargetime.ocpp.model.basic;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2021 John Michael Luy <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class StatusNotificationRequest implements Request {
private transient RequiredValidator validator = new RequiredValidator();
private ZonedDateTime timestamp;
| // Path: ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/types/ConnectorStatusEnumType.java
// public enum ConnectorStatusEnumType {
// Available,
// Occupied,
// Reserved,
// Unavailable,
// Faulted
// }
// Path: ocpp-v2_0/src/main/java/eu/chargetime/ocpp/model/basic/StatusNotificationRequest.java
import java.util.Objects;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.basic.types.ConnectorStatusEnumType;
import eu.chargetime.ocpp.model.validation.RequiredValidator;
import eu.chargetime.ocpp.utilities.MoreObjects;
import java.time.ZonedDateTime;
package eu.chargetime.ocpp.model.basic;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2021 John Michael Luy <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class StatusNotificationRequest implements Request {
private transient RequiredValidator validator = new RequiredValidator();
private ZonedDateTime timestamp;
| private ConnectorStatusEnumType connectorStatus; |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v2_0-test/src/main/java/eu/chargetime/ocpp/test/FakeCentralSystem.java | // Path: OCPP-J/src/main/java/eu/chargetime/ocpp/JSONConfiguration.java
// public class JSONConfiguration {
//
// public static final String TCP_NO_DELAY_PARAMETER = "TCP_NO_DELAY";
// public static final String REUSE_ADDR_PARAMETER = "REUSE_ADDR";
// public static final String PROXY_PARAMETER = "PROXY";
// public static final String PING_INTERVAL_PARAMETER = "PING_INTERVAL";
// public static final String USERNAME_PARAMETER = "USERNAME";
// public static final String PASSWORD_PARAMETER = "PASSWORD";
// public static final String CONNECT_TIMEOUT_IN_MS_PARAMETER = "CONNECT_TIMEOUT_IN_MS";
// public static final String WEBSOCKET_WORKER_COUNT = "WEBSOCKET_WORKER_COUNT";
//
// private final HashMap<String, Object> parameters = new HashMap<>();
//
// private JSONConfiguration() {}
//
// public static JSONConfiguration get() {
// return new JSONConfiguration();
// }
//
// public <T> JSONConfiguration setParameter(String name, T value) {
// parameters.put(name, value);
// return this;
// }
//
// public <T> T getParameter(String name) {
// //noinspection unchecked
// return (T) parameters.get(name);
// }
//
// public <T> T getParameter(String name, T defaultValue) {
// //noinspection unchecked
// T value = (T) parameters.get(name);
// return value != null ? value : defaultValue;
// }
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
| import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.UnsupportedFeatureException;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.SessionInformation;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.chargetime.ocpp.IServerAPI;
import eu.chargetime.ocpp.JSONConfiguration;
import eu.chargetime.ocpp.JSONServer;
import eu.chargetime.ocpp.NotConnectedException;
import eu.chargetime.ocpp.OccurenceConstraintException; | package eu.chargetime.ocpp.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2018 Thomas Volden <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class FakeCentralSystem {
private static final Logger logger = LoggerFactory.getLogger(FakeCentralSystem.class);
private final int port = 8887;
private final String host = "127.0.0.1";
private IServerAPI server;
private boolean isStarted;
private UUID currentSession;
private Request handlerRequest = null;
private Confirmation receivedConfirmation;
public FakeCentralSystem() { | // Path: OCPP-J/src/main/java/eu/chargetime/ocpp/JSONConfiguration.java
// public class JSONConfiguration {
//
// public static final String TCP_NO_DELAY_PARAMETER = "TCP_NO_DELAY";
// public static final String REUSE_ADDR_PARAMETER = "REUSE_ADDR";
// public static final String PROXY_PARAMETER = "PROXY";
// public static final String PING_INTERVAL_PARAMETER = "PING_INTERVAL";
// public static final String USERNAME_PARAMETER = "USERNAME";
// public static final String PASSWORD_PARAMETER = "PASSWORD";
// public static final String CONNECT_TIMEOUT_IN_MS_PARAMETER = "CONNECT_TIMEOUT_IN_MS";
// public static final String WEBSOCKET_WORKER_COUNT = "WEBSOCKET_WORKER_COUNT";
//
// private final HashMap<String, Object> parameters = new HashMap<>();
//
// private JSONConfiguration() {}
//
// public static JSONConfiguration get() {
// return new JSONConfiguration();
// }
//
// public <T> JSONConfiguration setParameter(String name, T value) {
// parameters.put(name, value);
// return this;
// }
//
// public <T> T getParameter(String name) {
// //noinspection unchecked
// return (T) parameters.get(name);
// }
//
// public <T> T getParameter(String name, T defaultValue) {
// //noinspection unchecked
// T value = (T) parameters.get(name);
// return value != null ? value : defaultValue;
// }
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
// Path: ocpp-v2_0-test/src/main/java/eu/chargetime/ocpp/test/FakeCentralSystem.java
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.UnsupportedFeatureException;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.SessionInformation;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.chargetime.ocpp.IServerAPI;
import eu.chargetime.ocpp.JSONConfiguration;
import eu.chargetime.ocpp.JSONServer;
import eu.chargetime.ocpp.NotConnectedException;
import eu.chargetime.ocpp.OccurenceConstraintException;
package eu.chargetime.ocpp.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2018 Thomas Volden <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class FakeCentralSystem {
private static final Logger logger = LoggerFactory.getLogger(FakeCentralSystem.class);
private final int port = 8887;
private final String host = "127.0.0.1";
private IServerAPI server;
private boolean isStarted;
private UUID currentSession;
private Request handlerRequest = null;
private Confirmation receivedConfirmation;
public FakeCentralSystem() { | JSONConfiguration configuration = |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v2_0-test/src/main/java/eu/chargetime/ocpp/test/FakeCentralSystem.java | // Path: OCPP-J/src/main/java/eu/chargetime/ocpp/JSONConfiguration.java
// public class JSONConfiguration {
//
// public static final String TCP_NO_DELAY_PARAMETER = "TCP_NO_DELAY";
// public static final String REUSE_ADDR_PARAMETER = "REUSE_ADDR";
// public static final String PROXY_PARAMETER = "PROXY";
// public static final String PING_INTERVAL_PARAMETER = "PING_INTERVAL";
// public static final String USERNAME_PARAMETER = "USERNAME";
// public static final String PASSWORD_PARAMETER = "PASSWORD";
// public static final String CONNECT_TIMEOUT_IN_MS_PARAMETER = "CONNECT_TIMEOUT_IN_MS";
// public static final String WEBSOCKET_WORKER_COUNT = "WEBSOCKET_WORKER_COUNT";
//
// private final HashMap<String, Object> parameters = new HashMap<>();
//
// private JSONConfiguration() {}
//
// public static JSONConfiguration get() {
// return new JSONConfiguration();
// }
//
// public <T> JSONConfiguration setParameter(String name, T value) {
// parameters.put(name, value);
// return this;
// }
//
// public <T> T getParameter(String name) {
// //noinspection unchecked
// return (T) parameters.get(name);
// }
//
// public <T> T getParameter(String name, T defaultValue) {
// //noinspection unchecked
// T value = (T) parameters.get(name);
// return value != null ? value : defaultValue;
// }
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
| import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.UnsupportedFeatureException;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.SessionInformation;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.chargetime.ocpp.IServerAPI;
import eu.chargetime.ocpp.JSONConfiguration;
import eu.chargetime.ocpp.JSONServer;
import eu.chargetime.ocpp.NotConnectedException;
import eu.chargetime.ocpp.OccurenceConstraintException; | package eu.chargetime.ocpp.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2018 Thomas Volden <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class FakeCentralSystem {
private static final Logger logger = LoggerFactory.getLogger(FakeCentralSystem.class);
private final int port = 8887;
private final String host = "127.0.0.1";
private IServerAPI server;
private boolean isStarted;
private UUID currentSession;
private Request handlerRequest = null;
private Confirmation receivedConfirmation;
public FakeCentralSystem() {
JSONConfiguration configuration =
JSONConfiguration.get().setParameter(JSONConfiguration.REUSE_ADDR_PARAMETER, true);
server = new JSONServer(configuration);
isStarted = false;
}
public void addFeature(Feature feature) {
FeatureTestDecorator monitoredFeature =
new FeatureTestDecorator(feature, request -> handlerRequest = request);
server.addFeature(monitoredFeature);
}
public void started() throws Exception {
if (!isStarted) {
server.open(
host,
port, | // Path: OCPP-J/src/main/java/eu/chargetime/ocpp/JSONConfiguration.java
// public class JSONConfiguration {
//
// public static final String TCP_NO_DELAY_PARAMETER = "TCP_NO_DELAY";
// public static final String REUSE_ADDR_PARAMETER = "REUSE_ADDR";
// public static final String PROXY_PARAMETER = "PROXY";
// public static final String PING_INTERVAL_PARAMETER = "PING_INTERVAL";
// public static final String USERNAME_PARAMETER = "USERNAME";
// public static final String PASSWORD_PARAMETER = "PASSWORD";
// public static final String CONNECT_TIMEOUT_IN_MS_PARAMETER = "CONNECT_TIMEOUT_IN_MS";
// public static final String WEBSOCKET_WORKER_COUNT = "WEBSOCKET_WORKER_COUNT";
//
// private final HashMap<String, Object> parameters = new HashMap<>();
//
// private JSONConfiguration() {}
//
// public static JSONConfiguration get() {
// return new JSONConfiguration();
// }
//
// public <T> JSONConfiguration setParameter(String name, T value) {
// parameters.put(name, value);
// return this;
// }
//
// public <T> T getParameter(String name) {
// //noinspection unchecked
// return (T) parameters.get(name);
// }
//
// public <T> T getParameter(String name, T defaultValue) {
// //noinspection unchecked
// T value = (T) parameters.get(name);
// return value != null ? value : defaultValue;
// }
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
// Path: ocpp-v2_0-test/src/main/java/eu/chargetime/ocpp/test/FakeCentralSystem.java
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.UnsupportedFeatureException;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.SessionInformation;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.chargetime.ocpp.IServerAPI;
import eu.chargetime.ocpp.JSONConfiguration;
import eu.chargetime.ocpp.JSONServer;
import eu.chargetime.ocpp.NotConnectedException;
import eu.chargetime.ocpp.OccurenceConstraintException;
package eu.chargetime.ocpp.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2018 Thomas Volden <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class FakeCentralSystem {
private static final Logger logger = LoggerFactory.getLogger(FakeCentralSystem.class);
private final int port = 8887;
private final String host = "127.0.0.1";
private IServerAPI server;
private boolean isStarted;
private UUID currentSession;
private Request handlerRequest = null;
private Confirmation receivedConfirmation;
public FakeCentralSystem() {
JSONConfiguration configuration =
JSONConfiguration.get().setParameter(JSONConfiguration.REUSE_ADDR_PARAMETER, true);
server = new JSONServer(configuration);
isStarted = false;
}
public void addFeature(Feature feature) {
FeatureTestDecorator monitoredFeature =
new FeatureTestDecorator(feature, request -> handlerRequest = request);
server.addFeature(monitoredFeature);
}
public void started() throws Exception {
if (!isStarted) {
server.open(
host,
port, | new ServerEvents() { |
ChargeTimeEU/Java-OCA-OCPP | ocpp-v2_0-test/src/main/java/eu/chargetime/ocpp/test/FakeCentralSystem.java | // Path: OCPP-J/src/main/java/eu/chargetime/ocpp/JSONConfiguration.java
// public class JSONConfiguration {
//
// public static final String TCP_NO_DELAY_PARAMETER = "TCP_NO_DELAY";
// public static final String REUSE_ADDR_PARAMETER = "REUSE_ADDR";
// public static final String PROXY_PARAMETER = "PROXY";
// public static final String PING_INTERVAL_PARAMETER = "PING_INTERVAL";
// public static final String USERNAME_PARAMETER = "USERNAME";
// public static final String PASSWORD_PARAMETER = "PASSWORD";
// public static final String CONNECT_TIMEOUT_IN_MS_PARAMETER = "CONNECT_TIMEOUT_IN_MS";
// public static final String WEBSOCKET_WORKER_COUNT = "WEBSOCKET_WORKER_COUNT";
//
// private final HashMap<String, Object> parameters = new HashMap<>();
//
// private JSONConfiguration() {}
//
// public static JSONConfiguration get() {
// return new JSONConfiguration();
// }
//
// public <T> JSONConfiguration setParameter(String name, T value) {
// parameters.put(name, value);
// return this;
// }
//
// public <T> T getParameter(String name) {
// //noinspection unchecked
// return (T) parameters.get(name);
// }
//
// public <T> T getParameter(String name, T defaultValue) {
// //noinspection unchecked
// T value = (T) parameters.get(name);
// return value != null ? value : defaultValue;
// }
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
| import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.UnsupportedFeatureException;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.SessionInformation;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.chargetime.ocpp.IServerAPI;
import eu.chargetime.ocpp.JSONConfiguration;
import eu.chargetime.ocpp.JSONServer;
import eu.chargetime.ocpp.NotConnectedException;
import eu.chargetime.ocpp.OccurenceConstraintException; | package eu.chargetime.ocpp.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2018 Thomas Volden <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class FakeCentralSystem {
private static final Logger logger = LoggerFactory.getLogger(FakeCentralSystem.class);
private final int port = 8887;
private final String host = "127.0.0.1";
private IServerAPI server;
private boolean isStarted;
private UUID currentSession;
private Request handlerRequest = null;
private Confirmation receivedConfirmation;
public FakeCentralSystem() {
JSONConfiguration configuration =
JSONConfiguration.get().setParameter(JSONConfiguration.REUSE_ADDR_PARAMETER, true);
server = new JSONServer(configuration);
isStarted = false;
}
public void addFeature(Feature feature) {
FeatureTestDecorator monitoredFeature =
new FeatureTestDecorator(feature, request -> handlerRequest = request);
server.addFeature(monitoredFeature);
}
public void started() throws Exception {
if (!isStarted) {
server.open(
host,
port,
new ServerEvents() {
@Override | // Path: OCPP-J/src/main/java/eu/chargetime/ocpp/JSONConfiguration.java
// public class JSONConfiguration {
//
// public static final String TCP_NO_DELAY_PARAMETER = "TCP_NO_DELAY";
// public static final String REUSE_ADDR_PARAMETER = "REUSE_ADDR";
// public static final String PROXY_PARAMETER = "PROXY";
// public static final String PING_INTERVAL_PARAMETER = "PING_INTERVAL";
// public static final String USERNAME_PARAMETER = "USERNAME";
// public static final String PASSWORD_PARAMETER = "PASSWORD";
// public static final String CONNECT_TIMEOUT_IN_MS_PARAMETER = "CONNECT_TIMEOUT_IN_MS";
// public static final String WEBSOCKET_WORKER_COUNT = "WEBSOCKET_WORKER_COUNT";
//
// private final HashMap<String, Object> parameters = new HashMap<>();
//
// private JSONConfiguration() {}
//
// public static JSONConfiguration get() {
// return new JSONConfiguration();
// }
//
// public <T> JSONConfiguration setParameter(String name, T value) {
// parameters.put(name, value);
// return this;
// }
//
// public <T> T getParameter(String name) {
// //noinspection unchecked
// return (T) parameters.get(name);
// }
//
// public <T> T getParameter(String name, T defaultValue) {
// //noinspection unchecked
// T value = (T) parameters.get(name);
// return value != null ? value : defaultValue;
// }
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/ServerEvents.java
// public interface ServerEvents {
// default void authenticateSession(SessionInformation information, String username, byte[] password)
// throws AuthenticationException {}
//
// void newSession(UUID sessionIndex, SessionInformation information);
//
// void lostSession(UUID sessionIndex);
// }
//
// Path: ocpp-common/src/main/java/eu/chargetime/ocpp/model/SessionInformation.java
// public class SessionInformation {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public String getIdentifier() {
// return identifier;
// }
//
// public InetSocketAddress getAddress() {
// return address;
// }
//
// public String getSOAPtoURL() {
// return SOAPtoURL;
// }
//
// public String getProxiedAddress() {
// return proxiedAddress;
// }
//
// public static class Builder {
//
// private String identifier;
// private InetSocketAddress address;
// private String SOAPtoURL;
// private String proxiedAddress;
//
// public Builder Identifier(String identifier) {
// this.identifier = identifier;
// return this;
// }
//
// public Builder InternetAddress(InetSocketAddress address) {
// this.address = address;
// return this;
// }
//
// public Builder ProxiedAddress(String proxiedAddress) {
// this.proxiedAddress = proxiedAddress;
// return this;
// }
//
// public SessionInformation build() {
// SessionInformation sessionInformation = new SessionInformation();
// sessionInformation.identifier = this.identifier;
// sessionInformation.address = this.address;
// sessionInformation.SOAPtoURL = this.SOAPtoURL;
// sessionInformation.proxiedAddress = this.proxiedAddress;
// return sessionInformation;
// }
//
// public Builder SOAPtoURL(String toUrl) {
// this.SOAPtoURL = toUrl;
// return this;
// }
// }
// }
// Path: ocpp-v2_0-test/src/main/java/eu/chargetime/ocpp/test/FakeCentralSystem.java
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.UnsupportedFeatureException;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.SessionInformation;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.chargetime.ocpp.IServerAPI;
import eu.chargetime.ocpp.JSONConfiguration;
import eu.chargetime.ocpp.JSONServer;
import eu.chargetime.ocpp.NotConnectedException;
import eu.chargetime.ocpp.OccurenceConstraintException;
package eu.chargetime.ocpp.test;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2018 Thomas Volden <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class FakeCentralSystem {
private static final Logger logger = LoggerFactory.getLogger(FakeCentralSystem.class);
private final int port = 8887;
private final String host = "127.0.0.1";
private IServerAPI server;
private boolean isStarted;
private UUID currentSession;
private Request handlerRequest = null;
private Confirmation receivedConfirmation;
public FakeCentralSystem() {
JSONConfiguration configuration =
JSONConfiguration.get().setParameter(JSONConfiguration.REUSE_ADDR_PARAMETER, true);
server = new JSONServer(configuration);
isStarted = false;
}
public void addFeature(Feature feature) {
FeatureTestDecorator monitoredFeature =
new FeatureTestDecorator(feature, request -> handlerRequest = request);
server.addFeature(monitoredFeature);
}
public void started() throws Exception {
if (!isStarted) {
server.open(
host,
port,
new ServerEvents() {
@Override | public void newSession(UUID sessionIndex, SessionInformation information) { |
monapu/monacoinj-multibit | examples/src/main/java/com/google/bitcoin/examples/RefreshWallet.java | // Path: core/src/main/java/com/google/bitcoin/params/TestNet3Params.java
// public class TestNet3Params extends NetworkParameters {
// public TestNet3Params() {
// super();
// id = ID_TESTNET;
// // Genesis hash is a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f
// packetMagic = 0xfcc1b7dc; // correspond to pchMessageStart in main.cpp
// interval = INTERVAL;
// digishieldInterval = DIGISHIELD_INTERVAL;
//
// //switchKGWBlock = 0;
// //switchDigishieldBlock = 300;
// switchKGWBlock = SWITCH_KGW_BLOCK;
// switchDigishieldBlock = SWITCH_DIGISHIELD_BLOCK;
// // switchDGWV3Block = SWITCH_DGW_V3_BLOCK;
// // switchAlgoLyra2ReV2 = SWITCH_ALGO_LYRA2_RE_V2;
// switchDGWV3Block = 5;
// switchAlgoLyra2ReV2 = 5;
//
// targetTimespan = TARGET_TIMESPAN;
// digishieldTargetTimespan = DIGISHIELD_TARGET_TIMESPAN;
// proofOfWorkLimit = Utils.decodeCompactBits(0x1e0fffffL);
// port = 19401;
// addressHeader = 111;
// p2shHeader = 196;
// acceptableAddressCodes = new int[] { addressHeader, p2shHeader };
// dumpedPrivateKeyHeader = 239;
// genesisBlock.setTime(1388479759L);
// genesisBlock.setDifficultyTarget(0x1e0ffff0L);
// genesisBlock.setNonce(600389L);
// spendableCoinbaseDepth = 100; // equivalent to COINBASE_MATURITY ?
// subsidyDecreaseBlockCount = 1051200;
//
// String genesisHash = genesisBlock.getHashAsString();
// // a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f
// checkState(genesisHash.equals("a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f"));
// alertSigningKey = Hex.decode("04887665070e79d20f722857e58ec8f402733f710135521a0b63441419bf5665ba4623bed13fca0cb2338682ab2a54ad13ce07fbc81c3c2f0912a4eb8521dd3cfb");
//
// dnsSeeds = new String[] {
// "test-dnsseed.monacoin.org",
// };
// }
//
// private static TestNet3Params instance;
// public static synchronized TestNet3Params get() {
// if (instance == null) {
// instance = new TestNet3Params();
// }
// return instance;
// }
//
// public String getPaymentProtocolId() {
// return PAYMENT_PROTOCOL_ID_TESTNET;
// }
// }
//
// Path: core/src/main/java/com/google/bitcoin/store/MemoryBlockStore.java
// public class MemoryBlockStore implements BlockStore {
// private LinkedHashMap<Sha256Hash, StoredBlock> blockMap = new LinkedHashMap<Sha256Hash, StoredBlock>() {
// @Override
// protected boolean removeEldestEntry(Map.Entry<Sha256Hash, StoredBlock> eldest) {
// return blockMap.size() > 60 * 60 * 24 * 7 / NetworkParameters.TARGET_SPACING + 1; // KGW past block max
// }
// };
// private StoredBlock chainHead;
//
// public MemoryBlockStore(NetworkParameters params) {
// // Insert the genesis block.
// try {
// Block genesisHeader = params.getGenesisBlock().cloneAsHeader();
// StoredBlock storedGenesis = new StoredBlock(genesisHeader, genesisHeader.getWork(), 0);
// put(storedGenesis);
// setChainHead(storedGenesis);
// } catch (BlockStoreException e) {
// throw new RuntimeException(e); // Cannot happen.
// } catch (VerificationException e) {
// throw new RuntimeException(e); // Cannot happen.
// }
// }
//
// public synchronized void put(StoredBlock block) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// Sha256Hash hash = block.getHeader().getHash();
// blockMap.put(hash, block);
// }
//
// public synchronized StoredBlock get(Sha256Hash hash) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// return blockMap.get(hash);
// }
//
// public StoredBlock getChainHead() throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// return chainHead;
// }
//
// public void setChainHead(StoredBlock chainHead) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// this.chainHead = chainHead;
// }
//
// public void close() {
// blockMap = null;
// }
// }
| import com.google.bitcoin.core.*;
import com.google.bitcoin.params.TestNet3Params;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.MemoryBlockStore;
import java.io.File;
import java.math.BigInteger;
import java.net.InetAddress; | /*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.examples;
/**
* RefreshWallet loads a wallet, then processes the block chain to update the transaction pools within it.
*/
public class RefreshWallet {
public static void main(String[] args) throws Exception {
File file = new File(args[0]);
Wallet wallet = Wallet.loadFromFile(file);
System.out.println(wallet.toString());
// Set up the components and link them together. | // Path: core/src/main/java/com/google/bitcoin/params/TestNet3Params.java
// public class TestNet3Params extends NetworkParameters {
// public TestNet3Params() {
// super();
// id = ID_TESTNET;
// // Genesis hash is a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f
// packetMagic = 0xfcc1b7dc; // correspond to pchMessageStart in main.cpp
// interval = INTERVAL;
// digishieldInterval = DIGISHIELD_INTERVAL;
//
// //switchKGWBlock = 0;
// //switchDigishieldBlock = 300;
// switchKGWBlock = SWITCH_KGW_BLOCK;
// switchDigishieldBlock = SWITCH_DIGISHIELD_BLOCK;
// // switchDGWV3Block = SWITCH_DGW_V3_BLOCK;
// // switchAlgoLyra2ReV2 = SWITCH_ALGO_LYRA2_RE_V2;
// switchDGWV3Block = 5;
// switchAlgoLyra2ReV2 = 5;
//
// targetTimespan = TARGET_TIMESPAN;
// digishieldTargetTimespan = DIGISHIELD_TARGET_TIMESPAN;
// proofOfWorkLimit = Utils.decodeCompactBits(0x1e0fffffL);
// port = 19401;
// addressHeader = 111;
// p2shHeader = 196;
// acceptableAddressCodes = new int[] { addressHeader, p2shHeader };
// dumpedPrivateKeyHeader = 239;
// genesisBlock.setTime(1388479759L);
// genesisBlock.setDifficultyTarget(0x1e0ffff0L);
// genesisBlock.setNonce(600389L);
// spendableCoinbaseDepth = 100; // equivalent to COINBASE_MATURITY ?
// subsidyDecreaseBlockCount = 1051200;
//
// String genesisHash = genesisBlock.getHashAsString();
// // a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f
// checkState(genesisHash.equals("a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f"));
// alertSigningKey = Hex.decode("04887665070e79d20f722857e58ec8f402733f710135521a0b63441419bf5665ba4623bed13fca0cb2338682ab2a54ad13ce07fbc81c3c2f0912a4eb8521dd3cfb");
//
// dnsSeeds = new String[] {
// "test-dnsseed.monacoin.org",
// };
// }
//
// private static TestNet3Params instance;
// public static synchronized TestNet3Params get() {
// if (instance == null) {
// instance = new TestNet3Params();
// }
// return instance;
// }
//
// public String getPaymentProtocolId() {
// return PAYMENT_PROTOCOL_ID_TESTNET;
// }
// }
//
// Path: core/src/main/java/com/google/bitcoin/store/MemoryBlockStore.java
// public class MemoryBlockStore implements BlockStore {
// private LinkedHashMap<Sha256Hash, StoredBlock> blockMap = new LinkedHashMap<Sha256Hash, StoredBlock>() {
// @Override
// protected boolean removeEldestEntry(Map.Entry<Sha256Hash, StoredBlock> eldest) {
// return blockMap.size() > 60 * 60 * 24 * 7 / NetworkParameters.TARGET_SPACING + 1; // KGW past block max
// }
// };
// private StoredBlock chainHead;
//
// public MemoryBlockStore(NetworkParameters params) {
// // Insert the genesis block.
// try {
// Block genesisHeader = params.getGenesisBlock().cloneAsHeader();
// StoredBlock storedGenesis = new StoredBlock(genesisHeader, genesisHeader.getWork(), 0);
// put(storedGenesis);
// setChainHead(storedGenesis);
// } catch (BlockStoreException e) {
// throw new RuntimeException(e); // Cannot happen.
// } catch (VerificationException e) {
// throw new RuntimeException(e); // Cannot happen.
// }
// }
//
// public synchronized void put(StoredBlock block) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// Sha256Hash hash = block.getHeader().getHash();
// blockMap.put(hash, block);
// }
//
// public synchronized StoredBlock get(Sha256Hash hash) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// return blockMap.get(hash);
// }
//
// public StoredBlock getChainHead() throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// return chainHead;
// }
//
// public void setChainHead(StoredBlock chainHead) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// this.chainHead = chainHead;
// }
//
// public void close() {
// blockMap = null;
// }
// }
// Path: examples/src/main/java/com/google/bitcoin/examples/RefreshWallet.java
import com.google.bitcoin.core.*;
import com.google.bitcoin.params.TestNet3Params;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.MemoryBlockStore;
import java.io.File;
import java.math.BigInteger;
import java.net.InetAddress;
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.examples;
/**
* RefreshWallet loads a wallet, then processes the block chain to update the transaction pools within it.
*/
public class RefreshWallet {
public static void main(String[] args) throws Exception {
File file = new File(args[0]);
Wallet wallet = Wallet.loadFromFile(file);
System.out.println(wallet.toString());
// Set up the components and link them together. | final NetworkParameters params = TestNet3Params.get(); |
monapu/monacoinj-multibit | examples/src/main/java/com/google/bitcoin/examples/RefreshWallet.java | // Path: core/src/main/java/com/google/bitcoin/params/TestNet3Params.java
// public class TestNet3Params extends NetworkParameters {
// public TestNet3Params() {
// super();
// id = ID_TESTNET;
// // Genesis hash is a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f
// packetMagic = 0xfcc1b7dc; // correspond to pchMessageStart in main.cpp
// interval = INTERVAL;
// digishieldInterval = DIGISHIELD_INTERVAL;
//
// //switchKGWBlock = 0;
// //switchDigishieldBlock = 300;
// switchKGWBlock = SWITCH_KGW_BLOCK;
// switchDigishieldBlock = SWITCH_DIGISHIELD_BLOCK;
// // switchDGWV3Block = SWITCH_DGW_V3_BLOCK;
// // switchAlgoLyra2ReV2 = SWITCH_ALGO_LYRA2_RE_V2;
// switchDGWV3Block = 5;
// switchAlgoLyra2ReV2 = 5;
//
// targetTimespan = TARGET_TIMESPAN;
// digishieldTargetTimespan = DIGISHIELD_TARGET_TIMESPAN;
// proofOfWorkLimit = Utils.decodeCompactBits(0x1e0fffffL);
// port = 19401;
// addressHeader = 111;
// p2shHeader = 196;
// acceptableAddressCodes = new int[] { addressHeader, p2shHeader };
// dumpedPrivateKeyHeader = 239;
// genesisBlock.setTime(1388479759L);
// genesisBlock.setDifficultyTarget(0x1e0ffff0L);
// genesisBlock.setNonce(600389L);
// spendableCoinbaseDepth = 100; // equivalent to COINBASE_MATURITY ?
// subsidyDecreaseBlockCount = 1051200;
//
// String genesisHash = genesisBlock.getHashAsString();
// // a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f
// checkState(genesisHash.equals("a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f"));
// alertSigningKey = Hex.decode("04887665070e79d20f722857e58ec8f402733f710135521a0b63441419bf5665ba4623bed13fca0cb2338682ab2a54ad13ce07fbc81c3c2f0912a4eb8521dd3cfb");
//
// dnsSeeds = new String[] {
// "test-dnsseed.monacoin.org",
// };
// }
//
// private static TestNet3Params instance;
// public static synchronized TestNet3Params get() {
// if (instance == null) {
// instance = new TestNet3Params();
// }
// return instance;
// }
//
// public String getPaymentProtocolId() {
// return PAYMENT_PROTOCOL_ID_TESTNET;
// }
// }
//
// Path: core/src/main/java/com/google/bitcoin/store/MemoryBlockStore.java
// public class MemoryBlockStore implements BlockStore {
// private LinkedHashMap<Sha256Hash, StoredBlock> blockMap = new LinkedHashMap<Sha256Hash, StoredBlock>() {
// @Override
// protected boolean removeEldestEntry(Map.Entry<Sha256Hash, StoredBlock> eldest) {
// return blockMap.size() > 60 * 60 * 24 * 7 / NetworkParameters.TARGET_SPACING + 1; // KGW past block max
// }
// };
// private StoredBlock chainHead;
//
// public MemoryBlockStore(NetworkParameters params) {
// // Insert the genesis block.
// try {
// Block genesisHeader = params.getGenesisBlock().cloneAsHeader();
// StoredBlock storedGenesis = new StoredBlock(genesisHeader, genesisHeader.getWork(), 0);
// put(storedGenesis);
// setChainHead(storedGenesis);
// } catch (BlockStoreException e) {
// throw new RuntimeException(e); // Cannot happen.
// } catch (VerificationException e) {
// throw new RuntimeException(e); // Cannot happen.
// }
// }
//
// public synchronized void put(StoredBlock block) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// Sha256Hash hash = block.getHeader().getHash();
// blockMap.put(hash, block);
// }
//
// public synchronized StoredBlock get(Sha256Hash hash) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// return blockMap.get(hash);
// }
//
// public StoredBlock getChainHead() throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// return chainHead;
// }
//
// public void setChainHead(StoredBlock chainHead) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// this.chainHead = chainHead;
// }
//
// public void close() {
// blockMap = null;
// }
// }
| import com.google.bitcoin.core.*;
import com.google.bitcoin.params.TestNet3Params;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.MemoryBlockStore;
import java.io.File;
import java.math.BigInteger;
import java.net.InetAddress; | /*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.examples;
/**
* RefreshWallet loads a wallet, then processes the block chain to update the transaction pools within it.
*/
public class RefreshWallet {
public static void main(String[] args) throws Exception {
File file = new File(args[0]);
Wallet wallet = Wallet.loadFromFile(file);
System.out.println(wallet.toString());
// Set up the components and link them together.
final NetworkParameters params = TestNet3Params.get(); | // Path: core/src/main/java/com/google/bitcoin/params/TestNet3Params.java
// public class TestNet3Params extends NetworkParameters {
// public TestNet3Params() {
// super();
// id = ID_TESTNET;
// // Genesis hash is a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f
// packetMagic = 0xfcc1b7dc; // correspond to pchMessageStart in main.cpp
// interval = INTERVAL;
// digishieldInterval = DIGISHIELD_INTERVAL;
//
// //switchKGWBlock = 0;
// //switchDigishieldBlock = 300;
// switchKGWBlock = SWITCH_KGW_BLOCK;
// switchDigishieldBlock = SWITCH_DIGISHIELD_BLOCK;
// // switchDGWV3Block = SWITCH_DGW_V3_BLOCK;
// // switchAlgoLyra2ReV2 = SWITCH_ALGO_LYRA2_RE_V2;
// switchDGWV3Block = 5;
// switchAlgoLyra2ReV2 = 5;
//
// targetTimespan = TARGET_TIMESPAN;
// digishieldTargetTimespan = DIGISHIELD_TARGET_TIMESPAN;
// proofOfWorkLimit = Utils.decodeCompactBits(0x1e0fffffL);
// port = 19401;
// addressHeader = 111;
// p2shHeader = 196;
// acceptableAddressCodes = new int[] { addressHeader, p2shHeader };
// dumpedPrivateKeyHeader = 239;
// genesisBlock.setTime(1388479759L);
// genesisBlock.setDifficultyTarget(0x1e0ffff0L);
// genesisBlock.setNonce(600389L);
// spendableCoinbaseDepth = 100; // equivalent to COINBASE_MATURITY ?
// subsidyDecreaseBlockCount = 1051200;
//
// String genesisHash = genesisBlock.getHashAsString();
// // a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f
// checkState(genesisHash.equals("a0d810b45c92ac12e8c5b312a680caafba52216e5d9649b9dd86f7ad6550a43f"));
// alertSigningKey = Hex.decode("04887665070e79d20f722857e58ec8f402733f710135521a0b63441419bf5665ba4623bed13fca0cb2338682ab2a54ad13ce07fbc81c3c2f0912a4eb8521dd3cfb");
//
// dnsSeeds = new String[] {
// "test-dnsseed.monacoin.org",
// };
// }
//
// private static TestNet3Params instance;
// public static synchronized TestNet3Params get() {
// if (instance == null) {
// instance = new TestNet3Params();
// }
// return instance;
// }
//
// public String getPaymentProtocolId() {
// return PAYMENT_PROTOCOL_ID_TESTNET;
// }
// }
//
// Path: core/src/main/java/com/google/bitcoin/store/MemoryBlockStore.java
// public class MemoryBlockStore implements BlockStore {
// private LinkedHashMap<Sha256Hash, StoredBlock> blockMap = new LinkedHashMap<Sha256Hash, StoredBlock>() {
// @Override
// protected boolean removeEldestEntry(Map.Entry<Sha256Hash, StoredBlock> eldest) {
// return blockMap.size() > 60 * 60 * 24 * 7 / NetworkParameters.TARGET_SPACING + 1; // KGW past block max
// }
// };
// private StoredBlock chainHead;
//
// public MemoryBlockStore(NetworkParameters params) {
// // Insert the genesis block.
// try {
// Block genesisHeader = params.getGenesisBlock().cloneAsHeader();
// StoredBlock storedGenesis = new StoredBlock(genesisHeader, genesisHeader.getWork(), 0);
// put(storedGenesis);
// setChainHead(storedGenesis);
// } catch (BlockStoreException e) {
// throw new RuntimeException(e); // Cannot happen.
// } catch (VerificationException e) {
// throw new RuntimeException(e); // Cannot happen.
// }
// }
//
// public synchronized void put(StoredBlock block) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// Sha256Hash hash = block.getHeader().getHash();
// blockMap.put(hash, block);
// }
//
// public synchronized StoredBlock get(Sha256Hash hash) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// return blockMap.get(hash);
// }
//
// public StoredBlock getChainHead() throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// return chainHead;
// }
//
// public void setChainHead(StoredBlock chainHead) throws BlockStoreException {
// if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed");
// this.chainHead = chainHead;
// }
//
// public void close() {
// blockMap = null;
// }
// }
// Path: examples/src/main/java/com/google/bitcoin/examples/RefreshWallet.java
import com.google.bitcoin.core.*;
import com.google.bitcoin.params.TestNet3Params;
import com.google.bitcoin.store.BlockStore;
import com.google.bitcoin.store.MemoryBlockStore;
import java.io.File;
import java.math.BigInteger;
import java.net.InetAddress;
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.examples;
/**
* RefreshWallet loads a wallet, then processes the block chain to update the transaction pools within it.
*/
public class RefreshWallet {
public static void main(String[] args) throws Exception {
File file = new File(args[0]);
Wallet wallet = Wallet.loadFromFile(file);
System.out.println(wallet.toString());
// Set up the components and link them together.
final NetworkParameters params = TestNet3Params.get(); | BlockStore blockStore = new MemoryBlockStore(params); |
wangzhengbo/TCC4Java | test/cn/com/tcc/SetErrorFuncTest.java | // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
| import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.IntHolder;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Callback;
import com.sun.jna.Function;
import com.sun.jna.Pointer;
| package cn.com.tcc;
public class SetErrorFuncTest extends BaseTest {
@Test
public void setErrorFunc() {
State state = new State();
final ObjHolder opaqueHolder = new ObjHolder();
final StringHolder msgHolder = new StringHolder();
| // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
// Path: test/cn/com/tcc/SetErrorFuncTest.java
import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.IntHolder;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Callback;
import com.sun.jna.Function;
import com.sun.jna.Pointer;
package cn.com.tcc;
public class SetErrorFuncTest extends BaseTest {
@Test
public void setErrorFunc() {
State state = new State();
final ObjHolder opaqueHolder = new ObjHolder();
final StringHolder msgHolder = new StringHolder();
| state.setErrorFunc(new ErrorFunction() {
|
wangzhengbo/TCC4Java | test/cn/com/tcc/SetOptionsTest.java | // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
| import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Pointer;
| package cn.com.tcc;
public class SetOptionsTest extends BaseTest {
@Test
public void setOptoins() throws IOException {
State state = new State();
final StringHolder msgHolder = new StringHolder();
| // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
// Path: test/cn/com/tcc/SetOptionsTest.java
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Pointer;
package cn.com.tcc;
public class SetOptionsTest extends BaseTest {
@Test
public void setOptoins() throws IOException {
State state = new State();
final StringHolder msgHolder = new StringHolder();
| state.setErrorFunc(new ErrorFunction() {
|
wangzhengbo/TCC4Java | test/cn/com/tcc/AddSysIncludePathTest.java | // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
| import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Pointer;
| package cn.com.tcc;
public class AddSysIncludePathTest extends BaseTest {
@Test
public void addSysIncludePath() throws IOException {
State state = new State();
final StringHolder msgHolder = new StringHolder();
| // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
// Path: test/cn/com/tcc/AddSysIncludePathTest.java
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Pointer;
package cn.com.tcc;
public class AddSysIncludePathTest extends BaseTest {
@Test
public void addSysIncludePath() throws IOException {
State state = new State();
final StringHolder msgHolder = new StringHolder();
| state.setErrorFunc(new ErrorFunction() {
|
wangzhengbo/TCC4Java | src/cn/com/tcc/State.java | // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
//
// Path: src/cn/com/tcc/TCC.java
// protected static interface TCCLibrary extends Library {
// /* create a new TCC compilation context */
// public Pointer tcc_new();
//
// /* free a TCC compilation context */
// public void tcc_delete(Pointer tccState);
//
// /* set CONFIG_TCCDIR at runtime */
// public void tcc_set_lib_path(Pointer tccState, String path);
//
// /* set error/warning display callback */
// public void tcc_set_error_func(Pointer tccState, Pointer error_opaque,
// Callback error_func);
//
// public void tcc_set_error_func(Pointer tccState, Callback error_opaque,
// Callback error_func);
//
// /* set options as from command line (multiple supported) */
// public int tcc_set_options(Pointer tccState, String str);
//
// /*****************************/
// /* preprocessor */
//
// /* add include path */
// public int tcc_add_include_path(Pointer tccState, String pathname);
//
// /* add in system include path */
// public int tcc_add_sysinclude_path(Pointer tccState, String pathname);
//
// /* define preprocessor symbol 'sym'. Can put optional value */
// public void tcc_define_symbol(Pointer tccState, String sym, String val);
//
// /* undefine preprocess symbol 'sym' */
// public void tcc_undefine_symbol(Pointer tccState, String sym);
//
// /*****************************/
// /* compiling */
//
// /*
// * add a file (C file, dll, object, library, ld script). Return -1 if
// * error.
// */
// public int tcc_add_file(Pointer tccState, String filename);
//
// /* compile a string containing a C source. Return -1 if error. */
// public int tcc_compile_string(Pointer tccState, String buf);
//
// /*****************************/
// /* linking commands */
//
// /* set output type. MUST BE CALLED before any compilation */
// public int tcc_set_output_type(Pointer tccState, int type);
//
// /* equivalent to -Lpath option */
// public int tcc_add_library_path(Pointer tccState, String pathname);
//
// /* the library name is the same as the argument of the '-l' option */
// public int tcc_add_library(Pointer tccState, String libraryname);
//
// /* add a symbol to the compiled program */
// public int tcc_add_symbol(Pointer tccState, String name, Pointer val);
//
// public int tcc_add_symbol(Pointer tccState, String name, Callback val);
//
// /*
// * output an executable, library or object file. DO NOT call
// * tcc_relocate() before.
// */
// public int tcc_output_file(Pointer tccState, String filename);
//
// /*
// * link and run main() function and return its value. DO NOT call
// * tcc_relocate() before.
// */
// public int tcc_run(Pointer tccState, int argc, String[] argv);
//
// /**
// * do all relocations (needed before using tcc_get_symbol())
// *
// * possible values for 'ptr':<br/>
// * - TCC_RELOCATE_AUTO : Allocate and manage memory internally<br/>
// * - NULL : return required memory size for the step below<br/>
// * - memory address : copy code to memory passed by the caller<br/>
// * returns -1 if error.
// */
// public int tcc_relocate(Pointer tccState, Pointer ptr);
//
// /* return symbol value or NULL if not found */
// public Pointer tcc_get_symbol(Pointer tccState, String name);
//
// }
| import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.tcc.TCC.ErrorFunction;
import cn.com.tcc.TCC.TCCLibrary;
import com.sun.jna.Callback;
import com.sun.jna.Function;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
| package cn.com.tcc;
public class State {
public static final int ERROR_RETURN_VALUE = -1;
public final Pointer TCC_RELOCATE_AUTO = Pointer.createConstant(1);
| // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
//
// Path: src/cn/com/tcc/TCC.java
// protected static interface TCCLibrary extends Library {
// /* create a new TCC compilation context */
// public Pointer tcc_new();
//
// /* free a TCC compilation context */
// public void tcc_delete(Pointer tccState);
//
// /* set CONFIG_TCCDIR at runtime */
// public void tcc_set_lib_path(Pointer tccState, String path);
//
// /* set error/warning display callback */
// public void tcc_set_error_func(Pointer tccState, Pointer error_opaque,
// Callback error_func);
//
// public void tcc_set_error_func(Pointer tccState, Callback error_opaque,
// Callback error_func);
//
// /* set options as from command line (multiple supported) */
// public int tcc_set_options(Pointer tccState, String str);
//
// /*****************************/
// /* preprocessor */
//
// /* add include path */
// public int tcc_add_include_path(Pointer tccState, String pathname);
//
// /* add in system include path */
// public int tcc_add_sysinclude_path(Pointer tccState, String pathname);
//
// /* define preprocessor symbol 'sym'. Can put optional value */
// public void tcc_define_symbol(Pointer tccState, String sym, String val);
//
// /* undefine preprocess symbol 'sym' */
// public void tcc_undefine_symbol(Pointer tccState, String sym);
//
// /*****************************/
// /* compiling */
//
// /*
// * add a file (C file, dll, object, library, ld script). Return -1 if
// * error.
// */
// public int tcc_add_file(Pointer tccState, String filename);
//
// /* compile a string containing a C source. Return -1 if error. */
// public int tcc_compile_string(Pointer tccState, String buf);
//
// /*****************************/
// /* linking commands */
//
// /* set output type. MUST BE CALLED before any compilation */
// public int tcc_set_output_type(Pointer tccState, int type);
//
// /* equivalent to -Lpath option */
// public int tcc_add_library_path(Pointer tccState, String pathname);
//
// /* the library name is the same as the argument of the '-l' option */
// public int tcc_add_library(Pointer tccState, String libraryname);
//
// /* add a symbol to the compiled program */
// public int tcc_add_symbol(Pointer tccState, String name, Pointer val);
//
// public int tcc_add_symbol(Pointer tccState, String name, Callback val);
//
// /*
// * output an executable, library or object file. DO NOT call
// * tcc_relocate() before.
// */
// public int tcc_output_file(Pointer tccState, String filename);
//
// /*
// * link and run main() function and return its value. DO NOT call
// * tcc_relocate() before.
// */
// public int tcc_run(Pointer tccState, int argc, String[] argv);
//
// /**
// * do all relocations (needed before using tcc_get_symbol())
// *
// * possible values for 'ptr':<br/>
// * - TCC_RELOCATE_AUTO : Allocate and manage memory internally<br/>
// * - NULL : return required memory size for the step below<br/>
// * - memory address : copy code to memory passed by the caller<br/>
// * returns -1 if error.
// */
// public int tcc_relocate(Pointer tccState, Pointer ptr);
//
// /* return symbol value or NULL if not found */
// public Pointer tcc_get_symbol(Pointer tccState, String name);
//
// }
// Path: src/cn/com/tcc/State.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.tcc.TCC.ErrorFunction;
import cn.com.tcc.TCC.TCCLibrary;
import com.sun.jna.Callback;
import com.sun.jna.Function;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
package cn.com.tcc;
public class State {
public static final int ERROR_RETURN_VALUE = -1;
public final Pointer TCC_RELOCATE_AUTO = Pointer.createConstant(1);
| private final TCCLibrary tcc;
|
wangzhengbo/TCC4Java | src/cn/com/tcc/State.java | // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
//
// Path: src/cn/com/tcc/TCC.java
// protected static interface TCCLibrary extends Library {
// /* create a new TCC compilation context */
// public Pointer tcc_new();
//
// /* free a TCC compilation context */
// public void tcc_delete(Pointer tccState);
//
// /* set CONFIG_TCCDIR at runtime */
// public void tcc_set_lib_path(Pointer tccState, String path);
//
// /* set error/warning display callback */
// public void tcc_set_error_func(Pointer tccState, Pointer error_opaque,
// Callback error_func);
//
// public void tcc_set_error_func(Pointer tccState, Callback error_opaque,
// Callback error_func);
//
// /* set options as from command line (multiple supported) */
// public int tcc_set_options(Pointer tccState, String str);
//
// /*****************************/
// /* preprocessor */
//
// /* add include path */
// public int tcc_add_include_path(Pointer tccState, String pathname);
//
// /* add in system include path */
// public int tcc_add_sysinclude_path(Pointer tccState, String pathname);
//
// /* define preprocessor symbol 'sym'. Can put optional value */
// public void tcc_define_symbol(Pointer tccState, String sym, String val);
//
// /* undefine preprocess symbol 'sym' */
// public void tcc_undefine_symbol(Pointer tccState, String sym);
//
// /*****************************/
// /* compiling */
//
// /*
// * add a file (C file, dll, object, library, ld script). Return -1 if
// * error.
// */
// public int tcc_add_file(Pointer tccState, String filename);
//
// /* compile a string containing a C source. Return -1 if error. */
// public int tcc_compile_string(Pointer tccState, String buf);
//
// /*****************************/
// /* linking commands */
//
// /* set output type. MUST BE CALLED before any compilation */
// public int tcc_set_output_type(Pointer tccState, int type);
//
// /* equivalent to -Lpath option */
// public int tcc_add_library_path(Pointer tccState, String pathname);
//
// /* the library name is the same as the argument of the '-l' option */
// public int tcc_add_library(Pointer tccState, String libraryname);
//
// /* add a symbol to the compiled program */
// public int tcc_add_symbol(Pointer tccState, String name, Pointer val);
//
// public int tcc_add_symbol(Pointer tccState, String name, Callback val);
//
// /*
// * output an executable, library or object file. DO NOT call
// * tcc_relocate() before.
// */
// public int tcc_output_file(Pointer tccState, String filename);
//
// /*
// * link and run main() function and return its value. DO NOT call
// * tcc_relocate() before.
// */
// public int tcc_run(Pointer tccState, int argc, String[] argv);
//
// /**
// * do all relocations (needed before using tcc_get_symbol())
// *
// * possible values for 'ptr':<br/>
// * - TCC_RELOCATE_AUTO : Allocate and manage memory internally<br/>
// * - NULL : return required memory size for the step below<br/>
// * - memory address : copy code to memory passed by the caller<br/>
// * returns -1 if error.
// */
// public int tcc_relocate(Pointer tccState, Pointer ptr);
//
// /* return symbol value or NULL if not found */
// public Pointer tcc_get_symbol(Pointer tccState, String name);
//
// }
| import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.tcc.TCC.ErrorFunction;
import cn.com.tcc.TCC.TCCLibrary;
import com.sun.jna.Callback;
import com.sun.jna.Function;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
| package cn.com.tcc;
public class State {
public static final int ERROR_RETURN_VALUE = -1;
public final Pointer TCC_RELOCATE_AUTO = Pointer.createConstant(1);
private final TCCLibrary tcc;
private final Pointer tccState;
private boolean deleted = false;
@SuppressWarnings("unused")
private Pointer errorOpaque = null;
@SuppressWarnings("unused")
private Callback errorOpaqueCallback = null;
@SuppressWarnings("unused")
| // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
//
// Path: src/cn/com/tcc/TCC.java
// protected static interface TCCLibrary extends Library {
// /* create a new TCC compilation context */
// public Pointer tcc_new();
//
// /* free a TCC compilation context */
// public void tcc_delete(Pointer tccState);
//
// /* set CONFIG_TCCDIR at runtime */
// public void tcc_set_lib_path(Pointer tccState, String path);
//
// /* set error/warning display callback */
// public void tcc_set_error_func(Pointer tccState, Pointer error_opaque,
// Callback error_func);
//
// public void tcc_set_error_func(Pointer tccState, Callback error_opaque,
// Callback error_func);
//
// /* set options as from command line (multiple supported) */
// public int tcc_set_options(Pointer tccState, String str);
//
// /*****************************/
// /* preprocessor */
//
// /* add include path */
// public int tcc_add_include_path(Pointer tccState, String pathname);
//
// /* add in system include path */
// public int tcc_add_sysinclude_path(Pointer tccState, String pathname);
//
// /* define preprocessor symbol 'sym'. Can put optional value */
// public void tcc_define_symbol(Pointer tccState, String sym, String val);
//
// /* undefine preprocess symbol 'sym' */
// public void tcc_undefine_symbol(Pointer tccState, String sym);
//
// /*****************************/
// /* compiling */
//
// /*
// * add a file (C file, dll, object, library, ld script). Return -1 if
// * error.
// */
// public int tcc_add_file(Pointer tccState, String filename);
//
// /* compile a string containing a C source. Return -1 if error. */
// public int tcc_compile_string(Pointer tccState, String buf);
//
// /*****************************/
// /* linking commands */
//
// /* set output type. MUST BE CALLED before any compilation */
// public int tcc_set_output_type(Pointer tccState, int type);
//
// /* equivalent to -Lpath option */
// public int tcc_add_library_path(Pointer tccState, String pathname);
//
// /* the library name is the same as the argument of the '-l' option */
// public int tcc_add_library(Pointer tccState, String libraryname);
//
// /* add a symbol to the compiled program */
// public int tcc_add_symbol(Pointer tccState, String name, Pointer val);
//
// public int tcc_add_symbol(Pointer tccState, String name, Callback val);
//
// /*
// * output an executable, library or object file. DO NOT call
// * tcc_relocate() before.
// */
// public int tcc_output_file(Pointer tccState, String filename);
//
// /*
// * link and run main() function and return its value. DO NOT call
// * tcc_relocate() before.
// */
// public int tcc_run(Pointer tccState, int argc, String[] argv);
//
// /**
// * do all relocations (needed before using tcc_get_symbol())
// *
// * possible values for 'ptr':<br/>
// * - TCC_RELOCATE_AUTO : Allocate and manage memory internally<br/>
// * - NULL : return required memory size for the step below<br/>
// * - memory address : copy code to memory passed by the caller<br/>
// * returns -1 if error.
// */
// public int tcc_relocate(Pointer tccState, Pointer ptr);
//
// /* return symbol value or NULL if not found */
// public Pointer tcc_get_symbol(Pointer tccState, String name);
//
// }
// Path: src/cn/com/tcc/State.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.tcc.TCC.ErrorFunction;
import cn.com.tcc.TCC.TCCLibrary;
import com.sun.jna.Callback;
import com.sun.jna.Function;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
package cn.com.tcc;
public class State {
public static final int ERROR_RETURN_VALUE = -1;
public final Pointer TCC_RELOCATE_AUTO = Pointer.createConstant(1);
private final TCCLibrary tcc;
private final Pointer tccState;
private boolean deleted = false;
@SuppressWarnings("unused")
private Pointer errorOpaque = null;
@SuppressWarnings("unused")
private Callback errorOpaqueCallback = null;
@SuppressWarnings("unused")
| private ErrorFunction errorFunc = null;
|
wangzhengbo/TCC4Java | test/cn/com/tcc/SetLibPathTest.java | // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
| import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Function;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
| package cn.com.tcc;
public class SetLibPathTest extends BaseTest {
@Test
public void setLibPath() {
State state = new State();
Assert.assertTrue(state.compileString(PROGRAM_ADD));
Assert.assertTrue(state.relocateAuto());
Function addFunc = state.getFunction("add");
Assert.assertNotNull(addFunc);
Assert.assertEquals(3, addFunc.invokeInt(new Object[] { 1, 2 }));
state.delete();
// error lib path
state = new State();
state.setLibPath(System.getProperty("java.io.tmpdir"));
Assert.assertTrue(state.compileString(PROGRAM_ADD));
if (Platform.isWindows()
|| "linux/arm".equals(TCC.getNativeLibraryResourcePrefix(
TCC.getOS(TCC.getOSName()),
System.getProperty("os.arch"),
System.getProperty("os.name")))) {
Assert.assertTrue(state.relocateAuto());
addFunc = state.getFunction("add");
Assert.assertNotNull(addFunc);
Assert.assertEquals(5, addFunc.invokeInt(new Object[] { 2, 3 }));
} else {
final StringHolder msgHolder = new StringHolder();
| // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
// Path: test/cn/com/tcc/SetLibPathTest.java
import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Function;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
package cn.com.tcc;
public class SetLibPathTest extends BaseTest {
@Test
public void setLibPath() {
State state = new State();
Assert.assertTrue(state.compileString(PROGRAM_ADD));
Assert.assertTrue(state.relocateAuto());
Function addFunc = state.getFunction("add");
Assert.assertNotNull(addFunc);
Assert.assertEquals(3, addFunc.invokeInt(new Object[] { 1, 2 }));
state.delete();
// error lib path
state = new State();
state.setLibPath(System.getProperty("java.io.tmpdir"));
Assert.assertTrue(state.compileString(PROGRAM_ADD));
if (Platform.isWindows()
|| "linux/arm".equals(TCC.getNativeLibraryResourcePrefix(
TCC.getOS(TCC.getOSName()),
System.getProperty("os.arch"),
System.getProperty("os.name")))) {
Assert.assertTrue(state.relocateAuto());
addFunc = state.getFunction("add");
Assert.assertNotNull(addFunc);
Assert.assertEquals(5, addFunc.invokeInt(new Object[] { 2, 3 }));
} else {
final StringHolder msgHolder = new StringHolder();
| state.setErrorFunc(new ErrorFunction() {
|
wangzhengbo/TCC4Java | test/cn/com/tcc/CompileStringTest.java | // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
| import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Pointer;
| package cn.com.tcc;
public class CompileStringTest extends BaseTest {
@Test
public void compileString() {
State state = new State();
Assert.assertTrue(state.compileString("int main() {return 0;}"));
Assert.assertEquals(0, state.run());
state.delete();
state = new State();
final StringHolder msgHolder = new StringHolder();
| // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
// Path: test/cn/com/tcc/CompileStringTest.java
import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Pointer;
package cn.com.tcc;
public class CompileStringTest extends BaseTest {
@Test
public void compileString() {
State state = new State();
Assert.assertTrue(state.compileString("int main() {return 0;}"));
Assert.assertEquals(0, state.run());
state.delete();
state = new State();
final StringHolder msgHolder = new StringHolder();
| state.setErrorFunc(new ErrorFunction() {
|
wangzhengbo/TCC4Java | test/cn/com/tcc/AddIncludePathTest.java | // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
| import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Pointer;
| package cn.com.tcc;
public class AddIncludePathTest extends BaseTest {
@Test
public void addIncludePath() throws IOException {
State state = new State();
final StringHolder msgHolder = new StringHolder();
| // Path: src/cn/com/tcc/TCC.java
// public static interface ErrorFunction extends Callback {
// public void callback(Pointer opaque, String msg);
// }
// Path: test/cn/com/tcc/AddIncludePathTest.java
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.omg.CORBA.StringHolder;
import cn.com.tcc.TCC.ErrorFunction;
import com.sun.jna.Pointer;
package cn.com.tcc;
public class AddIncludePathTest extends BaseTest {
@Test
public void addIncludePath() throws IOException {
State state = new State();
final StringHolder msgHolder = new StringHolder();
| state.setErrorFunc(new ErrorFunction() {
|
orange-cloudfoundry/db-dumper-service | src/test/java/com/orange/clara/cloud/servicedbdumper/task/ScheduledCreateDumpTaskTest.java | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/task/asynctask/CreateDumpTask.java
// public class CreateDumpTask {
// private Logger logger = LoggerFactory.getLogger(CreateDumpTask.class);
// @Autowired
// private Dumper dumper;
//
// @Autowired
// private JobRepo jobRepo;
//
// @Autowired
// private DatabaseRefManager databaseRefManager;
//
// @Autowired
// private DatabaseDumpFileRepo databaseDumpFileRepo;
//
// @Async
// @Transactional(propagation = Propagation.REQUIRES_NEW)
// public Future<Boolean> runTask(Integer jobId) throws AsyncTaskException {
// Job job = this.jobRepo.findOne(jobId);
// DatabaseDumpFile databaseDumpFile = null;
// try {
// databaseDumpFile = this.dumper.dump(job.getDbDumperServiceInstance());
// if (job.getMetadata() != null) {
// logger.debug("Adding metadata for dump {}.", databaseDumpFile.getId());
// databaseDumpFile.setMetadata(job.getMetadata());
// this.databaseDumpFileRepo.save(databaseDumpFile);
// logger.debug("Finished adding metadata.");
// }
// } catch (DumpException e) {
// logger.error("Cannot create dump for '{}': {}", job.getDatabaseRefSrc().getName(), e.getMessage());
// job.setJobEvent(JobEvent.ERRORED);
// job.setErrorMessage(e.getMessage());
// this.databaseRefManager.deleteServiceKey(job);
// jobRepo.save(job);
// return new AsyncResult<Boolean>(false);
// }
//
// job.setJobEvent(JobEvent.FINISHED);
// this.databaseRefManager.deleteServiceKey(job);
// jobRepo.save(job);
// return new AsyncResult<Boolean>(true);
// }
// }
| import com.google.common.collect.Lists;
import com.orange.clara.cloud.servicedbdumper.exception.AsyncTaskException;
import com.orange.clara.cloud.servicedbdumper.model.Job;
import com.orange.clara.cloud.servicedbdumper.model.JobEvent;
import com.orange.clara.cloud.servicedbdumper.model.JobType;
import com.orange.clara.cloud.servicedbdumper.repo.JobRepo;
import com.orange.clara.cloud.servicedbdumper.task.asynctask.CreateDumpTask;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.util.Arrays;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.notNull;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks; | package com.orange.clara.cloud.servicedbdumper.task;
/**
* Copyright (C) 2016 Arthur Halet
* <p>
* This software is distributed under the terms and conditions of the 'MIT'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'http://opensource.org/licenses/MIT'.
* <p>
* Author: Arthur Halet
* Date: 21/03/2016
*/
public class ScheduledCreateDumpTaskTest extends AbstractScheduledTaskTest {
@InjectMocks
ScheduledCreateDumpTask scheduledTask = new ScheduledCreateDumpTask();
@Mock | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/task/asynctask/CreateDumpTask.java
// public class CreateDumpTask {
// private Logger logger = LoggerFactory.getLogger(CreateDumpTask.class);
// @Autowired
// private Dumper dumper;
//
// @Autowired
// private JobRepo jobRepo;
//
// @Autowired
// private DatabaseRefManager databaseRefManager;
//
// @Autowired
// private DatabaseDumpFileRepo databaseDumpFileRepo;
//
// @Async
// @Transactional(propagation = Propagation.REQUIRES_NEW)
// public Future<Boolean> runTask(Integer jobId) throws AsyncTaskException {
// Job job = this.jobRepo.findOne(jobId);
// DatabaseDumpFile databaseDumpFile = null;
// try {
// databaseDumpFile = this.dumper.dump(job.getDbDumperServiceInstance());
// if (job.getMetadata() != null) {
// logger.debug("Adding metadata for dump {}.", databaseDumpFile.getId());
// databaseDumpFile.setMetadata(job.getMetadata());
// this.databaseDumpFileRepo.save(databaseDumpFile);
// logger.debug("Finished adding metadata.");
// }
// } catch (DumpException e) {
// logger.error("Cannot create dump for '{}': {}", job.getDatabaseRefSrc().getName(), e.getMessage());
// job.setJobEvent(JobEvent.ERRORED);
// job.setErrorMessage(e.getMessage());
// this.databaseRefManager.deleteServiceKey(job);
// jobRepo.save(job);
// return new AsyncResult<Boolean>(false);
// }
//
// job.setJobEvent(JobEvent.FINISHED);
// this.databaseRefManager.deleteServiceKey(job);
// jobRepo.save(job);
// return new AsyncResult<Boolean>(true);
// }
// }
// Path: src/test/java/com/orange/clara/cloud/servicedbdumper/task/ScheduledCreateDumpTaskTest.java
import com.google.common.collect.Lists;
import com.orange.clara.cloud.servicedbdumper.exception.AsyncTaskException;
import com.orange.clara.cloud.servicedbdumper.model.Job;
import com.orange.clara.cloud.servicedbdumper.model.JobEvent;
import com.orange.clara.cloud.servicedbdumper.model.JobType;
import com.orange.clara.cloud.servicedbdumper.repo.JobRepo;
import com.orange.clara.cloud.servicedbdumper.task.asynctask.CreateDumpTask;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.util.Arrays;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.notNull;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
package com.orange.clara.cloud.servicedbdumper.task;
/**
* Copyright (C) 2016 Arthur Halet
* <p>
* This software is distributed under the terms and conditions of the 'MIT'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'http://opensource.org/licenses/MIT'.
* <p>
* Author: Arthur Halet
* Date: 21/03/2016
*/
public class ScheduledCreateDumpTaskTest extends AbstractScheduledTaskTest {
@InjectMocks
ScheduledCreateDumpTask scheduledTask = new ScheduledCreateDumpTask();
@Mock | CreateDumpTask createDumpTask; |
orange-cloudfoundry/db-dumper-service | src/test/java/com/orange/clara/cloud/servicedbdumper/task/boot/BootTest.java | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/task/boot/sequences/BootSequence.java
// public interface BootSequence {
// void runSequence() throws BootSequenceException;
// }
| import com.google.common.collect.Lists;
import com.orange.clara.cloud.servicedbdumper.exception.BootSequenceException;
import com.orange.clara.cloud.servicedbdumper.task.boot.sequences.BootSequence;
import org.junit.Before;
import org.junit.Test;
import javax.annotation.PostConstruct;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.MockitoAnnotations.initMocks; | package com.orange.clara.cloud.servicedbdumper.task.boot;
/**
* Copyright (C) 2016 Arthur Halet
* <p>
* This software is distributed under the terms and conditions of the 'MIT'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'http://opensource.org/licenses/MIT'.
* <p>
* Author: Arthur Halet
* Date: 21/03/2016
*/
public class BootTest {
private static String content;
Boot boot = new Boot();
@Before
public void init() {
initMocks(this);
content = "content"; | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/task/boot/sequences/BootSequence.java
// public interface BootSequence {
// void runSequence() throws BootSequenceException;
// }
// Path: src/test/java/com/orange/clara/cloud/servicedbdumper/task/boot/BootTest.java
import com.google.common.collect.Lists;
import com.orange.clara.cloud.servicedbdumper.exception.BootSequenceException;
import com.orange.clara.cloud.servicedbdumper.task.boot.sequences.BootSequence;
import org.junit.Before;
import org.junit.Test;
import javax.annotation.PostConstruct;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.MockitoAnnotations.initMocks;
package com.orange.clara.cloud.servicedbdumper.task.boot;
/**
* Copyright (C) 2016 Arthur Halet
* <p>
* This software is distributed under the terms and conditions of the 'MIT'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'http://opensource.org/licenses/MIT'.
* <p>
* Author: Arthur Halet
* Date: 21/03/2016
*/
public class BootTest {
private static String content;
Boot boot = new Boot();
@Before
public void init() {
initMocks(this);
content = "content"; | List<BootSequence> bootSequences = Lists.newArrayList(); |
orange-cloudfoundry/db-dumper-service | src/test/java/com/orange/clara/cloud/servicedbdumper/fake/dbdumper/mocked/DeleterMock.java | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/model/DatabaseDumpFile.java
// @Entity
// public class DatabaseDumpFile {
//
// protected String user;
// @Convert(converter = CryptoConverter.class)
// protected String password;
// protected Boolean showable;
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int id;
//
// private String fileName;
// @Column(name = "created_at")
// private Date createdAt;
//
// @Column(name = "deleted_at")
// private Date deletedAt;
//
// @ManyToOne
// @JoinColumn(name = "service_instance_id")
// private DbDumperServiceInstance dbDumperServiceInstance;
//
// @Convert(converter = MetadataConverter.class)
// private Metadata metadata;
//
// private Boolean deleted;
// private Long size;
//
// public DatabaseDumpFile() {
// this.createdAt = Calendar.getInstance().getTime();
// this.showable = true;
// this.deleted = false;
// this.user = "";
// this.password = "";
// }
//
// public DatabaseDumpFile(String fileName, DbDumperServiceInstance dbDumperServiceInstance, String user, String password, boolean showable, long size) {
// this();
// this.fileName = fileName;
// this.user = user;
// this.password = password;
// this.showable = showable;
// this.size = size;
// this.setDbDumperServiceInstance(dbDumperServiceInstance);
// }
//
// public DatabaseDumpFile(File file, DbDumperServiceInstance dbDumperServiceInstance, String user, String password, boolean showable, long size) {
// this();
// this.user = user;
// this.password = password;
// this.showable = showable;
// this.size = size;
// this.setFileName(file);
// this.setDbDumperServiceInstance(dbDumperServiceInstance);
// }
//
// public DbDumperServiceInstance getDbDumperServiceInstance() {
// return dbDumperServiceInstance;
// }
//
// public void setDbDumperServiceInstance(DbDumperServiceInstance dbDumperServiceInstance) {
// this.dbDumperServiceInstance = dbDumperServiceInstance;
// dbDumperServiceInstance.addDatabaseDumpFile(this);
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getFileName() {
// return this.fileName;
// }
//
// public void setFileName(String fileName) {
// this.fileName = fileName;
// }
//
// public void setFileName(File file) {
// this.fileName = file.getName();
// }
//
// public File getFile() {
// return new File(this.fileName);
// }
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(Date createdAt) {
// this.createdAt = createdAt;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Boolean getShowable() {
// return showable;
// }
//
// public void setShowable(Boolean showable) {
// this.showable = showable;
// }
//
// public Boolean isShowable() {
// return showable;
// }
//
// public Boolean getDeleted() {
// return deleted;
// }
//
// public void setDeleted(Boolean deleted) {
// if (deleted) {
// this.deletedAt = new Date();
// } else {
// this.deleted = null;
// }
// this.deleted = deleted;
// }
//
// public Boolean isDeleted() {
// return deleted;
// }
//
// public Date getDeletedAt() {
// return deletedAt;
// }
//
// public void setDeletedAt(Date deletedAt) {
// this.deletedAt = deletedAt;
// }
//
// public Metadata getMetadata() {
// return metadata;
// }
//
// public void setMetadata(Metadata metadata) {
// this.metadata = metadata;
// }
//
// @PrePersist
// public void createdAt() {
// this.createdAt = new Date();
// }
//
// @Override
// public int hashCode() {
// return id;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// DatabaseDumpFile that = (DatabaseDumpFile) o;
//
// return id == that.id;
//
// }
//
// @Override
// public String toString() {
// return "DatabaseDumpFile{" +
// "id=" + id +
// ", fileName='" + fileName + '\'' +
// ", createdAt=" + createdAt +
// '}';
// }
//
// public Long getSize() {
// return size;
// }
//
// public void setSize(Long size) {
// this.size = size;
// }
// }
| import com.orange.clara.cloud.servicedbdumper.dbdumper.Deleter;
import com.orange.clara.cloud.servicedbdumper.model.DatabaseDumpFile;
import com.orange.clara.cloud.servicedbdumper.model.DbDumperServiceInstance; | package com.orange.clara.cloud.servicedbdumper.fake.dbdumper.mocked;
/**
* Copyright (C) 2016 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 24/03/2016
*/
public class DeleterMock implements Deleter {
private Integer numberCallDelete = 0;
public Integer getNumberCallDelete() {
return numberCallDelete;
}
public void resetNumberCallDelete() {
numberCallDelete = 0;
}
@Override
public void deleteAll(DbDumperServiceInstance dbDumperServiceInstance) { | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/model/DatabaseDumpFile.java
// @Entity
// public class DatabaseDumpFile {
//
// protected String user;
// @Convert(converter = CryptoConverter.class)
// protected String password;
// protected Boolean showable;
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private int id;
//
// private String fileName;
// @Column(name = "created_at")
// private Date createdAt;
//
// @Column(name = "deleted_at")
// private Date deletedAt;
//
// @ManyToOne
// @JoinColumn(name = "service_instance_id")
// private DbDumperServiceInstance dbDumperServiceInstance;
//
// @Convert(converter = MetadataConverter.class)
// private Metadata metadata;
//
// private Boolean deleted;
// private Long size;
//
// public DatabaseDumpFile() {
// this.createdAt = Calendar.getInstance().getTime();
// this.showable = true;
// this.deleted = false;
// this.user = "";
// this.password = "";
// }
//
// public DatabaseDumpFile(String fileName, DbDumperServiceInstance dbDumperServiceInstance, String user, String password, boolean showable, long size) {
// this();
// this.fileName = fileName;
// this.user = user;
// this.password = password;
// this.showable = showable;
// this.size = size;
// this.setDbDumperServiceInstance(dbDumperServiceInstance);
// }
//
// public DatabaseDumpFile(File file, DbDumperServiceInstance dbDumperServiceInstance, String user, String password, boolean showable, long size) {
// this();
// this.user = user;
// this.password = password;
// this.showable = showable;
// this.size = size;
// this.setFileName(file);
// this.setDbDumperServiceInstance(dbDumperServiceInstance);
// }
//
// public DbDumperServiceInstance getDbDumperServiceInstance() {
// return dbDumperServiceInstance;
// }
//
// public void setDbDumperServiceInstance(DbDumperServiceInstance dbDumperServiceInstance) {
// this.dbDumperServiceInstance = dbDumperServiceInstance;
// dbDumperServiceInstance.addDatabaseDumpFile(this);
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getFileName() {
// return this.fileName;
// }
//
// public void setFileName(String fileName) {
// this.fileName = fileName;
// }
//
// public void setFileName(File file) {
// this.fileName = file.getName();
// }
//
// public File getFile() {
// return new File(this.fileName);
// }
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(Date createdAt) {
// this.createdAt = createdAt;
// }
//
// public String getUser() {
// return user;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Boolean getShowable() {
// return showable;
// }
//
// public void setShowable(Boolean showable) {
// this.showable = showable;
// }
//
// public Boolean isShowable() {
// return showable;
// }
//
// public Boolean getDeleted() {
// return deleted;
// }
//
// public void setDeleted(Boolean deleted) {
// if (deleted) {
// this.deletedAt = new Date();
// } else {
// this.deleted = null;
// }
// this.deleted = deleted;
// }
//
// public Boolean isDeleted() {
// return deleted;
// }
//
// public Date getDeletedAt() {
// return deletedAt;
// }
//
// public void setDeletedAt(Date deletedAt) {
// this.deletedAt = deletedAt;
// }
//
// public Metadata getMetadata() {
// return metadata;
// }
//
// public void setMetadata(Metadata metadata) {
// this.metadata = metadata;
// }
//
// @PrePersist
// public void createdAt() {
// this.createdAt = new Date();
// }
//
// @Override
// public int hashCode() {
// return id;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// DatabaseDumpFile that = (DatabaseDumpFile) o;
//
// return id == that.id;
//
// }
//
// @Override
// public String toString() {
// return "DatabaseDumpFile{" +
// "id=" + id +
// ", fileName='" + fileName + '\'' +
// ", createdAt=" + createdAt +
// '}';
// }
//
// public Long getSize() {
// return size;
// }
//
// public void setSize(Long size) {
// this.size = size;
// }
// }
// Path: src/test/java/com/orange/clara/cloud/servicedbdumper/fake/dbdumper/mocked/DeleterMock.java
import com.orange.clara.cloud.servicedbdumper.dbdumper.Deleter;
import com.orange.clara.cloud.servicedbdumper.model.DatabaseDumpFile;
import com.orange.clara.cloud.servicedbdumper.model.DbDumperServiceInstance;
package com.orange.clara.cloud.servicedbdumper.fake.dbdumper.mocked;
/**
* Copyright (C) 2016 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 24/03/2016
*/
public class DeleterMock implements Deleter {
private Integer numberCallDelete = 0;
public Integer getNumberCallDelete() {
return numberCallDelete;
}
public void resetNumberCallDelete() {
numberCallDelete = 0;
}
@Override
public void deleteAll(DbDumperServiceInstance dbDumperServiceInstance) { | for (DatabaseDumpFile databaseDumpFile : dbDumperServiceInstance.getDatabaseDumpFiles()) { |
orange-cloudfoundry/db-dumper-service | src/main/java/com/orange/clara/cloud/servicedbdumper/model/DatabaseDumpFile.java | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/converter/MetadataConverter.java
// @Converter
// public class MetadataConverter implements AttributeConverter<Metadata, String> {
// @Override
// public String convertToDatabaseColumn(Metadata metadata) {
// if (metadata == null) {
// return null;
// }
// ObjectMapper objectMapper = new ObjectMapper();
// try {
// return objectMapper.writeValueAsString(metadata);
// } catch (JsonProcessingException e) {
// throw new RuntimeException(e.getMessage(), e);
// }
// }
//
// @Override
// public Metadata convertToEntityAttribute(String metadataInJson) {
// if (metadataInJson == null) {
// return null;
// }
// ObjectMapper objectMapper = new ObjectMapper();
// try {
// return objectMapper.readValue(metadataInJson, Metadata.class);
// } catch (IOException e) {
// throw new RuntimeException(e.getMessage(), e);
// }
// }
// }
| import com.orange.clara.cloud.servicedbdumper.converter.CryptoConverter;
import com.orange.clara.cloud.servicedbdumper.converter.MetadataConverter;
import javax.persistence.*;
import java.io.File;
import java.util.Calendar;
import java.util.Date; | package com.orange.clara.cloud.servicedbdumper.model;
/**
* Copyright (C) 2015 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 03/06/2015
*/
@Entity
public class DatabaseDumpFile {
protected String user;
@Convert(converter = CryptoConverter.class)
protected String password;
protected Boolean showable;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String fileName;
@Column(name = "created_at")
private Date createdAt;
@Column(name = "deleted_at")
private Date deletedAt;
@ManyToOne
@JoinColumn(name = "service_instance_id")
private DbDumperServiceInstance dbDumperServiceInstance;
| // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/converter/MetadataConverter.java
// @Converter
// public class MetadataConverter implements AttributeConverter<Metadata, String> {
// @Override
// public String convertToDatabaseColumn(Metadata metadata) {
// if (metadata == null) {
// return null;
// }
// ObjectMapper objectMapper = new ObjectMapper();
// try {
// return objectMapper.writeValueAsString(metadata);
// } catch (JsonProcessingException e) {
// throw new RuntimeException(e.getMessage(), e);
// }
// }
//
// @Override
// public Metadata convertToEntityAttribute(String metadataInJson) {
// if (metadataInJson == null) {
// return null;
// }
// ObjectMapper objectMapper = new ObjectMapper();
// try {
// return objectMapper.readValue(metadataInJson, Metadata.class);
// } catch (IOException e) {
// throw new RuntimeException(e.getMessage(), e);
// }
// }
// }
// Path: src/main/java/com/orange/clara/cloud/servicedbdumper/model/DatabaseDumpFile.java
import com.orange.clara.cloud.servicedbdumper.converter.CryptoConverter;
import com.orange.clara.cloud.servicedbdumper.converter.MetadataConverter;
import javax.persistence.*;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
package com.orange.clara.cloud.servicedbdumper.model;
/**
* Copyright (C) 2015 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 03/06/2015
*/
@Entity
public class DatabaseDumpFile {
protected String user;
@Convert(converter = CryptoConverter.class)
protected String password;
protected Boolean showable;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String fileName;
@Column(name = "created_at")
private Date createdAt;
@Column(name = "deleted_at")
private Date deletedAt;
@ManyToOne
@JoinColumn(name = "service_instance_id")
private DbDumperServiceInstance dbDumperServiceInstance;
| @Convert(converter = MetadataConverter.class) |
orange-cloudfoundry/db-dumper-service | src/test/java/com/orange/clara/cloud/servicedbdumper/security/AccessManagerTest.java | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/exception/UserAccessRightException.java
// public class UserAccessRightException extends Exception {
//
// public UserAccessRightException(String message) {
// super(message);
// }
//
// public UserAccessRightException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import com.google.common.collect.Lists;
import com.orange.clara.cloud.servicedbdumper.exception.UserAccessRightException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Spy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import java.util.Collection;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks; | package com.orange.clara.cloud.servicedbdumper.security;
/**
* Copyright (C) 2016 Arthur Halet
* <p>
* This software is distributed under the terms and conditions of the 'MIT'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'http://opensource.org/licenses/MIT'.
* <p>
* Author: Arthur Halet
* Date: 22/03/2016
*/
public class AccessManagerTest {
@Spy
AccessManager accessManager;
@Before
public void init() {
initMocks(this);
}
@Test | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/exception/UserAccessRightException.java
// public class UserAccessRightException extends Exception {
//
// public UserAccessRightException(String message) {
// super(message);
// }
//
// public UserAccessRightException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/test/java/com/orange/clara/cloud/servicedbdumper/security/AccessManagerTest.java
import com.google.common.collect.Lists;
import com.orange.clara.cloud.servicedbdumper.exception.UserAccessRightException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Spy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import java.util.Collection;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
package com.orange.clara.cloud.servicedbdumper.security;
/**
* Copyright (C) 2016 Arthur Halet
* <p>
* This software is distributed under the terms and conditions of the 'MIT'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'http://opensource.org/licenses/MIT'.
* <p>
* Author: Arthur Halet
* Date: 22/03/2016
*/
public class AccessManagerTest {
@Spy
AccessManager accessManager;
@Before
public void init() {
initMocks(this);
}
@Test | public void when_check_if_user_is_admin_and_there_is_no_security_context_it_should_return_that_user_is_not_an_admin() throws UserAccessRightException { |
orange-cloudfoundry/db-dumper-service | src/main/java/com/orange/clara/cloud/servicedbdumper/metric/DbDumperMetrics.java | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/repo/DbDumperServiceInstanceBindingRepo.java
// @Repository
// public interface DbDumperServiceInstanceBindingRepo extends PagingAndSortingRepository<DbDumperServiceInstanceBinding, String> {
// Long deleteByDbDumperServiceInstance(DbDumperServiceInstance dbDumperServiceInstance);
// }
| import com.google.common.collect.Lists;
import com.orange.clara.cloud.servicedbdumper.model.JobEvent;
import com.orange.clara.cloud.servicedbdumper.model.JobType;
import com.orange.clara.cloud.servicedbdumper.repo.DatabaseDumpFileRepo;
import com.orange.clara.cloud.servicedbdumper.repo.DbDumperServiceInstanceBindingRepo;
import com.orange.clara.cloud.servicedbdumper.repo.DbDumperServiceInstanceRepo;
import com.orange.clara.cloud.servicedbdumper.repo.JobRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.PublicMetrics;
import org.springframework.boot.actuate.metrics.Metric;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List; | package com.orange.clara.cloud.servicedbdumper.metric;
/**
* Copyright (C) 2016 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 21/09/2016
*/
@Service
public class DbDumperMetrics implements PublicMetrics {
private final String namespace = "dbdumper";
@Autowired
private JobRepo jobRepo;
@Autowired
private DatabaseDumpFileRepo dumpFileRepo;
@Autowired
private DbDumperServiceInstanceRepo serviceInstanceRepo;
@Autowired | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/repo/DbDumperServiceInstanceBindingRepo.java
// @Repository
// public interface DbDumperServiceInstanceBindingRepo extends PagingAndSortingRepository<DbDumperServiceInstanceBinding, String> {
// Long deleteByDbDumperServiceInstance(DbDumperServiceInstance dbDumperServiceInstance);
// }
// Path: src/main/java/com/orange/clara/cloud/servicedbdumper/metric/DbDumperMetrics.java
import com.google.common.collect.Lists;
import com.orange.clara.cloud.servicedbdumper.model.JobEvent;
import com.orange.clara.cloud.servicedbdumper.model.JobType;
import com.orange.clara.cloud.servicedbdumper.repo.DatabaseDumpFileRepo;
import com.orange.clara.cloud.servicedbdumper.repo.DbDumperServiceInstanceBindingRepo;
import com.orange.clara.cloud.servicedbdumper.repo.DbDumperServiceInstanceRepo;
import com.orange.clara.cloud.servicedbdumper.repo.JobRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.PublicMetrics;
import org.springframework.boot.actuate.metrics.Metric;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
package com.orange.clara.cloud.servicedbdumper.metric;
/**
* Copyright (C) 2016 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 21/09/2016
*/
@Service
public class DbDumperMetrics implements PublicMetrics {
private final String namespace = "dbdumper";
@Autowired
private JobRepo jobRepo;
@Autowired
private DatabaseDumpFileRepo dumpFileRepo;
@Autowired
private DbDumperServiceInstanceRepo serviceInstanceRepo;
@Autowired | private DbDumperServiceInstanceBindingRepo serviceInstanceBindingRepo; |
orange-cloudfoundry/db-dumper-service | src/main/java/com/orange/clara/cloud/servicedbdumper/config/AppConfig.java | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/security/useraccess/DefaultUserAccessRight.java
// public class DefaultUserAccessRight implements UserAccessRight {
// @Override
// public Boolean haveAccessToServiceInstance(String serviceInstanceId) {
// return true;
// }
//
// @Override
// public Boolean haveAccessToServiceInstance(DatabaseRef databaseRef) throws UserAccessRightException {
// return true;
// }
//
// @Override
// public Boolean haveAccessToServiceInstance(DbDumperServiceInstance dbDumperServiceInstance) throws UserAccessRightException {
// return true;
// }
// }
| import com.orange.clara.cloud.servicedbdumper.cloudfoundry.CloudFoundryClientFactory;
import com.orange.clara.cloud.servicedbdumper.security.useraccess.CloudFoundryUserAccessRight;
import com.orange.clara.cloud.servicedbdumper.security.useraccess.DefaultUserAccessRight;
import com.orange.clara.cloud.servicedbdumper.security.useraccess.UserAccessRight;
import com.orange.clara.cloud.servicedbdumper.service.servicekey.CloudFoundryServiceKeyManager;
import com.orange.clara.cloud.servicedbdumper.service.servicekey.NoServiceKeyManager;
import com.orange.clara.cloud.servicedbdumper.service.servicekey.ServiceKeyManager;
import org.cloudfoundry.client.lib.CloudFoundryClient;
import org.cloudfoundry.client.lib.domain.CloudOrganization;
import org.cloudfoundry.client.lib.domain.CloudSpace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import java.net.MalformedURLException;
import java.util.regex.Pattern; | }
@Bean
public ServiceKeyManager serviceKeyManager() {
if (this.cfAdminUser == null
|| this.cfAdminUser.isEmpty()
|| this.cfAdminPassword == null
|| this.cfAdminPassword.isEmpty()
|| this.cloudControllerUrl == null
|| this.cloudControllerUrl.isEmpty()
|| this.noCloudFoundryAccess) {
return new NoServiceKeyManager();
}
return new CloudFoundryServiceKeyManager();
}
@Bean
public String dateFormat() {
return this.dateFormat;
}
@Bean(name = "userAccessRight")
@Profile("uaa")
public UserAccessRight getCloudFoundryUserAccessRight() {
return new CloudFoundryUserAccessRight();
}
@Bean(name = "userAccessRight")
@Profile("!uaa")
public UserAccessRight getDefaultUserAccessRight() { | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/security/useraccess/DefaultUserAccessRight.java
// public class DefaultUserAccessRight implements UserAccessRight {
// @Override
// public Boolean haveAccessToServiceInstance(String serviceInstanceId) {
// return true;
// }
//
// @Override
// public Boolean haveAccessToServiceInstance(DatabaseRef databaseRef) throws UserAccessRightException {
// return true;
// }
//
// @Override
// public Boolean haveAccessToServiceInstance(DbDumperServiceInstance dbDumperServiceInstance) throws UserAccessRightException {
// return true;
// }
// }
// Path: src/main/java/com/orange/clara/cloud/servicedbdumper/config/AppConfig.java
import com.orange.clara.cloud.servicedbdumper.cloudfoundry.CloudFoundryClientFactory;
import com.orange.clara.cloud.servicedbdumper.security.useraccess.CloudFoundryUserAccessRight;
import com.orange.clara.cloud.servicedbdumper.security.useraccess.DefaultUserAccessRight;
import com.orange.clara.cloud.servicedbdumper.security.useraccess.UserAccessRight;
import com.orange.clara.cloud.servicedbdumper.service.servicekey.CloudFoundryServiceKeyManager;
import com.orange.clara.cloud.servicedbdumper.service.servicekey.NoServiceKeyManager;
import com.orange.clara.cloud.servicedbdumper.service.servicekey.ServiceKeyManager;
import org.cloudfoundry.client.lib.CloudFoundryClient;
import org.cloudfoundry.client.lib.domain.CloudOrganization;
import org.cloudfoundry.client.lib.domain.CloudSpace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import java.net.MalformedURLException;
import java.util.regex.Pattern;
}
@Bean
public ServiceKeyManager serviceKeyManager() {
if (this.cfAdminUser == null
|| this.cfAdminUser.isEmpty()
|| this.cfAdminPassword == null
|| this.cfAdminPassword.isEmpty()
|| this.cloudControllerUrl == null
|| this.cloudControllerUrl.isEmpty()
|| this.noCloudFoundryAccess) {
return new NoServiceKeyManager();
}
return new CloudFoundryServiceKeyManager();
}
@Bean
public String dateFormat() {
return this.dateFormat;
}
@Bean(name = "userAccessRight")
@Profile("uaa")
public UserAccessRight getCloudFoundryUserAccessRight() {
return new CloudFoundryUserAccessRight();
}
@Bean(name = "userAccessRight")
@Profile("!uaa")
public UserAccessRight getDefaultUserAccessRight() { | return new DefaultUserAccessRight(); |
orange-cloudfoundry/db-dumper-service | src/test/java/com/orange/clara/cloud/servicedbdumper/fake/cloudservicekey/MockCloudServiceKey.java | // Path: src/test/java/com/orange/clara/cloud/servicedbdumper/fake/cloudservice/MockCloudService.java
// public class MockCloudService extends CloudService {
//
//
// public MockCloudService(String serviceName) {
// super();
// this.setName(serviceName);
// this.setLabel("fakelabel");
// this.setPlan("fakeplan");
// this.setProvider("fakeprovider");
// this.setVersion("0.0.1");
// this.setMeta(this.generateMeta());
// }
//
// private Meta generateMeta() {
// return new Meta(UUID.randomUUID(), new Date(), new Date());
// }
// }
| import com.orange.clara.cloud.servicedbdumper.fake.cloudservice.MockCloudService;
import org.cloudfoundry.client.lib.domain.CloudServiceKey;
import java.util.Date;
import java.util.Map;
import java.util.UUID; | package com.orange.clara.cloud.servicedbdumper.fake.cloudservicekey;
/**
* Copyright (C) 2016 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 29/02/2016
*/
public class MockCloudServiceKey extends CloudServiceKey {
public MockCloudServiceKey(Map<String, Object> credentials, String serviceName) {
super();
this.setCredentials(credentials);
this.setMeta(this.generateMeta());
this.setName("fakeservicekey"); | // Path: src/test/java/com/orange/clara/cloud/servicedbdumper/fake/cloudservice/MockCloudService.java
// public class MockCloudService extends CloudService {
//
//
// public MockCloudService(String serviceName) {
// super();
// this.setName(serviceName);
// this.setLabel("fakelabel");
// this.setPlan("fakeplan");
// this.setProvider("fakeprovider");
// this.setVersion("0.0.1");
// this.setMeta(this.generateMeta());
// }
//
// private Meta generateMeta() {
// return new Meta(UUID.randomUUID(), new Date(), new Date());
// }
// }
// Path: src/test/java/com/orange/clara/cloud/servicedbdumper/fake/cloudservicekey/MockCloudServiceKey.java
import com.orange.clara.cloud.servicedbdumper.fake.cloudservice.MockCloudService;
import org.cloudfoundry.client.lib.domain.CloudServiceKey;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
package com.orange.clara.cloud.servicedbdumper.fake.cloudservicekey;
/**
* Copyright (C) 2016 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 29/02/2016
*/
public class MockCloudServiceKey extends CloudServiceKey {
public MockCloudServiceKey(Map<String, Object> credentials, String serviceName) {
super();
this.setCredentials(credentials);
this.setMeta(this.generateMeta());
this.setName("fakeservicekey"); | this.setService(new MockCloudService(serviceName)); |
orange-cloudfoundry/db-dumper-service | src/test/java/com/orange/clara/cloud/servicedbdumper/fake/configuration/DbDumperConfigContextMock.java | // Path: src/test/java/com/orange/clara/cloud/servicedbdumper/fake/dbdumper/mocked/DeleterMock.java
// public class DeleterMock implements Deleter {
//
// private Integer numberCallDelete = 0;
//
// public Integer getNumberCallDelete() {
// return numberCallDelete;
// }
//
// public void resetNumberCallDelete() {
// numberCallDelete = 0;
// }
//
// @Override
// public void deleteAll(DbDumperServiceInstance dbDumperServiceInstance) {
// for (DatabaseDumpFile databaseDumpFile : dbDumperServiceInstance.getDatabaseDumpFiles()) {
// this.delete(databaseDumpFile);
// }
// }
//
// @Override
// public void delete(DatabaseDumpFile databaseDumpFile) {
// numberCallDelete++;
// }
// }
| import com.orange.clara.cloud.servicedbdumper.dbdumper.Deleter;
import com.orange.clara.cloud.servicedbdumper.fake.dbdumper.mocked.DeleterMock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile; | package com.orange.clara.cloud.servicedbdumper.fake.configuration;
/**
* Copyright (C) 2016 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 24/03/2016
*/
@Configuration
@Profile("test-controller")
public class DbDumperConfigContextMock {
@Bean
public Deleter deleter() { | // Path: src/test/java/com/orange/clara/cloud/servicedbdumper/fake/dbdumper/mocked/DeleterMock.java
// public class DeleterMock implements Deleter {
//
// private Integer numberCallDelete = 0;
//
// public Integer getNumberCallDelete() {
// return numberCallDelete;
// }
//
// public void resetNumberCallDelete() {
// numberCallDelete = 0;
// }
//
// @Override
// public void deleteAll(DbDumperServiceInstance dbDumperServiceInstance) {
// for (DatabaseDumpFile databaseDumpFile : dbDumperServiceInstance.getDatabaseDumpFiles()) {
// this.delete(databaseDumpFile);
// }
// }
//
// @Override
// public void delete(DatabaseDumpFile databaseDumpFile) {
// numberCallDelete++;
// }
// }
// Path: src/test/java/com/orange/clara/cloud/servicedbdumper/fake/configuration/DbDumperConfigContextMock.java
import com.orange.clara.cloud.servicedbdumper.dbdumper.Deleter;
import com.orange.clara.cloud.servicedbdumper.fake.dbdumper.mocked.DeleterMock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
package com.orange.clara.cloud.servicedbdumper.fake.configuration;
/**
* Copyright (C) 2016 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 24/03/2016
*/
@Configuration
@Profile("test-controller")
public class DbDumperConfigContextMock {
@Bean
public Deleter deleter() { | return new DeleterMock(); |
orange-cloudfoundry/db-dumper-service | src/main/java/com/orange/clara/cloud/servicedbdumper/config/CloudConfig.java | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/filer/s3uploader/UploadS3StreamImpl.java
// public class UploadS3StreamImpl implements UploadS3Stream {
// public final static Integer DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024;//set a chunk to 5MB
// protected Logger logger = LoggerFactory.getLogger(UploadS3StreamImpl.class);
// @Autowired
// @Qualifier(value = "blobStoreContext")
// protected SpringCloudBlobStoreContext blobStoreContext;
// protected S3Client s3Client;
// @Value("${s3.upload.retry:5}")
// protected int retry;
// private Integer chunkSize = DEFAULT_CHUNK_SIZE; //set a chunk to 5MB
//
// @PostConstruct
// protected void injectS3Client() {
// this.s3Client = this.blobStoreContext.unwrapApi(S3Client.class);
// }
//
// @Override
// public String upload(InputStream content, Blob blob) throws IOException {
// String key = blob.getMetadata().getName();
// String bucketName = this.blobStoreContext.getBucketName();
// ContentMetadata metadata = blob.getMetadata().getContentMetadata();
// ObjectMetadataBuilder builder = ObjectMetadataBuilder.create().key(key)
// .contentType(MediaType.OCTET_STREAM.toString())
// .contentDisposition(key)
// .contentEncoding(metadata.getContentEncoding())
// .contentLanguage(metadata.getContentLanguage())
// .userMetadata(blob.getMetadata().getUserMetadata());
// String uploadId = this.s3Client.initiateMultipartUpload(bucketName, builder.build());
// Integer partNum = 1;
// Payload part = null;
// int bytesRead = 0;
// byte[] chunk = null;
// boolean shouldContinue = true;
// SortedMap<Integer, String> etags = Maps.newTreeMap();
// try {
// while (shouldContinue) {
// chunk = new byte[chunkSize];
// bytesRead = ByteStreams.read(content, chunk, 0, chunk.length);
// if (bytesRead != chunk.length) {
// shouldContinue = false;
// chunk = Arrays.copyOf(chunk, bytesRead);
// if (chunk.length == 0) {
// //something from jvm causing memory leak, we try to help jvm which seems working.
// //but PLEASE DON'T REPLICATE AT HOME !
// chunk = null;
// part = null;
// System.gc();
// //
// break;
// }
// }
// part = new ByteArrayPayload(chunk);
// prepareUploadPart(bucketName, key, uploadId, partNum, part, etags);
// partNum++;
// //something from jvm causing memory leak, we try to help jvm which seems working.
// //but PLEASE DON'T REPLICATE AT HOME !
// chunk = null;
// part = null;
// System.gc();
// //
// }
// return this.completeMultipartUpload(bucketName, key, uploadId, etags);
// } catch (RuntimeException ex) {
// this.s3Client.abortMultipartUpload(bucketName, key, uploadId);
// throw ex;
// }
// }
//
// protected String completeMultipartUpload(String bucketName, String key, String uploadId, Map<Integer, String> parts) {
// int i = 1;
// while (true) {
// try {
// return this.s3Client.completeMultipartUpload(bucketName, key, uploadId, parts);
// } catch (Exception e) {
// logger.warn("Retry {} to complete upload on S3.", i);
// if (i >= retry) {
// throw e;
// }
// }
// i++;
// }
// }
//
// protected void prepareUploadPart(String container, String key, String uploadId, int numPart, Payload chunkedPart, SortedMap<Integer, String> etags) {
// String eTag = null;
// int i = 1;
// while (true) {
// try {
// eTag = s3Client.uploadPart(container, key, numPart, uploadId, chunkedPart);
// etags.put(numPart, eTag);
// break;
// } catch (Exception e) {
// logger.warn("Retry {}/{} to upload on S3 for container {}.", i, retry, container);
// if (i >= retry) {
// throw e;
// }
// }
// i++;
// }
//
// }
//
// public Integer getChunkSize() {
// return chunkSize;
// }
//
// public void setChunkSize(Integer chunkSize) {
// this.chunkSize = chunkSize;
// }
// }
| import com.orange.clara.cloud.servicedbdumper.filer.s3uploader.UploadS3Stream;
import com.orange.clara.cloud.servicedbdumper.filer.s3uploader.UploadS3StreamImpl;
import com.orange.spring.cloud.connector.s3.core.jcloudswrappers.SpringCloudBlobStore;
import com.orange.spring.cloud.connector.s3.core.jcloudswrappers.SpringCloudBlobStoreContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.config.java.AbstractCloudConfig;
import org.springframework.cloud.config.java.ServiceScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile; | package com.orange.clara.cloud.servicedbdumper.config;
/**
* Copyright (C) 2015 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 03/06/2015
*/
@Configuration
@Profile({"core", "s3"})
@ServiceScan
public class CloudConfig extends AbstractCloudConfig {
@Autowired
private SpringCloudBlobStoreContext springCloudBlobStoreContext;
@Bean
public SpringCloudBlobStoreContext blobStoreContext() {
return this.springCloudBlobStoreContext;
}
@Bean
public SpringCloudBlobStore blobStore() {
return this.blobStoreContext().getSpringCloudBlobStore();
}
@Bean
public UploadS3Stream uploadS3Stream() { | // Path: src/main/java/com/orange/clara/cloud/servicedbdumper/filer/s3uploader/UploadS3StreamImpl.java
// public class UploadS3StreamImpl implements UploadS3Stream {
// public final static Integer DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024;//set a chunk to 5MB
// protected Logger logger = LoggerFactory.getLogger(UploadS3StreamImpl.class);
// @Autowired
// @Qualifier(value = "blobStoreContext")
// protected SpringCloudBlobStoreContext blobStoreContext;
// protected S3Client s3Client;
// @Value("${s3.upload.retry:5}")
// protected int retry;
// private Integer chunkSize = DEFAULT_CHUNK_SIZE; //set a chunk to 5MB
//
// @PostConstruct
// protected void injectS3Client() {
// this.s3Client = this.blobStoreContext.unwrapApi(S3Client.class);
// }
//
// @Override
// public String upload(InputStream content, Blob blob) throws IOException {
// String key = blob.getMetadata().getName();
// String bucketName = this.blobStoreContext.getBucketName();
// ContentMetadata metadata = blob.getMetadata().getContentMetadata();
// ObjectMetadataBuilder builder = ObjectMetadataBuilder.create().key(key)
// .contentType(MediaType.OCTET_STREAM.toString())
// .contentDisposition(key)
// .contentEncoding(metadata.getContentEncoding())
// .contentLanguage(metadata.getContentLanguage())
// .userMetadata(blob.getMetadata().getUserMetadata());
// String uploadId = this.s3Client.initiateMultipartUpload(bucketName, builder.build());
// Integer partNum = 1;
// Payload part = null;
// int bytesRead = 0;
// byte[] chunk = null;
// boolean shouldContinue = true;
// SortedMap<Integer, String> etags = Maps.newTreeMap();
// try {
// while (shouldContinue) {
// chunk = new byte[chunkSize];
// bytesRead = ByteStreams.read(content, chunk, 0, chunk.length);
// if (bytesRead != chunk.length) {
// shouldContinue = false;
// chunk = Arrays.copyOf(chunk, bytesRead);
// if (chunk.length == 0) {
// //something from jvm causing memory leak, we try to help jvm which seems working.
// //but PLEASE DON'T REPLICATE AT HOME !
// chunk = null;
// part = null;
// System.gc();
// //
// break;
// }
// }
// part = new ByteArrayPayload(chunk);
// prepareUploadPart(bucketName, key, uploadId, partNum, part, etags);
// partNum++;
// //something from jvm causing memory leak, we try to help jvm which seems working.
// //but PLEASE DON'T REPLICATE AT HOME !
// chunk = null;
// part = null;
// System.gc();
// //
// }
// return this.completeMultipartUpload(bucketName, key, uploadId, etags);
// } catch (RuntimeException ex) {
// this.s3Client.abortMultipartUpload(bucketName, key, uploadId);
// throw ex;
// }
// }
//
// protected String completeMultipartUpload(String bucketName, String key, String uploadId, Map<Integer, String> parts) {
// int i = 1;
// while (true) {
// try {
// return this.s3Client.completeMultipartUpload(bucketName, key, uploadId, parts);
// } catch (Exception e) {
// logger.warn("Retry {} to complete upload on S3.", i);
// if (i >= retry) {
// throw e;
// }
// }
// i++;
// }
// }
//
// protected void prepareUploadPart(String container, String key, String uploadId, int numPart, Payload chunkedPart, SortedMap<Integer, String> etags) {
// String eTag = null;
// int i = 1;
// while (true) {
// try {
// eTag = s3Client.uploadPart(container, key, numPart, uploadId, chunkedPart);
// etags.put(numPart, eTag);
// break;
// } catch (Exception e) {
// logger.warn("Retry {}/{} to upload on S3 for container {}.", i, retry, container);
// if (i >= retry) {
// throw e;
// }
// }
// i++;
// }
//
// }
//
// public Integer getChunkSize() {
// return chunkSize;
// }
//
// public void setChunkSize(Integer chunkSize) {
// this.chunkSize = chunkSize;
// }
// }
// Path: src/main/java/com/orange/clara/cloud/servicedbdumper/config/CloudConfig.java
import com.orange.clara.cloud.servicedbdumper.filer.s3uploader.UploadS3Stream;
import com.orange.clara.cloud.servicedbdumper.filer.s3uploader.UploadS3StreamImpl;
import com.orange.spring.cloud.connector.s3.core.jcloudswrappers.SpringCloudBlobStore;
import com.orange.spring.cloud.connector.s3.core.jcloudswrappers.SpringCloudBlobStoreContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.config.java.AbstractCloudConfig;
import org.springframework.cloud.config.java.ServiceScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
package com.orange.clara.cloud.servicedbdumper.config;
/**
* Copyright (C) 2015 Orange
* <p>
* This software is distributed under the terms and conditions of the 'Apache-2.0'
* license which can be found in the file 'LICENSE' in this package distribution
* or at 'https://opensource.org/licenses/Apache-2.0'.
* <p>
* Author: Arthur Halet
* Date: 03/06/2015
*/
@Configuration
@Profile({"core", "s3"})
@ServiceScan
public class CloudConfig extends AbstractCloudConfig {
@Autowired
private SpringCloudBlobStoreContext springCloudBlobStoreContext;
@Bean
public SpringCloudBlobStoreContext blobStoreContext() {
return this.springCloudBlobStoreContext;
}
@Bean
public SpringCloudBlobStore blobStore() {
return this.blobStoreContext().getSpringCloudBlobStore();
}
@Bean
public UploadS3Stream uploadS3Stream() { | return new UploadS3StreamImpl(); |
kalessil/yii2inspections | src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/MissingPropertyAnnotationsInspector.java | // Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/utils/InheritanceChainExtractUtil.java
// final public class InheritanceChainExtractUtil {
// @NotNull
// public static Set<PhpClass> collect(@NotNull PhpClass clazz) {
// final Set<PhpClass> processedItems = new HashSet<>();
//
// if (clazz.isInterface()) {
// processInterface(clazz, processedItems);
// } else {
// processClass(clazz, processedItems);
// }
//
// return processedItems;
// }
//
// private static void processClass(@NotNull PhpClass clazz, @NotNull Set<PhpClass> processed) {
// if (clazz.isInterface()) {
// throw new InvalidParameterException("Interface shall not be provided");
// }
// processed.add(clazz);
//
// /* re-delegate interface handling */
// for (PhpClass anInterface : clazz.getImplementedInterfaces()) {
// processInterface(anInterface, processed);
// }
//
// /* handle parent class */
// if (null != clazz.getSuperClass()) {
// processClass(clazz.getSuperClass(), processed);
// }
// }
//
// private static void processInterface(@NotNull PhpClass clazz, @NotNull Set<PhpClass> processed) {
// if (!clazz.isInterface()) {
// throw new InvalidParameterException("Class shall not be provided");
// }
//
// if (processed.add(clazz)) {
// for (PhpClass parentInterface : clazz.getImplementedInterfaces()) {
// processInterface(parentInterface, processed);
// }
// }
// }
// }
//
// Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/utils/NamedElementUtil.java
// final public class NamedElementUtil {
//
// /** returns name identifier, which is valid for reporting */
// @Nullable
// static public PsiElement getNameIdentifier(@Nullable PsiNameIdentifierOwner element) {
// if (null != element) {
// PsiElement id = element.getNameIdentifier();
// boolean isIdReportable = null != id && id.getTextLength() > 0;
//
// return isIdReportable ? id : null;
// }
//
// return null;
// }
//
// }
| import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;
import com.jetbrains.php.lang.inspections.PhpInspection;
import com.jetbrains.php.lang.psi.PhpPsiElementFactory;
import com.jetbrains.php.lang.psi.elements.*;
import com.jetbrains.php.lang.psi.visitors.PhpElementVisitor;
import com.kalessil.phpStorm.yii2inspections.inspectors.utils.InheritanceChainExtractUtil;
import com.kalessil.phpStorm.yii2inspections.inspectors.utils.NamedElementUtil;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.*; | package com.kalessil.phpStorm.yii2inspections.inspectors;
/*
* This file is part of the Yii2 Inspections package.
*
* Author: Vladimir Reznichenko <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
final public class MissingPropertyAnnotationsInspector extends PhpInspection {
// configuration flags automatically saved by IDE
@SuppressWarnings("WeakerAccess")
public boolean REQUIRE_BOTH_GETTER_SETTER = false;
private static final String messagePattern = "'%p%': properties needs to be annotated";
private static final Set<String> baseObjectClasses = new HashSet<>();
static {
baseObjectClasses.add("\\yii\\base\\Object");
baseObjectClasses.add("\\yii\\base\\BaseObject");
}
@NotNull
public String getShortName() {
return "MissingPropertyAnnotationsInspection";
}
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new PhpElementVisitor() {
@Override
public void visitPhpClass(PhpClass clazz) {
/* check only regular named classes */ | // Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/utils/InheritanceChainExtractUtil.java
// final public class InheritanceChainExtractUtil {
// @NotNull
// public static Set<PhpClass> collect(@NotNull PhpClass clazz) {
// final Set<PhpClass> processedItems = new HashSet<>();
//
// if (clazz.isInterface()) {
// processInterface(clazz, processedItems);
// } else {
// processClass(clazz, processedItems);
// }
//
// return processedItems;
// }
//
// private static void processClass(@NotNull PhpClass clazz, @NotNull Set<PhpClass> processed) {
// if (clazz.isInterface()) {
// throw new InvalidParameterException("Interface shall not be provided");
// }
// processed.add(clazz);
//
// /* re-delegate interface handling */
// for (PhpClass anInterface : clazz.getImplementedInterfaces()) {
// processInterface(anInterface, processed);
// }
//
// /* handle parent class */
// if (null != clazz.getSuperClass()) {
// processClass(clazz.getSuperClass(), processed);
// }
// }
//
// private static void processInterface(@NotNull PhpClass clazz, @NotNull Set<PhpClass> processed) {
// if (!clazz.isInterface()) {
// throw new InvalidParameterException("Class shall not be provided");
// }
//
// if (processed.add(clazz)) {
// for (PhpClass parentInterface : clazz.getImplementedInterfaces()) {
// processInterface(parentInterface, processed);
// }
// }
// }
// }
//
// Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/utils/NamedElementUtil.java
// final public class NamedElementUtil {
//
// /** returns name identifier, which is valid for reporting */
// @Nullable
// static public PsiElement getNameIdentifier(@Nullable PsiNameIdentifierOwner element) {
// if (null != element) {
// PsiElement id = element.getNameIdentifier();
// boolean isIdReportable = null != id && id.getTextLength() > 0;
//
// return isIdReportable ? id : null;
// }
//
// return null;
// }
//
// }
// Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/MissingPropertyAnnotationsInspector.java
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;
import com.jetbrains.php.lang.inspections.PhpInspection;
import com.jetbrains.php.lang.psi.PhpPsiElementFactory;
import com.jetbrains.php.lang.psi.elements.*;
import com.jetbrains.php.lang.psi.visitors.PhpElementVisitor;
import com.kalessil.phpStorm.yii2inspections.inspectors.utils.InheritanceChainExtractUtil;
import com.kalessil.phpStorm.yii2inspections.inspectors.utils.NamedElementUtil;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.*;
package com.kalessil.phpStorm.yii2inspections.inspectors;
/*
* This file is part of the Yii2 Inspections package.
*
* Author: Vladimir Reznichenko <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
final public class MissingPropertyAnnotationsInspector extends PhpInspection {
// configuration flags automatically saved by IDE
@SuppressWarnings("WeakerAccess")
public boolean REQUIRE_BOTH_GETTER_SETTER = false;
private static final String messagePattern = "'%p%': properties needs to be annotated";
private static final Set<String> baseObjectClasses = new HashSet<>();
static {
baseObjectClasses.add("\\yii\\base\\Object");
baseObjectClasses.add("\\yii\\base\\BaseObject");
}
@NotNull
public String getShortName() {
return "MissingPropertyAnnotationsInspection";
}
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new PhpElementVisitor() {
@Override
public void visitPhpClass(PhpClass clazz) {
/* check only regular named classes */ | final PsiElement nameNode = NamedElementUtil.getNameIdentifier(clazz); |
kalessil/yii2inspections | src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/MissingPropertyAnnotationsInspector.java | // Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/utils/InheritanceChainExtractUtil.java
// final public class InheritanceChainExtractUtil {
// @NotNull
// public static Set<PhpClass> collect(@NotNull PhpClass clazz) {
// final Set<PhpClass> processedItems = new HashSet<>();
//
// if (clazz.isInterface()) {
// processInterface(clazz, processedItems);
// } else {
// processClass(clazz, processedItems);
// }
//
// return processedItems;
// }
//
// private static void processClass(@NotNull PhpClass clazz, @NotNull Set<PhpClass> processed) {
// if (clazz.isInterface()) {
// throw new InvalidParameterException("Interface shall not be provided");
// }
// processed.add(clazz);
//
// /* re-delegate interface handling */
// for (PhpClass anInterface : clazz.getImplementedInterfaces()) {
// processInterface(anInterface, processed);
// }
//
// /* handle parent class */
// if (null != clazz.getSuperClass()) {
// processClass(clazz.getSuperClass(), processed);
// }
// }
//
// private static void processInterface(@NotNull PhpClass clazz, @NotNull Set<PhpClass> processed) {
// if (!clazz.isInterface()) {
// throw new InvalidParameterException("Class shall not be provided");
// }
//
// if (processed.add(clazz)) {
// for (PhpClass parentInterface : clazz.getImplementedInterfaces()) {
// processInterface(parentInterface, processed);
// }
// }
// }
// }
//
// Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/utils/NamedElementUtil.java
// final public class NamedElementUtil {
//
// /** returns name identifier, which is valid for reporting */
// @Nullable
// static public PsiElement getNameIdentifier(@Nullable PsiNameIdentifierOwner element) {
// if (null != element) {
// PsiElement id = element.getNameIdentifier();
// boolean isIdReportable = null != id && id.getTextLength() > 0;
//
// return isIdReportable ? id : null;
// }
//
// return null;
// }
//
// }
| import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;
import com.jetbrains.php.lang.inspections.PhpInspection;
import com.jetbrains.php.lang.psi.PhpPsiElementFactory;
import com.jetbrains.php.lang.psi.elements.*;
import com.jetbrains.php.lang.psi.visitors.PhpElementVisitor;
import com.kalessil.phpStorm.yii2inspections.inspectors.utils.InheritanceChainExtractUtil;
import com.kalessil.phpStorm.yii2inspections.inspectors.utils.NamedElementUtil;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.*; | package com.kalessil.phpStorm.yii2inspections.inspectors;
/*
* This file is part of the Yii2 Inspections package.
*
* Author: Vladimir Reznichenko <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
final public class MissingPropertyAnnotationsInspector extends PhpInspection {
// configuration flags automatically saved by IDE
@SuppressWarnings("WeakerAccess")
public boolean REQUIRE_BOTH_GETTER_SETTER = false;
private static final String messagePattern = "'%p%': properties needs to be annotated";
private static final Set<String> baseObjectClasses = new HashSet<>();
static {
baseObjectClasses.add("\\yii\\base\\Object");
baseObjectClasses.add("\\yii\\base\\BaseObject");
}
@NotNull
public String getShortName() {
return "MissingPropertyAnnotationsInspection";
}
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new PhpElementVisitor() {
@Override
public void visitPhpClass(PhpClass clazz) {
/* check only regular named classes */
final PsiElement nameNode = NamedElementUtil.getNameIdentifier(clazz);
if (null == nameNode) {
return;
}
/* check if the class inherited from yii\base\Object */
boolean supportsPropertyFeature = false; | // Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/utils/InheritanceChainExtractUtil.java
// final public class InheritanceChainExtractUtil {
// @NotNull
// public static Set<PhpClass> collect(@NotNull PhpClass clazz) {
// final Set<PhpClass> processedItems = new HashSet<>();
//
// if (clazz.isInterface()) {
// processInterface(clazz, processedItems);
// } else {
// processClass(clazz, processedItems);
// }
//
// return processedItems;
// }
//
// private static void processClass(@NotNull PhpClass clazz, @NotNull Set<PhpClass> processed) {
// if (clazz.isInterface()) {
// throw new InvalidParameterException("Interface shall not be provided");
// }
// processed.add(clazz);
//
// /* re-delegate interface handling */
// for (PhpClass anInterface : clazz.getImplementedInterfaces()) {
// processInterface(anInterface, processed);
// }
//
// /* handle parent class */
// if (null != clazz.getSuperClass()) {
// processClass(clazz.getSuperClass(), processed);
// }
// }
//
// private static void processInterface(@NotNull PhpClass clazz, @NotNull Set<PhpClass> processed) {
// if (!clazz.isInterface()) {
// throw new InvalidParameterException("Class shall not be provided");
// }
//
// if (processed.add(clazz)) {
// for (PhpClass parentInterface : clazz.getImplementedInterfaces()) {
// processInterface(parentInterface, processed);
// }
// }
// }
// }
//
// Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/utils/NamedElementUtil.java
// final public class NamedElementUtil {
//
// /** returns name identifier, which is valid for reporting */
// @Nullable
// static public PsiElement getNameIdentifier(@Nullable PsiNameIdentifierOwner element) {
// if (null != element) {
// PsiElement id = element.getNameIdentifier();
// boolean isIdReportable = null != id && id.getTextLength() > 0;
//
// return isIdReportable ? id : null;
// }
//
// return null;
// }
//
// }
// Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/MissingPropertyAnnotationsInspector.java
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;
import com.jetbrains.php.lang.inspections.PhpInspection;
import com.jetbrains.php.lang.psi.PhpPsiElementFactory;
import com.jetbrains.php.lang.psi.elements.*;
import com.jetbrains.php.lang.psi.visitors.PhpElementVisitor;
import com.kalessil.phpStorm.yii2inspections.inspectors.utils.InheritanceChainExtractUtil;
import com.kalessil.phpStorm.yii2inspections.inspectors.utils.NamedElementUtil;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.*;
package com.kalessil.phpStorm.yii2inspections.inspectors;
/*
* This file is part of the Yii2 Inspections package.
*
* Author: Vladimir Reznichenko <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
final public class MissingPropertyAnnotationsInspector extends PhpInspection {
// configuration flags automatically saved by IDE
@SuppressWarnings("WeakerAccess")
public boolean REQUIRE_BOTH_GETTER_SETTER = false;
private static final String messagePattern = "'%p%': properties needs to be annotated";
private static final Set<String> baseObjectClasses = new HashSet<>();
static {
baseObjectClasses.add("\\yii\\base\\Object");
baseObjectClasses.add("\\yii\\base\\BaseObject");
}
@NotNull
public String getShortName() {
return "MissingPropertyAnnotationsInspection";
}
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new PhpElementVisitor() {
@Override
public void visitPhpClass(PhpClass clazz) {
/* check only regular named classes */
final PsiElement nameNode = NamedElementUtil.getNameIdentifier(clazz);
if (null == nameNode) {
return;
}
/* check if the class inherited from yii\base\Object */
boolean supportsPropertyFeature = false; | final Set<PhpClass> parents = InheritanceChainExtractUtil.collect(clazz); |
kalessil/yii2inspections | src/main/java/com/kalessil/phpStorm/yii2inspections/codeInsight/TranslationAutocompleteContributor.java | // Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/utils/StringLiteralExtractUtil.java
// final public class StringLiteralExtractUtil {
// @Nullable
// private static PsiElement getExpressionTroughParenthesis(@Nullable PsiElement expression) {
// if (!(expression instanceof ParenthesizedExpression)) {
// return expression;
// }
//
// PsiElement innerExpression = ((ParenthesizedExpression) expression).getArgument();
// while (innerExpression instanceof ParenthesizedExpression) {
// innerExpression = ((ParenthesizedExpression) innerExpression).getArgument();
// }
//
// return innerExpression;
// }
//
// @Nullable
// private static Function getScope(@NotNull PsiElement expression) {
// PsiElement parent = expression.getParent();
// while (null != parent && !(parent instanceof PhpFile)) {
// if (parent instanceof Function) {
// return (Function) parent;
// }
//
// parent = parent.getParent();
// }
//
// return null;
// }
//
// @Nullable
// public static StringLiteralExpression resolveAsStringLiteral(@Nullable PsiElement expression, boolean resolve) {
// if (null == expression) {
// return null;
// }
// expression = getExpressionTroughParenthesis(expression);
//
// if (expression instanceof StringLiteralExpression) {
// return (StringLiteralExpression) expression;
// }
//
// if (expression instanceof FieldReference || expression instanceof ClassConstantReference) {
// final Field fieldOrConstant = resolve ? (Field) ((MemberReference) expression).resolve() : null;
// if (null != fieldOrConstant && fieldOrConstant.getDefaultValue() instanceof StringLiteralExpression) {
// return (StringLiteralExpression) fieldOrConstant.getDefaultValue();
// }
// }
//
// if (expression instanceof Variable) {
// final String variable = ((Variable) expression).getName();
// if (!StringUtil.isEmpty(variable)) {
// final Function scope = getScope(expression);
// if (null != scope) {
// final Set<AssignmentExpression> matched = new HashSet<>();
//
// Collection<AssignmentExpression> assignments
// = PsiTreeUtil.findChildrenOfType(scope, AssignmentExpression.class);
// /* collect self-assignments as well */
// for (AssignmentExpression assignment : assignments) {
// if (assignment.getVariable() instanceof Variable && assignment.getValue() instanceof StringLiteralExpression) {
// final String name = assignment.getVariable().getName();
// if (!StringUtil.isEmpty(name) && name.equals(variable)) {
// matched.add(assignment);
// }
// }
// }
// assignments.clear();
//
// if (matched.size() == 1) {
// StringLiteralExpression result = (StringLiteralExpression) matched.iterator().next().getValue();
//
// matched.clear();
// return result;
// }
// matched.clear();
// }
// }
// }
//
// return null;
// }
// }
| import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.ProcessingContext;
import com.intellij.util.indexing.FileBasedIndex;
import com.jetbrains.php.lang.PhpLanguage;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.psi.elements.MethodReference;
import com.jetbrains.php.lang.psi.elements.ParameterList;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import com.kalessil.phpStorm.yii2inspections.inspectors.utils.StringLiteralExtractUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*; | package com.kalessil.phpStorm.yii2inspections.codeInsight;
public class TranslationAutocompleteContributor extends CompletionContributor {
public TranslationAutocompleteContributor() {
final CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(
@NotNull CompletionParameters completionParameters,
ProcessingContext processingContext,
@NotNull CompletionResultSet completionResultSet
) {
/* validate the autocompletion target */
final PsiElement target = completionParameters.getOriginalPosition();
if (target == null || !(target.getParent() instanceof StringLiteralExpression)) {
return;
}
/* suggest only to target code structure */
final StringLiteralExpression parameter = (StringLiteralExpression) target.getParent();
final PsiElement context = parameter.getParent().getParent();
if (!(context instanceof MethodReference)) {
return;
}
final MethodReference reference = (MethodReference) context;
final String name = reference.getName();
final PsiElement[] arguments = reference.getParameters();
if (name == null || arguments.length == 0 || (!name.equals("t") && !name.equals("registerTranslations"))) {
return;
}
/* generate proposals */
final boolean autocompleteCategory = arguments[0] == parameter;
final boolean autocompleteMessage = arguments.length > 1 && arguments[1] == parameter;
if (autocompleteCategory || autocompleteMessage) {
StringLiteralExpression categoryLiteral = null;
if (autocompleteMessage) { | // Path: src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/utils/StringLiteralExtractUtil.java
// final public class StringLiteralExtractUtil {
// @Nullable
// private static PsiElement getExpressionTroughParenthesis(@Nullable PsiElement expression) {
// if (!(expression instanceof ParenthesizedExpression)) {
// return expression;
// }
//
// PsiElement innerExpression = ((ParenthesizedExpression) expression).getArgument();
// while (innerExpression instanceof ParenthesizedExpression) {
// innerExpression = ((ParenthesizedExpression) innerExpression).getArgument();
// }
//
// return innerExpression;
// }
//
// @Nullable
// private static Function getScope(@NotNull PsiElement expression) {
// PsiElement parent = expression.getParent();
// while (null != parent && !(parent instanceof PhpFile)) {
// if (parent instanceof Function) {
// return (Function) parent;
// }
//
// parent = parent.getParent();
// }
//
// return null;
// }
//
// @Nullable
// public static StringLiteralExpression resolveAsStringLiteral(@Nullable PsiElement expression, boolean resolve) {
// if (null == expression) {
// return null;
// }
// expression = getExpressionTroughParenthesis(expression);
//
// if (expression instanceof StringLiteralExpression) {
// return (StringLiteralExpression) expression;
// }
//
// if (expression instanceof FieldReference || expression instanceof ClassConstantReference) {
// final Field fieldOrConstant = resolve ? (Field) ((MemberReference) expression).resolve() : null;
// if (null != fieldOrConstant && fieldOrConstant.getDefaultValue() instanceof StringLiteralExpression) {
// return (StringLiteralExpression) fieldOrConstant.getDefaultValue();
// }
// }
//
// if (expression instanceof Variable) {
// final String variable = ((Variable) expression).getName();
// if (!StringUtil.isEmpty(variable)) {
// final Function scope = getScope(expression);
// if (null != scope) {
// final Set<AssignmentExpression> matched = new HashSet<>();
//
// Collection<AssignmentExpression> assignments
// = PsiTreeUtil.findChildrenOfType(scope, AssignmentExpression.class);
// /* collect self-assignments as well */
// for (AssignmentExpression assignment : assignments) {
// if (assignment.getVariable() instanceof Variable && assignment.getValue() instanceof StringLiteralExpression) {
// final String name = assignment.getVariable().getName();
// if (!StringUtil.isEmpty(name) && name.equals(variable)) {
// matched.add(assignment);
// }
// }
// }
// assignments.clear();
//
// if (matched.size() == 1) {
// StringLiteralExpression result = (StringLiteralExpression) matched.iterator().next().getValue();
//
// matched.clear();
// return result;
// }
// matched.clear();
// }
// }
// }
//
// return null;
// }
// }
// Path: src/main/java/com/kalessil/phpStorm/yii2inspections/codeInsight/TranslationAutocompleteContributor.java
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.ProcessingContext;
import com.intellij.util.indexing.FileBasedIndex;
import com.jetbrains.php.lang.PhpLanguage;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.psi.elements.MethodReference;
import com.jetbrains.php.lang.psi.elements.ParameterList;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import com.kalessil.phpStorm.yii2inspections.inspectors.utils.StringLiteralExtractUtil;
import org.jetbrains.annotations.NotNull;
import java.util.*;
package com.kalessil.phpStorm.yii2inspections.codeInsight;
public class TranslationAutocompleteContributor extends CompletionContributor {
public TranslationAutocompleteContributor() {
final CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(
@NotNull CompletionParameters completionParameters,
ProcessingContext processingContext,
@NotNull CompletionResultSet completionResultSet
) {
/* validate the autocompletion target */
final PsiElement target = completionParameters.getOriginalPosition();
if (target == null || !(target.getParent() instanceof StringLiteralExpression)) {
return;
}
/* suggest only to target code structure */
final StringLiteralExpression parameter = (StringLiteralExpression) target.getParent();
final PsiElement context = parameter.getParent().getParent();
if (!(context instanceof MethodReference)) {
return;
}
final MethodReference reference = (MethodReference) context;
final String name = reference.getName();
final PsiElement[] arguments = reference.getParameters();
if (name == null || arguments.length == 0 || (!name.equals("t") && !name.equals("registerTranslations"))) {
return;
}
/* generate proposals */
final boolean autocompleteCategory = arguments[0] == parameter;
final boolean autocompleteMessage = arguments.length > 1 && arguments[1] == parameter;
if (autocompleteCategory || autocompleteMessage) {
StringLiteralExpression categoryLiteral = null;
if (autocompleteMessage) { | categoryLiteral = StringLiteralExtractUtil.resolveAsStringLiteral(arguments[0], true); |
kalessil/yii2inspections | src/test/java/com/kalessil/phpStorm/yii2inspections/inspectors/TranslationCallsProcessUtilTest.java | // Path: src/main/java/com/kalessil/phpStorm/yii2inspections/utils/TranslationCallsProcessUtil.java
// final public class TranslationCallsProcessUtil {
//
// /* Returns null if category is not clean or empty string literal or no reasonable messages were found*/
// @Nullable
// static public ProcessingResult process(@NotNull MethodReference reference, boolean resolve) {
// final String name = reference.getName();
// final PsiElement[] params = reference.getParameters();
// if (null == name || params.length < 2 || (!name.equals("t") && !(name.equals("registerTranslations")))) {
// return null;
// }
//
// /* category needs to be resolved and without any injections */
// final StringLiteralExpression categoryLiteral = StringLiteralExtractUtil.resolveAsStringLiteral(params[0], resolve);
// if (null == categoryLiteral || null != categoryLiteral.getFirstPsiChild() || categoryLiteral.getTextLength() <= 2) {
// return null;
// }
//
// final Map<StringLiteralExpression, PsiElement> messages = new HashMap<>();
// if (name.equals("t")) {
// /* 2nd argument expected to be a string literal (possible with injections) */
// final StringLiteralExpression messageLiteral = StringLiteralExtractUtil.resolveAsStringLiteral(params[1], resolve);
// if (null != messageLiteral && messageLiteral.getTextLength() > 2) {
// messages.put(messageLiteral, params[1]);
// }
// }
//
// if (name.equals("registerTranslations") && params[1] instanceof ArrayCreationExpression) {
// /* 2nd argument expected to be an inline array with string literal (possible with injections) */
// for (PsiElement child : params[1].getChildren()) {
// final PsiElement literalCandidate = child.getFirstChild();
// final StringLiteralExpression messageLiteral = StringLiteralExtractUtil.resolveAsStringLiteral(literalCandidate, resolve);
// if (null != messageLiteral && messageLiteral.getTextLength() > 2) {
// messages.put(messageLiteral, literalCandidate);
// }
// }
// }
//
// return 0 == messages.size() ? null : new ProcessingResult(categoryLiteral, messages);
// }
//
// static public class ProcessingResult {
// @Nullable
// private StringLiteralExpression category;
// @Nullable
// private Map<StringLiteralExpression, PsiElement> messages;
//
// ProcessingResult(@NotNull StringLiteralExpression category, @NotNull Map<StringLiteralExpression, PsiElement> messages) {
// this.category = category;
// this.messages = messages;
// }
//
// @NotNull
// public StringLiteralExpression getCategory() {
// if (null == this.category) {
// throw new RuntimeException("The object has been disposed already");
// }
//
// return this.category;
// }
//
// @NotNull
// public Map<StringLiteralExpression, PsiElement> getMessages() {
// if (null == this.messages) {
// throw new RuntimeException("The object has been disposed already");
// }
//
// return this.messages;
// }
//
// public void dispose() {
// if (null != this.messages) {
// this.messages.clear();
// }
//
// this.category = null;
// this.messages = null;
// }
// }
// }
| import com.intellij.openapi.project.Project;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import com.jetbrains.php.lang.psi.PhpPsiElementFactory;
import com.jetbrains.php.lang.psi.elements.MethodReference;
import com.kalessil.phpStorm.yii2inspections.utils.TranslationCallsProcessUtil;
import java.util.HashMap;
import java.util.Map; | package com.kalessil.phpStorm.yii2inspections.inspectors;
public class TranslationCallsProcessUtilTest extends CodeInsightFixtureTestCase {
public void testSingleMessageExtraction() {
Project project = myFixture.getProject();
Map<String, Integer> patterns = new HashMap<>();
patterns.put("Yii::t('yii', \"$x\")", 1);
patterns.put("Yii::t('yii', 'message')", 1);
patterns.put("Yii::t('yii', \"message\")", 1);
patterns.put("$view->registerTranslations('craft', ['message', 'message']);", 2);
for (String pattern : patterns.keySet()) {
MethodReference call = PhpPsiElementFactory.createFromText(project, MethodReference.class, pattern);
assertNotNull(pattern + ": incorrect pattern", call);
| // Path: src/main/java/com/kalessil/phpStorm/yii2inspections/utils/TranslationCallsProcessUtil.java
// final public class TranslationCallsProcessUtil {
//
// /* Returns null if category is not clean or empty string literal or no reasonable messages were found*/
// @Nullable
// static public ProcessingResult process(@NotNull MethodReference reference, boolean resolve) {
// final String name = reference.getName();
// final PsiElement[] params = reference.getParameters();
// if (null == name || params.length < 2 || (!name.equals("t") && !(name.equals("registerTranslations")))) {
// return null;
// }
//
// /* category needs to be resolved and without any injections */
// final StringLiteralExpression categoryLiteral = StringLiteralExtractUtil.resolveAsStringLiteral(params[0], resolve);
// if (null == categoryLiteral || null != categoryLiteral.getFirstPsiChild() || categoryLiteral.getTextLength() <= 2) {
// return null;
// }
//
// final Map<StringLiteralExpression, PsiElement> messages = new HashMap<>();
// if (name.equals("t")) {
// /* 2nd argument expected to be a string literal (possible with injections) */
// final StringLiteralExpression messageLiteral = StringLiteralExtractUtil.resolveAsStringLiteral(params[1], resolve);
// if (null != messageLiteral && messageLiteral.getTextLength() > 2) {
// messages.put(messageLiteral, params[1]);
// }
// }
//
// if (name.equals("registerTranslations") && params[1] instanceof ArrayCreationExpression) {
// /* 2nd argument expected to be an inline array with string literal (possible with injections) */
// for (PsiElement child : params[1].getChildren()) {
// final PsiElement literalCandidate = child.getFirstChild();
// final StringLiteralExpression messageLiteral = StringLiteralExtractUtil.resolveAsStringLiteral(literalCandidate, resolve);
// if (null != messageLiteral && messageLiteral.getTextLength() > 2) {
// messages.put(messageLiteral, literalCandidate);
// }
// }
// }
//
// return 0 == messages.size() ? null : new ProcessingResult(categoryLiteral, messages);
// }
//
// static public class ProcessingResult {
// @Nullable
// private StringLiteralExpression category;
// @Nullable
// private Map<StringLiteralExpression, PsiElement> messages;
//
// ProcessingResult(@NotNull StringLiteralExpression category, @NotNull Map<StringLiteralExpression, PsiElement> messages) {
// this.category = category;
// this.messages = messages;
// }
//
// @NotNull
// public StringLiteralExpression getCategory() {
// if (null == this.category) {
// throw new RuntimeException("The object has been disposed already");
// }
//
// return this.category;
// }
//
// @NotNull
// public Map<StringLiteralExpression, PsiElement> getMessages() {
// if (null == this.messages) {
// throw new RuntimeException("The object has been disposed already");
// }
//
// return this.messages;
// }
//
// public void dispose() {
// if (null != this.messages) {
// this.messages.clear();
// }
//
// this.category = null;
// this.messages = null;
// }
// }
// }
// Path: src/test/java/com/kalessil/phpStorm/yii2inspections/inspectors/TranslationCallsProcessUtilTest.java
import com.intellij.openapi.project.Project;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import com.jetbrains.php.lang.psi.PhpPsiElementFactory;
import com.jetbrains.php.lang.psi.elements.MethodReference;
import com.kalessil.phpStorm.yii2inspections.utils.TranslationCallsProcessUtil;
import java.util.HashMap;
import java.util.Map;
package com.kalessil.phpStorm.yii2inspections.inspectors;
public class TranslationCallsProcessUtilTest extends CodeInsightFixtureTestCase {
public void testSingleMessageExtraction() {
Project project = myFixture.getProject();
Map<String, Integer> patterns = new HashMap<>();
patterns.put("Yii::t('yii', \"$x\")", 1);
patterns.put("Yii::t('yii', 'message')", 1);
patterns.put("Yii::t('yii', \"message\")", 1);
patterns.put("$view->registerTranslations('craft', ['message', 'message']);", 2);
for (String pattern : patterns.keySet()) {
MethodReference call = PhpPsiElementFactory.createFromText(project, MethodReference.class, pattern);
assertNotNull(pattern + ": incorrect pattern", call);
| TranslationCallsProcessUtil.ProcessingResult messages = TranslationCallsProcessUtil.process(call, false); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.