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
state-machine-systems/envy
src/main/java/com/statemachinesystems/envy/Envy.java
// Path: src/main/java/com/statemachinesystems/envy/sources/DelegatingConfigSource.java // public class DelegatingConfigSource implements ConfigSource { // // private final ConfigSource[] sources; // // /** // * Creates a {@link com.statemachinesystems.envy.sources.DelegatingConfigSource} using // * the given component sources in preference order. // * // * @param sources component {@link com.statemachinesystems.envy.ConfigSource}s in preference order // */ // public DelegatingConfigSource(ConfigSource... sources) { // this.sources = sources; // } // // @Override // public String getValue(Parameter parameter) { // for (ConfigSource source : sources) { // String value = source.getValue(parameter); // if (value != null) { // return value; // } // } // return null; // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/EnvironmentVariableConfigSource.java // public class EnvironmentVariableConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getenv(parameter.asEnvironmentVariableName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/SystemPropertyConfigSource.java // public class SystemPropertyConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getProperty(parameter.asSystemPropertyName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/values/ConfigMap.java // public class ConfigMap implements Serializable { // // private final Map<String, ConfigValue> values; // // public ConfigMap(Map<String, ConfigValue> values) { // this.values = values; // } // // public ConfigValue getValue(String methodName) { // return values.get(methodName); // } // // public Set<String> getMethodNames() { // return values.keySet(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConfigMap configMap = (ConfigMap) o; // return Objects.equals(values, configMap.values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // }
import com.statemachinesystems.envy.parsers.*; import com.statemachinesystems.envy.sources.DelegatingConfigSource; import com.statemachinesystems.envy.sources.EnvironmentVariableConfigSource; import com.statemachinesystems.envy.sources.SystemPropertyConfigSource; import com.statemachinesystems.envy.values.ConfigMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;
valueParsers.add(new InetSocketAddressValueParser()); valueParsers.add(new IntegerValueParser()); valueParsers.add(new LongValueParser()); valueParsers.add(new ObjectAsStringValueParser()); valueParsers.add(new PatternValueParser()); valueParsers.add(new PeriodValueParser()); valueParsers.add(new ShortValueParser()); valueParsers.add(new StringValueParser()); valueParsers.add(new UuidValueParser()); valueParsers.add(new UriValueParser()); valueParsers.add(new UrlValueParser()); return Collections.unmodifiableList(valueParsers); } /** * Provides a default {@link com.statemachinesystems.envy.ConfigSource} implementation * that retrieves configuration values from either JVM system properties or * environment variables. * * System properties override environment variables with * equivalent names. * * @return a default {@link com.statemachinesystems.envy.ConfigSource} implementation */ public static ConfigSource defaultConfigSource() { return DEFAULT_CONFIG_SOURCE; } private static final ConfigSource DEFAULT_CONFIG_SOURCE =
// Path: src/main/java/com/statemachinesystems/envy/sources/DelegatingConfigSource.java // public class DelegatingConfigSource implements ConfigSource { // // private final ConfigSource[] sources; // // /** // * Creates a {@link com.statemachinesystems.envy.sources.DelegatingConfigSource} using // * the given component sources in preference order. // * // * @param sources component {@link com.statemachinesystems.envy.ConfigSource}s in preference order // */ // public DelegatingConfigSource(ConfigSource... sources) { // this.sources = sources; // } // // @Override // public String getValue(Parameter parameter) { // for (ConfigSource source : sources) { // String value = source.getValue(parameter); // if (value != null) { // return value; // } // } // return null; // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/EnvironmentVariableConfigSource.java // public class EnvironmentVariableConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getenv(parameter.asEnvironmentVariableName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/SystemPropertyConfigSource.java // public class SystemPropertyConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getProperty(parameter.asSystemPropertyName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/values/ConfigMap.java // public class ConfigMap implements Serializable { // // private final Map<String, ConfigValue> values; // // public ConfigMap(Map<String, ConfigValue> values) { // this.values = values; // } // // public ConfigValue getValue(String methodName) { // return values.get(methodName); // } // // public Set<String> getMethodNames() { // return values.keySet(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConfigMap configMap = (ConfigMap) o; // return Objects.equals(values, configMap.values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // } // Path: src/main/java/com/statemachinesystems/envy/Envy.java import com.statemachinesystems.envy.parsers.*; import com.statemachinesystems.envy.sources.DelegatingConfigSource; import com.statemachinesystems.envy.sources.EnvironmentVariableConfigSource; import com.statemachinesystems.envy.sources.SystemPropertyConfigSource; import com.statemachinesystems.envy.values.ConfigMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; valueParsers.add(new InetSocketAddressValueParser()); valueParsers.add(new IntegerValueParser()); valueParsers.add(new LongValueParser()); valueParsers.add(new ObjectAsStringValueParser()); valueParsers.add(new PatternValueParser()); valueParsers.add(new PeriodValueParser()); valueParsers.add(new ShortValueParser()); valueParsers.add(new StringValueParser()); valueParsers.add(new UuidValueParser()); valueParsers.add(new UriValueParser()); valueParsers.add(new UrlValueParser()); return Collections.unmodifiableList(valueParsers); } /** * Provides a default {@link com.statemachinesystems.envy.ConfigSource} implementation * that retrieves configuration values from either JVM system properties or * environment variables. * * System properties override environment variables with * equivalent names. * * @return a default {@link com.statemachinesystems.envy.ConfigSource} implementation */ public static ConfigSource defaultConfigSource() { return DEFAULT_CONFIG_SOURCE; } private static final ConfigSource DEFAULT_CONFIG_SOURCE =
new DelegatingConfigSource(new SystemPropertyConfigSource(), new EnvironmentVariableConfigSource());
state-machine-systems/envy
src/main/java/com/statemachinesystems/envy/Envy.java
// Path: src/main/java/com/statemachinesystems/envy/sources/DelegatingConfigSource.java // public class DelegatingConfigSource implements ConfigSource { // // private final ConfigSource[] sources; // // /** // * Creates a {@link com.statemachinesystems.envy.sources.DelegatingConfigSource} using // * the given component sources in preference order. // * // * @param sources component {@link com.statemachinesystems.envy.ConfigSource}s in preference order // */ // public DelegatingConfigSource(ConfigSource... sources) { // this.sources = sources; // } // // @Override // public String getValue(Parameter parameter) { // for (ConfigSource source : sources) { // String value = source.getValue(parameter); // if (value != null) { // return value; // } // } // return null; // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/EnvironmentVariableConfigSource.java // public class EnvironmentVariableConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getenv(parameter.asEnvironmentVariableName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/SystemPropertyConfigSource.java // public class SystemPropertyConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getProperty(parameter.asSystemPropertyName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/values/ConfigMap.java // public class ConfigMap implements Serializable { // // private final Map<String, ConfigValue> values; // // public ConfigMap(Map<String, ConfigValue> values) { // this.values = values; // } // // public ConfigValue getValue(String methodName) { // return values.get(methodName); // } // // public Set<String> getMethodNames() { // return values.keySet(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConfigMap configMap = (ConfigMap) o; // return Objects.equals(values, configMap.values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // }
import com.statemachinesystems.envy.parsers.*; import com.statemachinesystems.envy.sources.DelegatingConfigSource; import com.statemachinesystems.envy.sources.EnvironmentVariableConfigSource; import com.statemachinesystems.envy.sources.SystemPropertyConfigSource; import com.statemachinesystems.envy.values.ConfigMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;
valueParsers.add(new InetSocketAddressValueParser()); valueParsers.add(new IntegerValueParser()); valueParsers.add(new LongValueParser()); valueParsers.add(new ObjectAsStringValueParser()); valueParsers.add(new PatternValueParser()); valueParsers.add(new PeriodValueParser()); valueParsers.add(new ShortValueParser()); valueParsers.add(new StringValueParser()); valueParsers.add(new UuidValueParser()); valueParsers.add(new UriValueParser()); valueParsers.add(new UrlValueParser()); return Collections.unmodifiableList(valueParsers); } /** * Provides a default {@link com.statemachinesystems.envy.ConfigSource} implementation * that retrieves configuration values from either JVM system properties or * environment variables. * * System properties override environment variables with * equivalent names. * * @return a default {@link com.statemachinesystems.envy.ConfigSource} implementation */ public static ConfigSource defaultConfigSource() { return DEFAULT_CONFIG_SOURCE; } private static final ConfigSource DEFAULT_CONFIG_SOURCE =
// Path: src/main/java/com/statemachinesystems/envy/sources/DelegatingConfigSource.java // public class DelegatingConfigSource implements ConfigSource { // // private final ConfigSource[] sources; // // /** // * Creates a {@link com.statemachinesystems.envy.sources.DelegatingConfigSource} using // * the given component sources in preference order. // * // * @param sources component {@link com.statemachinesystems.envy.ConfigSource}s in preference order // */ // public DelegatingConfigSource(ConfigSource... sources) { // this.sources = sources; // } // // @Override // public String getValue(Parameter parameter) { // for (ConfigSource source : sources) { // String value = source.getValue(parameter); // if (value != null) { // return value; // } // } // return null; // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/EnvironmentVariableConfigSource.java // public class EnvironmentVariableConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getenv(parameter.asEnvironmentVariableName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/SystemPropertyConfigSource.java // public class SystemPropertyConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getProperty(parameter.asSystemPropertyName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/values/ConfigMap.java // public class ConfigMap implements Serializable { // // private final Map<String, ConfigValue> values; // // public ConfigMap(Map<String, ConfigValue> values) { // this.values = values; // } // // public ConfigValue getValue(String methodName) { // return values.get(methodName); // } // // public Set<String> getMethodNames() { // return values.keySet(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConfigMap configMap = (ConfigMap) o; // return Objects.equals(values, configMap.values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // } // Path: src/main/java/com/statemachinesystems/envy/Envy.java import com.statemachinesystems.envy.parsers.*; import com.statemachinesystems.envy.sources.DelegatingConfigSource; import com.statemachinesystems.envy.sources.EnvironmentVariableConfigSource; import com.statemachinesystems.envy.sources.SystemPropertyConfigSource; import com.statemachinesystems.envy.values.ConfigMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; valueParsers.add(new InetSocketAddressValueParser()); valueParsers.add(new IntegerValueParser()); valueParsers.add(new LongValueParser()); valueParsers.add(new ObjectAsStringValueParser()); valueParsers.add(new PatternValueParser()); valueParsers.add(new PeriodValueParser()); valueParsers.add(new ShortValueParser()); valueParsers.add(new StringValueParser()); valueParsers.add(new UuidValueParser()); valueParsers.add(new UriValueParser()); valueParsers.add(new UrlValueParser()); return Collections.unmodifiableList(valueParsers); } /** * Provides a default {@link com.statemachinesystems.envy.ConfigSource} implementation * that retrieves configuration values from either JVM system properties or * environment variables. * * System properties override environment variables with * equivalent names. * * @return a default {@link com.statemachinesystems.envy.ConfigSource} implementation */ public static ConfigSource defaultConfigSource() { return DEFAULT_CONFIG_SOURCE; } private static final ConfigSource DEFAULT_CONFIG_SOURCE =
new DelegatingConfigSource(new SystemPropertyConfigSource(), new EnvironmentVariableConfigSource());
state-machine-systems/envy
src/main/java/com/statemachinesystems/envy/Envy.java
// Path: src/main/java/com/statemachinesystems/envy/sources/DelegatingConfigSource.java // public class DelegatingConfigSource implements ConfigSource { // // private final ConfigSource[] sources; // // /** // * Creates a {@link com.statemachinesystems.envy.sources.DelegatingConfigSource} using // * the given component sources in preference order. // * // * @param sources component {@link com.statemachinesystems.envy.ConfigSource}s in preference order // */ // public DelegatingConfigSource(ConfigSource... sources) { // this.sources = sources; // } // // @Override // public String getValue(Parameter parameter) { // for (ConfigSource source : sources) { // String value = source.getValue(parameter); // if (value != null) { // return value; // } // } // return null; // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/EnvironmentVariableConfigSource.java // public class EnvironmentVariableConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getenv(parameter.asEnvironmentVariableName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/SystemPropertyConfigSource.java // public class SystemPropertyConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getProperty(parameter.asSystemPropertyName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/values/ConfigMap.java // public class ConfigMap implements Serializable { // // private final Map<String, ConfigValue> values; // // public ConfigMap(Map<String, ConfigValue> values) { // this.values = values; // } // // public ConfigValue getValue(String methodName) { // return values.get(methodName); // } // // public Set<String> getMethodNames() { // return values.keySet(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConfigMap configMap = (ConfigMap) o; // return Objects.equals(values, configMap.values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // }
import com.statemachinesystems.envy.parsers.*; import com.statemachinesystems.envy.sources.DelegatingConfigSource; import com.statemachinesystems.envy.sources.EnvironmentVariableConfigSource; import com.statemachinesystems.envy.sources.SystemPropertyConfigSource; import com.statemachinesystems.envy.values.ConfigMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;
* @return a default {@link com.statemachinesystems.envy.ConfigSource} implementation */ public static ConfigSource defaultConfigSource() { return DEFAULT_CONFIG_SOURCE; } private static final ConfigSource DEFAULT_CONFIG_SOURCE = new DelegatingConfigSource(new SystemPropertyConfigSource(), new EnvironmentVariableConfigSource()); private final ConfigExtractor configExtractor; /** * Creates a new {@link com.statemachinesystems.envy.Envy} instance with the given * {@link com.statemachinesystems.envy.ValueParserFactory} and {@link com.statemachinesystems.envy.ConfigSource}. * * @param valueParserFactory the {@link com.statemachinesystems.envy.ValueParserFactory} to use * @param configSource the {@link com.statemachinesystems.envy.ConfigSource} to use */ public Envy(ValueParserFactory valueParserFactory, ConfigSource configSource) { this.configExtractor = new ConfigExtractor(valueParserFactory, configSource); } /** * Builds a proxy configuration object from the given interface. * * @param configClass the configuration interface to be proxied * @param <T> the type of the configuration interface * @return a configuration object that implements the interface */ public <T> T proxy(Class<T> configClass) {
// Path: src/main/java/com/statemachinesystems/envy/sources/DelegatingConfigSource.java // public class DelegatingConfigSource implements ConfigSource { // // private final ConfigSource[] sources; // // /** // * Creates a {@link com.statemachinesystems.envy.sources.DelegatingConfigSource} using // * the given component sources in preference order. // * // * @param sources component {@link com.statemachinesystems.envy.ConfigSource}s in preference order // */ // public DelegatingConfigSource(ConfigSource... sources) { // this.sources = sources; // } // // @Override // public String getValue(Parameter parameter) { // for (ConfigSource source : sources) { // String value = source.getValue(parameter); // if (value != null) { // return value; // } // } // return null; // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/EnvironmentVariableConfigSource.java // public class EnvironmentVariableConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getenv(parameter.asEnvironmentVariableName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/sources/SystemPropertyConfigSource.java // public class SystemPropertyConfigSource implements ConfigSource { // // @Override // public String getValue(Parameter parameter) { // return System.getProperty(parameter.asSystemPropertyName()); // } // } // // Path: src/main/java/com/statemachinesystems/envy/values/ConfigMap.java // public class ConfigMap implements Serializable { // // private final Map<String, ConfigValue> values; // // public ConfigMap(Map<String, ConfigValue> values) { // this.values = values; // } // // public ConfigValue getValue(String methodName) { // return values.get(methodName); // } // // public Set<String> getMethodNames() { // return values.keySet(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConfigMap configMap = (ConfigMap) o; // return Objects.equals(values, configMap.values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // } // Path: src/main/java/com/statemachinesystems/envy/Envy.java import com.statemachinesystems.envy.parsers.*; import com.statemachinesystems.envy.sources.DelegatingConfigSource; import com.statemachinesystems.envy.sources.EnvironmentVariableConfigSource; import com.statemachinesystems.envy.sources.SystemPropertyConfigSource; import com.statemachinesystems.envy.values.ConfigMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; * @return a default {@link com.statemachinesystems.envy.ConfigSource} implementation */ public static ConfigSource defaultConfigSource() { return DEFAULT_CONFIG_SOURCE; } private static final ConfigSource DEFAULT_CONFIG_SOURCE = new DelegatingConfigSource(new SystemPropertyConfigSource(), new EnvironmentVariableConfigSource()); private final ConfigExtractor configExtractor; /** * Creates a new {@link com.statemachinesystems.envy.Envy} instance with the given * {@link com.statemachinesystems.envy.ValueParserFactory} and {@link com.statemachinesystems.envy.ConfigSource}. * * @param valueParserFactory the {@link com.statemachinesystems.envy.ValueParserFactory} to use * @param configSource the {@link com.statemachinesystems.envy.ConfigSource} to use */ public Envy(ValueParserFactory valueParserFactory, ConfigSource configSource) { this.configExtractor = new ConfigExtractor(valueParserFactory, configSource); } /** * Builds a proxy configuration object from the given interface. * * @param configClass the configuration interface to be proxied * @param <T> the type of the configuration interface * @return a configuration object that implements the interface */ public <T> T proxy(Class<T> configClass) {
ConfigMap values = configExtractor.extractConfigMap(configClass);
state-machine-systems/envy
src/main/java/com/statemachinesystems/envy/ProxyInvocationHandler.java
// Path: src/main/java/com/statemachinesystems/envy/values/ConfigMap.java // public class ConfigMap implements Serializable { // // private final Map<String, ConfigValue> values; // // public ConfigMap(Map<String, ConfigValue> values) { // this.values = values; // } // // public ConfigValue getValue(String methodName) { // return values.get(methodName); // } // // public Set<String> getMethodNames() { // return values.keySet(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConfigMap configMap = (ConfigMap) o; // return Objects.equals(values, configMap.values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // } // // Path: src/main/java/com/statemachinesystems/envy/values/ConfigValue.java // public interface ConfigValue<T> extends Serializable { // // static <T> ConfigValue<T> of(T value, ConfigValue.Status status, Method method) { // return method.getAnnotation(Sensitive.class) != null // ? new SensitiveValue<>(value, status) // : new ResolvedValue<>(value, status); // } // // enum Status { // CONFIGURED, // MISSING, // DEFAULTED // } // // /** // * Returns the fully extracted and parsed value, or a default. // * // * @param proxy the proxy this value belongs to // */ // T getValue(Object proxy); // // /** // * Returns the value formatted as a String. // * // * @param proxy the proxy this value belongs to // * @return the value formatted as a String // */ // String format(Object proxy); // // /** // * Indicates whether the value was found in the underlying {@link ConfigSource}, // * missing, or replaced by a default value. // */ // Status getStatus(); // } // // Path: src/main/java/com/statemachinesystems/envy/Assertions.java // public static void assertInterface(Class<?> c) { // if (! c.isInterface()) { // throw new IllegalArgumentException( // String.format("%s is not an interface", c.getCanonicalName())); // } // }
import com.statemachinesystems.envy.values.ConfigMap; import com.statemachinesystems.envy.values.ConfigValue; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import static com.statemachinesystems.envy.Assertions.assertInterface;
package com.statemachinesystems.envy; /** * Handles method calls on proxied configuration interfaces. * * @see java.lang.reflect.InvocationHandler */ public class ProxyInvocationHandler implements InvocationHandler, Serializable { /** * Builds a proxy configuration object from the given interface and configuration values. * * @param configClass the configuration interface to be proxied * @param values map of configuration values indexed by method name * @param <T> the type of the configuration interface * @return a configuration object that implements the interface */ public static <T> T proxy(Class<T> configClass, ConfigMap values) {
// Path: src/main/java/com/statemachinesystems/envy/values/ConfigMap.java // public class ConfigMap implements Serializable { // // private final Map<String, ConfigValue> values; // // public ConfigMap(Map<String, ConfigValue> values) { // this.values = values; // } // // public ConfigValue getValue(String methodName) { // return values.get(methodName); // } // // public Set<String> getMethodNames() { // return values.keySet(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConfigMap configMap = (ConfigMap) o; // return Objects.equals(values, configMap.values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // } // // Path: src/main/java/com/statemachinesystems/envy/values/ConfigValue.java // public interface ConfigValue<T> extends Serializable { // // static <T> ConfigValue<T> of(T value, ConfigValue.Status status, Method method) { // return method.getAnnotation(Sensitive.class) != null // ? new SensitiveValue<>(value, status) // : new ResolvedValue<>(value, status); // } // // enum Status { // CONFIGURED, // MISSING, // DEFAULTED // } // // /** // * Returns the fully extracted and parsed value, or a default. // * // * @param proxy the proxy this value belongs to // */ // T getValue(Object proxy); // // /** // * Returns the value formatted as a String. // * // * @param proxy the proxy this value belongs to // * @return the value formatted as a String // */ // String format(Object proxy); // // /** // * Indicates whether the value was found in the underlying {@link ConfigSource}, // * missing, or replaced by a default value. // */ // Status getStatus(); // } // // Path: src/main/java/com/statemachinesystems/envy/Assertions.java // public static void assertInterface(Class<?> c) { // if (! c.isInterface()) { // throw new IllegalArgumentException( // String.format("%s is not an interface", c.getCanonicalName())); // } // } // Path: src/main/java/com/statemachinesystems/envy/ProxyInvocationHandler.java import com.statemachinesystems.envy.values.ConfigMap; import com.statemachinesystems.envy.values.ConfigValue; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import static com.statemachinesystems.envy.Assertions.assertInterface; package com.statemachinesystems.envy; /** * Handles method calls on proxied configuration interfaces. * * @see java.lang.reflect.InvocationHandler */ public class ProxyInvocationHandler implements InvocationHandler, Serializable { /** * Builds a proxy configuration object from the given interface and configuration values. * * @param configClass the configuration interface to be proxied * @param values map of configuration values indexed by method name * @param <T> the type of the configuration interface * @return a configuration object that implements the interface */ public static <T> T proxy(Class<T> configClass, ConfigMap values) {
assertInterface(configClass);
state-machine-systems/envy
src/main/java/com/statemachinesystems/envy/ProxyInvocationHandler.java
// Path: src/main/java/com/statemachinesystems/envy/values/ConfigMap.java // public class ConfigMap implements Serializable { // // private final Map<String, ConfigValue> values; // // public ConfigMap(Map<String, ConfigValue> values) { // this.values = values; // } // // public ConfigValue getValue(String methodName) { // return values.get(methodName); // } // // public Set<String> getMethodNames() { // return values.keySet(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConfigMap configMap = (ConfigMap) o; // return Objects.equals(values, configMap.values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // } // // Path: src/main/java/com/statemachinesystems/envy/values/ConfigValue.java // public interface ConfigValue<T> extends Serializable { // // static <T> ConfigValue<T> of(T value, ConfigValue.Status status, Method method) { // return method.getAnnotation(Sensitive.class) != null // ? new SensitiveValue<>(value, status) // : new ResolvedValue<>(value, status); // } // // enum Status { // CONFIGURED, // MISSING, // DEFAULTED // } // // /** // * Returns the fully extracted and parsed value, or a default. // * // * @param proxy the proxy this value belongs to // */ // T getValue(Object proxy); // // /** // * Returns the value formatted as a String. // * // * @param proxy the proxy this value belongs to // * @return the value formatted as a String // */ // String format(Object proxy); // // /** // * Indicates whether the value was found in the underlying {@link ConfigSource}, // * missing, or replaced by a default value. // */ // Status getStatus(); // } // // Path: src/main/java/com/statemachinesystems/envy/Assertions.java // public static void assertInterface(Class<?> c) { // if (! c.isInterface()) { // throw new IllegalArgumentException( // String.format("%s is not an interface", c.getCanonicalName())); // } // }
import com.statemachinesystems.envy.values.ConfigMap; import com.statemachinesystems.envy.values.ConfigValue; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import static com.statemachinesystems.envy.Assertions.assertInterface;
package com.statemachinesystems.envy; /** * Handles method calls on proxied configuration interfaces. * * @see java.lang.reflect.InvocationHandler */ public class ProxyInvocationHandler implements InvocationHandler, Serializable { /** * Builds a proxy configuration object from the given interface and configuration values. * * @param configClass the configuration interface to be proxied * @param values map of configuration values indexed by method name * @param <T> the type of the configuration interface * @return a configuration object that implements the interface */ public static <T> T proxy(Class<T> configClass, ConfigMap values) { assertInterface(configClass); InvocationHandler invocationHandler = new ProxyInvocationHandler(configClass, values); ClassLoader classLoader = configClass.getClassLoader(); Class<?>[] proxyInterfaces = new Class<?>[] { configClass }; @SuppressWarnings("unchecked") T proxyInstance = (T) Proxy.newProxyInstance(classLoader, proxyInterfaces, invocationHandler); return proxyInstance; } private static Method getObjectMethod(String name, Class<?>... argumentTypes) { try { return Object.class.getMethod(name, argumentTypes); } catch (Exception e) { throw new IllegalStateException(e); } } private static final Method TO_STRING_METHOD = getObjectMethod("toString"); private static final Method EQUALS_METHOD = getObjectMethod("equals", Object.class); private static final Method HASH_CODE_METHOD = getObjectMethod("hashCode"); private final Class<?> configClass; private final ConfigMap values; /** * Creates a {@link com.statemachinesystems.envy.ProxyInvocationHandler} instance using the given interface * and configuration values. * * @param configClass the configuration interface to be proxied * @param values map of configuration values indexed by method name */ private ProxyInvocationHandler(Class<?> configClass, ConfigMap values) { this.configClass = configClass; this.values = values; } @Override public Object invoke(Object proxy, Method method, Object[] args) {
// Path: src/main/java/com/statemachinesystems/envy/values/ConfigMap.java // public class ConfigMap implements Serializable { // // private final Map<String, ConfigValue> values; // // public ConfigMap(Map<String, ConfigValue> values) { // this.values = values; // } // // public ConfigValue getValue(String methodName) { // return values.get(methodName); // } // // public Set<String> getMethodNames() { // return values.keySet(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConfigMap configMap = (ConfigMap) o; // return Objects.equals(values, configMap.values); // } // // @Override // public int hashCode() { // return Objects.hash(values); // } // } // // Path: src/main/java/com/statemachinesystems/envy/values/ConfigValue.java // public interface ConfigValue<T> extends Serializable { // // static <T> ConfigValue<T> of(T value, ConfigValue.Status status, Method method) { // return method.getAnnotation(Sensitive.class) != null // ? new SensitiveValue<>(value, status) // : new ResolvedValue<>(value, status); // } // // enum Status { // CONFIGURED, // MISSING, // DEFAULTED // } // // /** // * Returns the fully extracted and parsed value, or a default. // * // * @param proxy the proxy this value belongs to // */ // T getValue(Object proxy); // // /** // * Returns the value formatted as a String. // * // * @param proxy the proxy this value belongs to // * @return the value formatted as a String // */ // String format(Object proxy); // // /** // * Indicates whether the value was found in the underlying {@link ConfigSource}, // * missing, or replaced by a default value. // */ // Status getStatus(); // } // // Path: src/main/java/com/statemachinesystems/envy/Assertions.java // public static void assertInterface(Class<?> c) { // if (! c.isInterface()) { // throw new IllegalArgumentException( // String.format("%s is not an interface", c.getCanonicalName())); // } // } // Path: src/main/java/com/statemachinesystems/envy/ProxyInvocationHandler.java import com.statemachinesystems.envy.values.ConfigMap; import com.statemachinesystems.envy.values.ConfigValue; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import static com.statemachinesystems.envy.Assertions.assertInterface; package com.statemachinesystems.envy; /** * Handles method calls on proxied configuration interfaces. * * @see java.lang.reflect.InvocationHandler */ public class ProxyInvocationHandler implements InvocationHandler, Serializable { /** * Builds a proxy configuration object from the given interface and configuration values. * * @param configClass the configuration interface to be proxied * @param values map of configuration values indexed by method name * @param <T> the type of the configuration interface * @return a configuration object that implements the interface */ public static <T> T proxy(Class<T> configClass, ConfigMap values) { assertInterface(configClass); InvocationHandler invocationHandler = new ProxyInvocationHandler(configClass, values); ClassLoader classLoader = configClass.getClassLoader(); Class<?>[] proxyInterfaces = new Class<?>[] { configClass }; @SuppressWarnings("unchecked") T proxyInstance = (T) Proxy.newProxyInstance(classLoader, proxyInterfaces, invocationHandler); return proxyInstance; } private static Method getObjectMethod(String name, Class<?>... argumentTypes) { try { return Object.class.getMethod(name, argumentTypes); } catch (Exception e) { throw new IllegalStateException(e); } } private static final Method TO_STRING_METHOD = getObjectMethod("toString"); private static final Method EQUALS_METHOD = getObjectMethod("equals", Object.class); private static final Method HASH_CODE_METHOD = getObjectMethod("hashCode"); private final Class<?> configClass; private final ConfigMap values; /** * Creates a {@link com.statemachinesystems.envy.ProxyInvocationHandler} instance using the given interface * and configuration values. * * @param configClass the configuration interface to be proxied * @param values map of configuration values indexed by method name */ private ProxyInvocationHandler(Class<?> configClass, ConfigMap values) { this.configClass = configClass; this.values = values; } @Override public Object invoke(Object proxy, Method method, Object[] args) {
ConfigValue<?> value = values.getValue(method.getName());
state-machine-systems/envy
src/main/java/com/statemachinesystems/envy/ValueParserFactory.java
// Path: src/main/java/com/statemachinesystems/envy/parsers/ArrayValueParser.java // public class ArrayValueParser<T> implements ValueParser<T[]> { // // public static final String DEFAULT_SEPARATOR = ","; // private static final int INCLUDE_TRAILING = -1; // // private final ValueParser<T> valueParser; // private final String separator; // // public ArrayValueParser(ValueParser<T> valueParser, String separator) { // this.valueParser = valueParser; // this.separator = separator; // } // // public ArrayValueParser(ValueParser<T> valueParser) { // this(valueParser, DEFAULT_SEPARATOR); // } // // @Override // public T[] parseValue(String value) { // String[] parts = value.isEmpty() // ? new String[] {} // : value.split(separator, INCLUDE_TRAILING); // // @SuppressWarnings("unchecked") // T[] array = (T[]) Array.newInstance(valueParser.getValueClass(), parts.length); // // for (int i = 0; i < parts.length; i++) { // array[i] = valueParser.parseValue(parts[i]); // } // return array; // } // // @Override // @SuppressWarnings("unchecked") // public Class<T[]> getValueClass() { // return (Class<T[]>) Array.newInstance(valueParser.getValueClass(), 0).getClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/EnumValueParser.java // public class EnumValueParser<T extends Enum<T>> implements ValueParser<T> { // // private final Class<T> enumClass; // // public EnumValueParser(Class<T> enumClass) { // assertEnum(enumClass); // this.enumClass = enumClass; // } // // @Override // public T parseValue(String value) { // for (Object constant : enumClass.getEnumConstants()) { // if (value.equals(((Enum<?>) constant).name())) { // @SuppressWarnings("unchecked") // T enumValue = (T) constant; // // return enumValue; // } // } // throw new IllegalArgumentException( // String.format("No constant '%s' for enum %s", value, enumClass.getName())); // } // // @Override // public Class<T> getValueClass() { // return enumClass; // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/ReflectionValueParser.java // public class ReflectionValueParser<T> implements ValueParser<T> { // // public static <T> ReflectionValueParser<T> parserOrNull(Class<T> valueClass) { // Constructor<T> constructor = stringConstructorOrNull(valueClass); // return constructor != null // ? new ReflectionValueParser<T>(constructor) // : null; // } // // public static <T> Constructor<T> stringConstructorOrNull(Class<T> targetClass) { // @SuppressWarnings("unchecked") // Constructor<T>[] constructors = (Constructor<T>[]) targetClass.getConstructors(); // // for (Constructor<T> constructor : constructors) { // if (isStringConstructor(constructor)) { // return constructor; // } // } // return null; // } // // public static <T> boolean isStringConstructor(Constructor<T> constructor) { // Class<?>[] parameterTypes = constructor.getParameterTypes(); // return parameterTypes.length == 1 // && parameterTypes[0].isAssignableFrom(String.class);// TODO CharSequence instead? // } // // private final Constructor<T> constructor; // // private ReflectionValueParser(Constructor<T> constructor) { // this.constructor = constructor; // } // // @Override // public T parseValue(String value) { // try { // return constructor.newInstance(value); // } catch (Exception e) { // throw new RuntimeException(e.getMessage(), e); // } // } // // @Override // public Class<T> getValueClass() { // return constructor.getDeclaringClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/Conversions.java // public static Class<?> toBoxed(Class<?> c) { // return c.isPrimitive() // ? primitiveToBoxed.get(c) // : c; // }
import com.statemachinesystems.envy.parsers.ArrayValueParser; import com.statemachinesystems.envy.parsers.EnumValueParser; import com.statemachinesystems.envy.parsers.ReflectionValueParser; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static com.statemachinesystems.envy.Conversions.toBoxed;
package com.statemachinesystems.envy; /** * Creates {@link com.statemachinesystems.envy.ValueParser} instances with special * support for arrays, enums and types with a constructor that takes * a single {@link java.lang.String} argument (see {@link com.statemachinesystems.envy.parsers.ReflectionValueParser}). */ public class ValueParserFactory { private final Map<Class<?>, ValueParser<?>> valueParsers; public ValueParserFactory(ValueParser<?>... valueParsers) { this(Arrays.asList(valueParsers)); } public ValueParserFactory(Collection<ValueParser<?>> valueParsers) { this.valueParsers = new HashMap<Class<?>, ValueParser<?>>(); for (ValueParser<?> parser : valueParsers) { this.valueParsers.put(parser.getValueClass(), parser); } } /** * Creates a {@link com.statemachinesystems.envy.ValueParser} for the given class. * * Returns null if no applicable parser is available. * * @param propertyClass the class for which to create the {@link com.statemachinesystems.envy.ValueParser} * @return a {@link com.statemachinesystems.envy.ValueParser} for the given class, or null if * no applicable parser is available */ @SuppressWarnings("unchecked") public <T> ValueParser<T> getValueParser(Class<T> propertyClass) { return (ValueParser<T>) getValueParser(propertyClass, true); } private ValueParser<?> getValueParser(Class<?> propertyClass, boolean allowArrays) {
// Path: src/main/java/com/statemachinesystems/envy/parsers/ArrayValueParser.java // public class ArrayValueParser<T> implements ValueParser<T[]> { // // public static final String DEFAULT_SEPARATOR = ","; // private static final int INCLUDE_TRAILING = -1; // // private final ValueParser<T> valueParser; // private final String separator; // // public ArrayValueParser(ValueParser<T> valueParser, String separator) { // this.valueParser = valueParser; // this.separator = separator; // } // // public ArrayValueParser(ValueParser<T> valueParser) { // this(valueParser, DEFAULT_SEPARATOR); // } // // @Override // public T[] parseValue(String value) { // String[] parts = value.isEmpty() // ? new String[] {} // : value.split(separator, INCLUDE_TRAILING); // // @SuppressWarnings("unchecked") // T[] array = (T[]) Array.newInstance(valueParser.getValueClass(), parts.length); // // for (int i = 0; i < parts.length; i++) { // array[i] = valueParser.parseValue(parts[i]); // } // return array; // } // // @Override // @SuppressWarnings("unchecked") // public Class<T[]> getValueClass() { // return (Class<T[]>) Array.newInstance(valueParser.getValueClass(), 0).getClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/EnumValueParser.java // public class EnumValueParser<T extends Enum<T>> implements ValueParser<T> { // // private final Class<T> enumClass; // // public EnumValueParser(Class<T> enumClass) { // assertEnum(enumClass); // this.enumClass = enumClass; // } // // @Override // public T parseValue(String value) { // for (Object constant : enumClass.getEnumConstants()) { // if (value.equals(((Enum<?>) constant).name())) { // @SuppressWarnings("unchecked") // T enumValue = (T) constant; // // return enumValue; // } // } // throw new IllegalArgumentException( // String.format("No constant '%s' for enum %s", value, enumClass.getName())); // } // // @Override // public Class<T> getValueClass() { // return enumClass; // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/ReflectionValueParser.java // public class ReflectionValueParser<T> implements ValueParser<T> { // // public static <T> ReflectionValueParser<T> parserOrNull(Class<T> valueClass) { // Constructor<T> constructor = stringConstructorOrNull(valueClass); // return constructor != null // ? new ReflectionValueParser<T>(constructor) // : null; // } // // public static <T> Constructor<T> stringConstructorOrNull(Class<T> targetClass) { // @SuppressWarnings("unchecked") // Constructor<T>[] constructors = (Constructor<T>[]) targetClass.getConstructors(); // // for (Constructor<T> constructor : constructors) { // if (isStringConstructor(constructor)) { // return constructor; // } // } // return null; // } // // public static <T> boolean isStringConstructor(Constructor<T> constructor) { // Class<?>[] parameterTypes = constructor.getParameterTypes(); // return parameterTypes.length == 1 // && parameterTypes[0].isAssignableFrom(String.class);// TODO CharSequence instead? // } // // private final Constructor<T> constructor; // // private ReflectionValueParser(Constructor<T> constructor) { // this.constructor = constructor; // } // // @Override // public T parseValue(String value) { // try { // return constructor.newInstance(value); // } catch (Exception e) { // throw new RuntimeException(e.getMessage(), e); // } // } // // @Override // public Class<T> getValueClass() { // return constructor.getDeclaringClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/Conversions.java // public static Class<?> toBoxed(Class<?> c) { // return c.isPrimitive() // ? primitiveToBoxed.get(c) // : c; // } // Path: src/main/java/com/statemachinesystems/envy/ValueParserFactory.java import com.statemachinesystems.envy.parsers.ArrayValueParser; import com.statemachinesystems.envy.parsers.EnumValueParser; import com.statemachinesystems.envy.parsers.ReflectionValueParser; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static com.statemachinesystems.envy.Conversions.toBoxed; package com.statemachinesystems.envy; /** * Creates {@link com.statemachinesystems.envy.ValueParser} instances with special * support for arrays, enums and types with a constructor that takes * a single {@link java.lang.String} argument (see {@link com.statemachinesystems.envy.parsers.ReflectionValueParser}). */ public class ValueParserFactory { private final Map<Class<?>, ValueParser<?>> valueParsers; public ValueParserFactory(ValueParser<?>... valueParsers) { this(Arrays.asList(valueParsers)); } public ValueParserFactory(Collection<ValueParser<?>> valueParsers) { this.valueParsers = new HashMap<Class<?>, ValueParser<?>>(); for (ValueParser<?> parser : valueParsers) { this.valueParsers.put(parser.getValueClass(), parser); } } /** * Creates a {@link com.statemachinesystems.envy.ValueParser} for the given class. * * Returns null if no applicable parser is available. * * @param propertyClass the class for which to create the {@link com.statemachinesystems.envy.ValueParser} * @return a {@link com.statemachinesystems.envy.ValueParser} for the given class, or null if * no applicable parser is available */ @SuppressWarnings("unchecked") public <T> ValueParser<T> getValueParser(Class<T> propertyClass) { return (ValueParser<T>) getValueParser(propertyClass, true); } private ValueParser<?> getValueParser(Class<?> propertyClass, boolean allowArrays) {
ValueParser<?> parser = valueParsers.get(toBoxed(propertyClass));
state-machine-systems/envy
src/main/java/com/statemachinesystems/envy/ValueParserFactory.java
// Path: src/main/java/com/statemachinesystems/envy/parsers/ArrayValueParser.java // public class ArrayValueParser<T> implements ValueParser<T[]> { // // public static final String DEFAULT_SEPARATOR = ","; // private static final int INCLUDE_TRAILING = -1; // // private final ValueParser<T> valueParser; // private final String separator; // // public ArrayValueParser(ValueParser<T> valueParser, String separator) { // this.valueParser = valueParser; // this.separator = separator; // } // // public ArrayValueParser(ValueParser<T> valueParser) { // this(valueParser, DEFAULT_SEPARATOR); // } // // @Override // public T[] parseValue(String value) { // String[] parts = value.isEmpty() // ? new String[] {} // : value.split(separator, INCLUDE_TRAILING); // // @SuppressWarnings("unchecked") // T[] array = (T[]) Array.newInstance(valueParser.getValueClass(), parts.length); // // for (int i = 0; i < parts.length; i++) { // array[i] = valueParser.parseValue(parts[i]); // } // return array; // } // // @Override // @SuppressWarnings("unchecked") // public Class<T[]> getValueClass() { // return (Class<T[]>) Array.newInstance(valueParser.getValueClass(), 0).getClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/EnumValueParser.java // public class EnumValueParser<T extends Enum<T>> implements ValueParser<T> { // // private final Class<T> enumClass; // // public EnumValueParser(Class<T> enumClass) { // assertEnum(enumClass); // this.enumClass = enumClass; // } // // @Override // public T parseValue(String value) { // for (Object constant : enumClass.getEnumConstants()) { // if (value.equals(((Enum<?>) constant).name())) { // @SuppressWarnings("unchecked") // T enumValue = (T) constant; // // return enumValue; // } // } // throw new IllegalArgumentException( // String.format("No constant '%s' for enum %s", value, enumClass.getName())); // } // // @Override // public Class<T> getValueClass() { // return enumClass; // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/ReflectionValueParser.java // public class ReflectionValueParser<T> implements ValueParser<T> { // // public static <T> ReflectionValueParser<T> parserOrNull(Class<T> valueClass) { // Constructor<T> constructor = stringConstructorOrNull(valueClass); // return constructor != null // ? new ReflectionValueParser<T>(constructor) // : null; // } // // public static <T> Constructor<T> stringConstructorOrNull(Class<T> targetClass) { // @SuppressWarnings("unchecked") // Constructor<T>[] constructors = (Constructor<T>[]) targetClass.getConstructors(); // // for (Constructor<T> constructor : constructors) { // if (isStringConstructor(constructor)) { // return constructor; // } // } // return null; // } // // public static <T> boolean isStringConstructor(Constructor<T> constructor) { // Class<?>[] parameterTypes = constructor.getParameterTypes(); // return parameterTypes.length == 1 // && parameterTypes[0].isAssignableFrom(String.class);// TODO CharSequence instead? // } // // private final Constructor<T> constructor; // // private ReflectionValueParser(Constructor<T> constructor) { // this.constructor = constructor; // } // // @Override // public T parseValue(String value) { // try { // return constructor.newInstance(value); // } catch (Exception e) { // throw new RuntimeException(e.getMessage(), e); // } // } // // @Override // public Class<T> getValueClass() { // return constructor.getDeclaringClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/Conversions.java // public static Class<?> toBoxed(Class<?> c) { // return c.isPrimitive() // ? primitiveToBoxed.get(c) // : c; // }
import com.statemachinesystems.envy.parsers.ArrayValueParser; import com.statemachinesystems.envy.parsers.EnumValueParser; import com.statemachinesystems.envy.parsers.ReflectionValueParser; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static com.statemachinesystems.envy.Conversions.toBoxed;
* Returns null if no applicable parser is available. * * @param propertyClass the class for which to create the {@link com.statemachinesystems.envy.ValueParser} * @return a {@link com.statemachinesystems.envy.ValueParser} for the given class, or null if * no applicable parser is available */ @SuppressWarnings("unchecked") public <T> ValueParser<T> getValueParser(Class<T> propertyClass) { return (ValueParser<T>) getValueParser(propertyClass, true); } private ValueParser<?> getValueParser(Class<?> propertyClass, boolean allowArrays) { ValueParser<?> parser = valueParsers.get(toBoxed(propertyClass)); if (parser != null) { return parser; } else if (propertyClass.isEnum()) { return enumValueParser(propertyClass); } else if (propertyClass.isArray()) { if (! allowArrays) { throw new UnsupportedTypeException("Nested arrays are not supported"); } return arrayValueParser(propertyClass); } else { return ReflectionValueParser.parserOrNull(propertyClass); } } private ValueParser<?> enumValueParser(Class<?> propertyClass) { @SuppressWarnings("unchecked")
// Path: src/main/java/com/statemachinesystems/envy/parsers/ArrayValueParser.java // public class ArrayValueParser<T> implements ValueParser<T[]> { // // public static final String DEFAULT_SEPARATOR = ","; // private static final int INCLUDE_TRAILING = -1; // // private final ValueParser<T> valueParser; // private final String separator; // // public ArrayValueParser(ValueParser<T> valueParser, String separator) { // this.valueParser = valueParser; // this.separator = separator; // } // // public ArrayValueParser(ValueParser<T> valueParser) { // this(valueParser, DEFAULT_SEPARATOR); // } // // @Override // public T[] parseValue(String value) { // String[] parts = value.isEmpty() // ? new String[] {} // : value.split(separator, INCLUDE_TRAILING); // // @SuppressWarnings("unchecked") // T[] array = (T[]) Array.newInstance(valueParser.getValueClass(), parts.length); // // for (int i = 0; i < parts.length; i++) { // array[i] = valueParser.parseValue(parts[i]); // } // return array; // } // // @Override // @SuppressWarnings("unchecked") // public Class<T[]> getValueClass() { // return (Class<T[]>) Array.newInstance(valueParser.getValueClass(), 0).getClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/EnumValueParser.java // public class EnumValueParser<T extends Enum<T>> implements ValueParser<T> { // // private final Class<T> enumClass; // // public EnumValueParser(Class<T> enumClass) { // assertEnum(enumClass); // this.enumClass = enumClass; // } // // @Override // public T parseValue(String value) { // for (Object constant : enumClass.getEnumConstants()) { // if (value.equals(((Enum<?>) constant).name())) { // @SuppressWarnings("unchecked") // T enumValue = (T) constant; // // return enumValue; // } // } // throw new IllegalArgumentException( // String.format("No constant '%s' for enum %s", value, enumClass.getName())); // } // // @Override // public Class<T> getValueClass() { // return enumClass; // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/ReflectionValueParser.java // public class ReflectionValueParser<T> implements ValueParser<T> { // // public static <T> ReflectionValueParser<T> parserOrNull(Class<T> valueClass) { // Constructor<T> constructor = stringConstructorOrNull(valueClass); // return constructor != null // ? new ReflectionValueParser<T>(constructor) // : null; // } // // public static <T> Constructor<T> stringConstructorOrNull(Class<T> targetClass) { // @SuppressWarnings("unchecked") // Constructor<T>[] constructors = (Constructor<T>[]) targetClass.getConstructors(); // // for (Constructor<T> constructor : constructors) { // if (isStringConstructor(constructor)) { // return constructor; // } // } // return null; // } // // public static <T> boolean isStringConstructor(Constructor<T> constructor) { // Class<?>[] parameterTypes = constructor.getParameterTypes(); // return parameterTypes.length == 1 // && parameterTypes[0].isAssignableFrom(String.class);// TODO CharSequence instead? // } // // private final Constructor<T> constructor; // // private ReflectionValueParser(Constructor<T> constructor) { // this.constructor = constructor; // } // // @Override // public T parseValue(String value) { // try { // return constructor.newInstance(value); // } catch (Exception e) { // throw new RuntimeException(e.getMessage(), e); // } // } // // @Override // public Class<T> getValueClass() { // return constructor.getDeclaringClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/Conversions.java // public static Class<?> toBoxed(Class<?> c) { // return c.isPrimitive() // ? primitiveToBoxed.get(c) // : c; // } // Path: src/main/java/com/statemachinesystems/envy/ValueParserFactory.java import com.statemachinesystems.envy.parsers.ArrayValueParser; import com.statemachinesystems.envy.parsers.EnumValueParser; import com.statemachinesystems.envy.parsers.ReflectionValueParser; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static com.statemachinesystems.envy.Conversions.toBoxed; * Returns null if no applicable parser is available. * * @param propertyClass the class for which to create the {@link com.statemachinesystems.envy.ValueParser} * @return a {@link com.statemachinesystems.envy.ValueParser} for the given class, or null if * no applicable parser is available */ @SuppressWarnings("unchecked") public <T> ValueParser<T> getValueParser(Class<T> propertyClass) { return (ValueParser<T>) getValueParser(propertyClass, true); } private ValueParser<?> getValueParser(Class<?> propertyClass, boolean allowArrays) { ValueParser<?> parser = valueParsers.get(toBoxed(propertyClass)); if (parser != null) { return parser; } else if (propertyClass.isEnum()) { return enumValueParser(propertyClass); } else if (propertyClass.isArray()) { if (! allowArrays) { throw new UnsupportedTypeException("Nested arrays are not supported"); } return arrayValueParser(propertyClass); } else { return ReflectionValueParser.parserOrNull(propertyClass); } } private ValueParser<?> enumValueParser(Class<?> propertyClass) { @SuppressWarnings("unchecked")
ValueParser<?> enumValueParser = new EnumValueParser(propertyClass);
state-machine-systems/envy
src/main/java/com/statemachinesystems/envy/ValueParserFactory.java
// Path: src/main/java/com/statemachinesystems/envy/parsers/ArrayValueParser.java // public class ArrayValueParser<T> implements ValueParser<T[]> { // // public static final String DEFAULT_SEPARATOR = ","; // private static final int INCLUDE_TRAILING = -1; // // private final ValueParser<T> valueParser; // private final String separator; // // public ArrayValueParser(ValueParser<T> valueParser, String separator) { // this.valueParser = valueParser; // this.separator = separator; // } // // public ArrayValueParser(ValueParser<T> valueParser) { // this(valueParser, DEFAULT_SEPARATOR); // } // // @Override // public T[] parseValue(String value) { // String[] parts = value.isEmpty() // ? new String[] {} // : value.split(separator, INCLUDE_TRAILING); // // @SuppressWarnings("unchecked") // T[] array = (T[]) Array.newInstance(valueParser.getValueClass(), parts.length); // // for (int i = 0; i < parts.length; i++) { // array[i] = valueParser.parseValue(parts[i]); // } // return array; // } // // @Override // @SuppressWarnings("unchecked") // public Class<T[]> getValueClass() { // return (Class<T[]>) Array.newInstance(valueParser.getValueClass(), 0).getClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/EnumValueParser.java // public class EnumValueParser<T extends Enum<T>> implements ValueParser<T> { // // private final Class<T> enumClass; // // public EnumValueParser(Class<T> enumClass) { // assertEnum(enumClass); // this.enumClass = enumClass; // } // // @Override // public T parseValue(String value) { // for (Object constant : enumClass.getEnumConstants()) { // if (value.equals(((Enum<?>) constant).name())) { // @SuppressWarnings("unchecked") // T enumValue = (T) constant; // // return enumValue; // } // } // throw new IllegalArgumentException( // String.format("No constant '%s' for enum %s", value, enumClass.getName())); // } // // @Override // public Class<T> getValueClass() { // return enumClass; // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/ReflectionValueParser.java // public class ReflectionValueParser<T> implements ValueParser<T> { // // public static <T> ReflectionValueParser<T> parserOrNull(Class<T> valueClass) { // Constructor<T> constructor = stringConstructorOrNull(valueClass); // return constructor != null // ? new ReflectionValueParser<T>(constructor) // : null; // } // // public static <T> Constructor<T> stringConstructorOrNull(Class<T> targetClass) { // @SuppressWarnings("unchecked") // Constructor<T>[] constructors = (Constructor<T>[]) targetClass.getConstructors(); // // for (Constructor<T> constructor : constructors) { // if (isStringConstructor(constructor)) { // return constructor; // } // } // return null; // } // // public static <T> boolean isStringConstructor(Constructor<T> constructor) { // Class<?>[] parameterTypes = constructor.getParameterTypes(); // return parameterTypes.length == 1 // && parameterTypes[0].isAssignableFrom(String.class);// TODO CharSequence instead? // } // // private final Constructor<T> constructor; // // private ReflectionValueParser(Constructor<T> constructor) { // this.constructor = constructor; // } // // @Override // public T parseValue(String value) { // try { // return constructor.newInstance(value); // } catch (Exception e) { // throw new RuntimeException(e.getMessage(), e); // } // } // // @Override // public Class<T> getValueClass() { // return constructor.getDeclaringClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/Conversions.java // public static Class<?> toBoxed(Class<?> c) { // return c.isPrimitive() // ? primitiveToBoxed.get(c) // : c; // }
import com.statemachinesystems.envy.parsers.ArrayValueParser; import com.statemachinesystems.envy.parsers.EnumValueParser; import com.statemachinesystems.envy.parsers.ReflectionValueParser; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static com.statemachinesystems.envy.Conversions.toBoxed;
if (parser != null) { return parser; } else if (propertyClass.isEnum()) { return enumValueParser(propertyClass); } else if (propertyClass.isArray()) { if (! allowArrays) { throw new UnsupportedTypeException("Nested arrays are not supported"); } return arrayValueParser(propertyClass); } else { return ReflectionValueParser.parserOrNull(propertyClass); } } private ValueParser<?> enumValueParser(Class<?> propertyClass) { @SuppressWarnings("unchecked") ValueParser<?> enumValueParser = new EnumValueParser(propertyClass); return enumValueParser; } private ValueParser<?> arrayValueParser(Class<?> propertyClass) { Class<?> componentType = propertyClass.getComponentType(); ValueParser<?> componentParser = getValueParser(componentType, false); if (componentParser == null) { return null; } @SuppressWarnings("unchecked")
// Path: src/main/java/com/statemachinesystems/envy/parsers/ArrayValueParser.java // public class ArrayValueParser<T> implements ValueParser<T[]> { // // public static final String DEFAULT_SEPARATOR = ","; // private static final int INCLUDE_TRAILING = -1; // // private final ValueParser<T> valueParser; // private final String separator; // // public ArrayValueParser(ValueParser<T> valueParser, String separator) { // this.valueParser = valueParser; // this.separator = separator; // } // // public ArrayValueParser(ValueParser<T> valueParser) { // this(valueParser, DEFAULT_SEPARATOR); // } // // @Override // public T[] parseValue(String value) { // String[] parts = value.isEmpty() // ? new String[] {} // : value.split(separator, INCLUDE_TRAILING); // // @SuppressWarnings("unchecked") // T[] array = (T[]) Array.newInstance(valueParser.getValueClass(), parts.length); // // for (int i = 0; i < parts.length; i++) { // array[i] = valueParser.parseValue(parts[i]); // } // return array; // } // // @Override // @SuppressWarnings("unchecked") // public Class<T[]> getValueClass() { // return (Class<T[]>) Array.newInstance(valueParser.getValueClass(), 0).getClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/EnumValueParser.java // public class EnumValueParser<T extends Enum<T>> implements ValueParser<T> { // // private final Class<T> enumClass; // // public EnumValueParser(Class<T> enumClass) { // assertEnum(enumClass); // this.enumClass = enumClass; // } // // @Override // public T parseValue(String value) { // for (Object constant : enumClass.getEnumConstants()) { // if (value.equals(((Enum<?>) constant).name())) { // @SuppressWarnings("unchecked") // T enumValue = (T) constant; // // return enumValue; // } // } // throw new IllegalArgumentException( // String.format("No constant '%s' for enum %s", value, enumClass.getName())); // } // // @Override // public Class<T> getValueClass() { // return enumClass; // } // } // // Path: src/main/java/com/statemachinesystems/envy/parsers/ReflectionValueParser.java // public class ReflectionValueParser<T> implements ValueParser<T> { // // public static <T> ReflectionValueParser<T> parserOrNull(Class<T> valueClass) { // Constructor<T> constructor = stringConstructorOrNull(valueClass); // return constructor != null // ? new ReflectionValueParser<T>(constructor) // : null; // } // // public static <T> Constructor<T> stringConstructorOrNull(Class<T> targetClass) { // @SuppressWarnings("unchecked") // Constructor<T>[] constructors = (Constructor<T>[]) targetClass.getConstructors(); // // for (Constructor<T> constructor : constructors) { // if (isStringConstructor(constructor)) { // return constructor; // } // } // return null; // } // // public static <T> boolean isStringConstructor(Constructor<T> constructor) { // Class<?>[] parameterTypes = constructor.getParameterTypes(); // return parameterTypes.length == 1 // && parameterTypes[0].isAssignableFrom(String.class);// TODO CharSequence instead? // } // // private final Constructor<T> constructor; // // private ReflectionValueParser(Constructor<T> constructor) { // this.constructor = constructor; // } // // @Override // public T parseValue(String value) { // try { // return constructor.newInstance(value); // } catch (Exception e) { // throw new RuntimeException(e.getMessage(), e); // } // } // // @Override // public Class<T> getValueClass() { // return constructor.getDeclaringClass(); // } // } // // Path: src/main/java/com/statemachinesystems/envy/Conversions.java // public static Class<?> toBoxed(Class<?> c) { // return c.isPrimitive() // ? primitiveToBoxed.get(c) // : c; // } // Path: src/main/java/com/statemachinesystems/envy/ValueParserFactory.java import com.statemachinesystems.envy.parsers.ArrayValueParser; import com.statemachinesystems.envy.parsers.EnumValueParser; import com.statemachinesystems.envy.parsers.ReflectionValueParser; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static com.statemachinesystems.envy.Conversions.toBoxed; if (parser != null) { return parser; } else if (propertyClass.isEnum()) { return enumValueParser(propertyClass); } else if (propertyClass.isArray()) { if (! allowArrays) { throw new UnsupportedTypeException("Nested arrays are not supported"); } return arrayValueParser(propertyClass); } else { return ReflectionValueParser.parserOrNull(propertyClass); } } private ValueParser<?> enumValueParser(Class<?> propertyClass) { @SuppressWarnings("unchecked") ValueParser<?> enumValueParser = new EnumValueParser(propertyClass); return enumValueParser; } private ValueParser<?> arrayValueParser(Class<?> propertyClass) { Class<?> componentType = propertyClass.getComponentType(); ValueParser<?> componentParser = getValueParser(componentType, false); if (componentParser == null) { return null; } @SuppressWarnings("unchecked")
ValueParser<?> arrayValueParser = new ArrayValueParser(componentParser);
state-machine-systems/envy
src/test/java/com/statemachinesystems/envy/features/EqualsAndHashCodeTest.java
// Path: src/main/java/com/statemachinesystems/envy/ConfigSource.java // public interface ConfigSource { // // /** // * Retrieves the configuration value associated with the given parameter. // * // * @param parameter the parameter to retrieve. // * @return the value associated with the parameter, or null if no value was present // */ // String getValue(Parameter parameter); // } // // Path: src/test/java/com/statemachinesystems/envy/common/FeatureTest.java // public abstract class FeatureTest { // // protected Envy envy() { // return envy(valueParserFactory(), configSource()); // } // // protected Envy envy(ValueParserFactory valueParserFactory) { // return envy(valueParserFactory, configSource()); // } // // protected Envy envy(ConfigSource configSource) { // return envy(valueParserFactory(), configSource); // } // // protected Envy envy(ValueParserFactory valueParserFactory, ConfigSource configSource) { // return new Envy(valueParserFactory, configSource); // } // // protected ValueParserFactory valueParserFactory() { // List<ValueParser<?>> valueParsers = new ArrayList<ValueParser<?>>(Envy.defaultValueParsers()); // return new ValueParserFactory(valueParsers); // } // // protected StubConfigSource configSource() { // return new StubConfigSource(); // } // } // // Path: src/test/java/com/statemachinesystems/envy/common/StubConfigSource.java // public class StubConfigSource implements ConfigSource { // // private final Map<Parameter, String> params; // // public StubConfigSource() { // this.params = new HashMap<Parameter, String>(); // } // // public StubConfigSource add(String parameter, String value) { // params.put(new Parameter(parameter), value); // return this; // } // // @Override // public String getValue(Parameter parameter) { // return params.get(parameter); // } // }
import com.statemachinesystems.envy.ConfigSource; import com.statemachinesystems.envy.common.FeatureTest; import com.statemachinesystems.envy.common.StubConfigSource; import org.junit.Test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*;
package com.statemachinesystems.envy.features; public class EqualsAndHashCodeTest extends FeatureTest { @SuppressWarnings("unused") public interface Config { int foo(); String bar(); } @SuppressWarnings("unused") public interface AnotherConfig { int foo(); String bar(); } @Override
// Path: src/main/java/com/statemachinesystems/envy/ConfigSource.java // public interface ConfigSource { // // /** // * Retrieves the configuration value associated with the given parameter. // * // * @param parameter the parameter to retrieve. // * @return the value associated with the parameter, or null if no value was present // */ // String getValue(Parameter parameter); // } // // Path: src/test/java/com/statemachinesystems/envy/common/FeatureTest.java // public abstract class FeatureTest { // // protected Envy envy() { // return envy(valueParserFactory(), configSource()); // } // // protected Envy envy(ValueParserFactory valueParserFactory) { // return envy(valueParserFactory, configSource()); // } // // protected Envy envy(ConfigSource configSource) { // return envy(valueParserFactory(), configSource); // } // // protected Envy envy(ValueParserFactory valueParserFactory, ConfigSource configSource) { // return new Envy(valueParserFactory, configSource); // } // // protected ValueParserFactory valueParserFactory() { // List<ValueParser<?>> valueParsers = new ArrayList<ValueParser<?>>(Envy.defaultValueParsers()); // return new ValueParserFactory(valueParsers); // } // // protected StubConfigSource configSource() { // return new StubConfigSource(); // } // } // // Path: src/test/java/com/statemachinesystems/envy/common/StubConfigSource.java // public class StubConfigSource implements ConfigSource { // // private final Map<Parameter, String> params; // // public StubConfigSource() { // this.params = new HashMap<Parameter, String>(); // } // // public StubConfigSource add(String parameter, String value) { // params.put(new Parameter(parameter), value); // return this; // } // // @Override // public String getValue(Parameter parameter) { // return params.get(parameter); // } // } // Path: src/test/java/com/statemachinesystems/envy/features/EqualsAndHashCodeTest.java import com.statemachinesystems.envy.ConfigSource; import com.statemachinesystems.envy.common.FeatureTest; import com.statemachinesystems.envy.common.StubConfigSource; import org.junit.Test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; package com.statemachinesystems.envy.features; public class EqualsAndHashCodeTest extends FeatureTest { @SuppressWarnings("unused") public interface Config { int foo(); String bar(); } @SuppressWarnings("unused") public interface AnotherConfig { int foo(); String bar(); } @Override
public StubConfigSource configSource() {
state-machine-systems/envy
src/test/java/com/statemachinesystems/envy/features/EqualsAndHashCodeTest.java
// Path: src/main/java/com/statemachinesystems/envy/ConfigSource.java // public interface ConfigSource { // // /** // * Retrieves the configuration value associated with the given parameter. // * // * @param parameter the parameter to retrieve. // * @return the value associated with the parameter, or null if no value was present // */ // String getValue(Parameter parameter); // } // // Path: src/test/java/com/statemachinesystems/envy/common/FeatureTest.java // public abstract class FeatureTest { // // protected Envy envy() { // return envy(valueParserFactory(), configSource()); // } // // protected Envy envy(ValueParserFactory valueParserFactory) { // return envy(valueParserFactory, configSource()); // } // // protected Envy envy(ConfigSource configSource) { // return envy(valueParserFactory(), configSource); // } // // protected Envy envy(ValueParserFactory valueParserFactory, ConfigSource configSource) { // return new Envy(valueParserFactory, configSource); // } // // protected ValueParserFactory valueParserFactory() { // List<ValueParser<?>> valueParsers = new ArrayList<ValueParser<?>>(Envy.defaultValueParsers()); // return new ValueParserFactory(valueParsers); // } // // protected StubConfigSource configSource() { // return new StubConfigSource(); // } // } // // Path: src/test/java/com/statemachinesystems/envy/common/StubConfigSource.java // public class StubConfigSource implements ConfigSource { // // private final Map<Parameter, String> params; // // public StubConfigSource() { // this.params = new HashMap<Parameter, String>(); // } // // public StubConfigSource add(String parameter, String value) { // params.put(new Parameter(parameter), value); // return this; // } // // @Override // public String getValue(Parameter parameter) { // return params.get(parameter); // } // }
import com.statemachinesystems.envy.ConfigSource; import com.statemachinesystems.envy.common.FeatureTest; import com.statemachinesystems.envy.common.StubConfigSource; import org.junit.Test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*;
package com.statemachinesystems.envy.features; public class EqualsAndHashCodeTest extends FeatureTest { @SuppressWarnings("unused") public interface Config { int foo(); String bar(); } @SuppressWarnings("unused") public interface AnotherConfig { int foo(); String bar(); } @Override public StubConfigSource configSource() { return super.configSource().add("foo", "1").add("bar", "bar"); } @Test public void equalsMethodOnProxyReturnsTrueForSameInstance() { Config config = envy().proxy(Config.class); assertEquals(config, config); } @Test public void equalsMethodOnProxyReturnsTrueForEqualInstances() { Config config1 = envy().proxy(Config.class); Config config2 = envy().proxy(Config.class); assertEquals(config1, config2); assertEquals(config2, config1); } @Test public void equalsMethodOnProxyReturnsFalseForUnequalInstances() {
// Path: src/main/java/com/statemachinesystems/envy/ConfigSource.java // public interface ConfigSource { // // /** // * Retrieves the configuration value associated with the given parameter. // * // * @param parameter the parameter to retrieve. // * @return the value associated with the parameter, or null if no value was present // */ // String getValue(Parameter parameter); // } // // Path: src/test/java/com/statemachinesystems/envy/common/FeatureTest.java // public abstract class FeatureTest { // // protected Envy envy() { // return envy(valueParserFactory(), configSource()); // } // // protected Envy envy(ValueParserFactory valueParserFactory) { // return envy(valueParserFactory, configSource()); // } // // protected Envy envy(ConfigSource configSource) { // return envy(valueParserFactory(), configSource); // } // // protected Envy envy(ValueParserFactory valueParserFactory, ConfigSource configSource) { // return new Envy(valueParserFactory, configSource); // } // // protected ValueParserFactory valueParserFactory() { // List<ValueParser<?>> valueParsers = new ArrayList<ValueParser<?>>(Envy.defaultValueParsers()); // return new ValueParserFactory(valueParsers); // } // // protected StubConfigSource configSource() { // return new StubConfigSource(); // } // } // // Path: src/test/java/com/statemachinesystems/envy/common/StubConfigSource.java // public class StubConfigSource implements ConfigSource { // // private final Map<Parameter, String> params; // // public StubConfigSource() { // this.params = new HashMap<Parameter, String>(); // } // // public StubConfigSource add(String parameter, String value) { // params.put(new Parameter(parameter), value); // return this; // } // // @Override // public String getValue(Parameter parameter) { // return params.get(parameter); // } // } // Path: src/test/java/com/statemachinesystems/envy/features/EqualsAndHashCodeTest.java import com.statemachinesystems.envy.ConfigSource; import com.statemachinesystems.envy.common.FeatureTest; import com.statemachinesystems.envy.common.StubConfigSource; import org.junit.Test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; package com.statemachinesystems.envy.features; public class EqualsAndHashCodeTest extends FeatureTest { @SuppressWarnings("unused") public interface Config { int foo(); String bar(); } @SuppressWarnings("unused") public interface AnotherConfig { int foo(); String bar(); } @Override public StubConfigSource configSource() { return super.configSource().add("foo", "1").add("bar", "bar"); } @Test public void equalsMethodOnProxyReturnsTrueForSameInstance() { Config config = envy().proxy(Config.class); assertEquals(config, config); } @Test public void equalsMethodOnProxyReturnsTrueForEqualInstances() { Config config1 = envy().proxy(Config.class); Config config2 = envy().proxy(Config.class); assertEquals(config1, config2); assertEquals(config2, config1); } @Test public void equalsMethodOnProxyReturnsFalseForUnequalInstances() {
ConfigSource configSource1 = configSource();
methusalah/OpenRTS
core/src/model/editor/tools/CliffTool.java
// Path: core/src/model/builders/entity/CliffShapeBuilder.java // public class CliffShapeBuilder extends Builder { // private static final String NATURAL_FACE_LINK = "NaturalFaceLink"; // private static final String MANMADE_FACE_LINK = "ManmadeFaceLink"; // private static final String TRINKET_LIST = "TrinketList"; // private static final String RAMP_TRINKET_LIST = "RampTrinketList"; // private static final String EDITOR_ICON_PATH = "EditorIconPath"; // private static final String LINK = "link"; // private static final String PROB = "prob"; // // private NaturalFaceBuilder naturalFaceBuilder = null; // private String naturalFaceBuilderID = ""; // private ManmadeFaceBuilder manmadeFaceBuilder = null; // private String manmadeFaceBuilderID = ""; // private List<TrinketBuilder> trinketBuilders = new ArrayList<>(); // private List<String> trinketBuildersID = new ArrayList<>(); // private List<Double> trinketProbs = new ArrayList<>(); // private List<TrinketBuilder> rampTrinketBuilders = new ArrayList<>(); // private List<String> rampTrinketBuildersID = new ArrayList<>(); // private List<Double> rampTrinketProbs = new ArrayList<>(); // private String editorIconPath = "textures/editor/defaultcliffshapeicon.png"; // // public CliffShapeBuilder(Definition def) { // super(def); // for (DefElement de : def.getElements()) { // switch (de.name) { // case NATURAL_FACE_LINK: // naturalFaceBuilderID = de.getVal(); // break; // case MANMADE_FACE_LINK: // manmadeFaceBuilderID = de.getVal(); // break; // case TRINKET_LIST: // trinketBuildersID.add(de.getVal(LINK)); // trinketProbs.add(de.getDoubleVal(PROB)); // break; // case RAMP_TRINKET_LIST: // rampTrinketBuildersID.add(de.getVal(LINK)); // rampTrinketProbs.add(de.getDoubleVal(PROB)); // break; // case EDITOR_ICON_PATH: // editorIconPath = de.getVal(); // } // } // } // // public void build(Cliff cliff) { // if (naturalFaceBuilder != null) { // cliff.face = naturalFaceBuilder.build(cliff); // } else { // cliff.face = manmadeFaceBuilder.build(cliff); // } // int i = 0; // cliff.trinkets.clear(); // if (cliff.getTile().ramp == null) { // for (TrinketBuilder tb : trinketBuilders) { // if (RandomUtil.next() < trinketProbs.get(i)) { // cliff.trinkets.add(tb.build(cliff)); // } // } // i++; // } else { // for (TrinketBuilder tb : rampTrinketBuilders) { // if (RandomUtil.next() < rampTrinketProbs.get(i)) { // cliff.trinkets.add(tb.build(cliff)); // } // } // i++; // } // } // // public String getID() { // return def.getId(); // } // // public String getIconPath() { // return editorIconPath; // } // // @Override // public void readFinalizedLibrary() { // if (!naturalFaceBuilderID.isEmpty()) { // naturalFaceBuilder = BuilderManager.getNaturalFaceBuilder(naturalFaceBuilderID); // } // if (!manmadeFaceBuilderID.isEmpty()) { // manmadeFaceBuilder = BuilderManager.getManmadeFaceBuilder(manmadeFaceBuilderID); // } // for (String s : trinketBuildersID) { // trinketBuilders.add(BuilderManager.getTrinketBuilder(s)); // } // for (String s : rampTrinketBuildersID) { // rampTrinketBuilders.add(BuilderManager.getTrinketBuilder(s)); // } // } // }
import java.util.ArrayList; import java.util.List; import model.ModelManager; import model.battlefield.map.Tile; import model.builders.MapArtisanUtil; import model.builders.TileArtisanUtil; import model.builders.entity.CliffShapeBuilder; import model.editor.AssetSet; import model.editor.Pencil;
/* * To change this template, choose Tools | Templates and open the template in the editor. */ package model.editor.tools; /** * @author Benoît */ public class CliffTool extends Tool { private static final String RAISE_LOW_OP = "raise/low"; private static final String FLATTEN_OP = "flatten"; int maintainedLevel; public CliffTool() { super(RAISE_LOW_OP, FLATTEN_OP); ArrayList<String> iconPaths = new ArrayList<>();
// Path: core/src/model/builders/entity/CliffShapeBuilder.java // public class CliffShapeBuilder extends Builder { // private static final String NATURAL_FACE_LINK = "NaturalFaceLink"; // private static final String MANMADE_FACE_LINK = "ManmadeFaceLink"; // private static final String TRINKET_LIST = "TrinketList"; // private static final String RAMP_TRINKET_LIST = "RampTrinketList"; // private static final String EDITOR_ICON_PATH = "EditorIconPath"; // private static final String LINK = "link"; // private static final String PROB = "prob"; // // private NaturalFaceBuilder naturalFaceBuilder = null; // private String naturalFaceBuilderID = ""; // private ManmadeFaceBuilder manmadeFaceBuilder = null; // private String manmadeFaceBuilderID = ""; // private List<TrinketBuilder> trinketBuilders = new ArrayList<>(); // private List<String> trinketBuildersID = new ArrayList<>(); // private List<Double> trinketProbs = new ArrayList<>(); // private List<TrinketBuilder> rampTrinketBuilders = new ArrayList<>(); // private List<String> rampTrinketBuildersID = new ArrayList<>(); // private List<Double> rampTrinketProbs = new ArrayList<>(); // private String editorIconPath = "textures/editor/defaultcliffshapeicon.png"; // // public CliffShapeBuilder(Definition def) { // super(def); // for (DefElement de : def.getElements()) { // switch (de.name) { // case NATURAL_FACE_LINK: // naturalFaceBuilderID = de.getVal(); // break; // case MANMADE_FACE_LINK: // manmadeFaceBuilderID = de.getVal(); // break; // case TRINKET_LIST: // trinketBuildersID.add(de.getVal(LINK)); // trinketProbs.add(de.getDoubleVal(PROB)); // break; // case RAMP_TRINKET_LIST: // rampTrinketBuildersID.add(de.getVal(LINK)); // rampTrinketProbs.add(de.getDoubleVal(PROB)); // break; // case EDITOR_ICON_PATH: // editorIconPath = de.getVal(); // } // } // } // // public void build(Cliff cliff) { // if (naturalFaceBuilder != null) { // cliff.face = naturalFaceBuilder.build(cliff); // } else { // cliff.face = manmadeFaceBuilder.build(cliff); // } // int i = 0; // cliff.trinkets.clear(); // if (cliff.getTile().ramp == null) { // for (TrinketBuilder tb : trinketBuilders) { // if (RandomUtil.next() < trinketProbs.get(i)) { // cliff.trinkets.add(tb.build(cliff)); // } // } // i++; // } else { // for (TrinketBuilder tb : rampTrinketBuilders) { // if (RandomUtil.next() < rampTrinketProbs.get(i)) { // cliff.trinkets.add(tb.build(cliff)); // } // } // i++; // } // } // // public String getID() { // return def.getId(); // } // // public String getIconPath() { // return editorIconPath; // } // // @Override // public void readFinalizedLibrary() { // if (!naturalFaceBuilderID.isEmpty()) { // naturalFaceBuilder = BuilderManager.getNaturalFaceBuilder(naturalFaceBuilderID); // } // if (!manmadeFaceBuilderID.isEmpty()) { // manmadeFaceBuilder = BuilderManager.getManmadeFaceBuilder(manmadeFaceBuilderID); // } // for (String s : trinketBuildersID) { // trinketBuilders.add(BuilderManager.getTrinketBuilder(s)); // } // for (String s : rampTrinketBuildersID) { // rampTrinketBuilders.add(BuilderManager.getTrinketBuilder(s)); // } // } // } // Path: core/src/model/editor/tools/CliffTool.java import java.util.ArrayList; import java.util.List; import model.ModelManager; import model.battlefield.map.Tile; import model.builders.MapArtisanUtil; import model.builders.TileArtisanUtil; import model.builders.entity.CliffShapeBuilder; import model.editor.AssetSet; import model.editor.Pencil; /* * To change this template, choose Tools | Templates and open the template in the editor. */ package model.editor.tools; /** * @author Benoît */ public class CliffTool extends Tool { private static final String RAISE_LOW_OP = "raise/low"; private static final String FLATTEN_OP = "flatten"; int maintainedLevel; public CliffTool() { super(RAISE_LOW_OP, FLATTEN_OP); ArrayList<String> iconPaths = new ArrayList<>();
for (CliffShapeBuilder b : ModelManager.getBattlefield().getMap().getStyle().cliffShapeBuilders) {
methusalah/OpenRTS
core/src/controller/editor/EditorInputInterpreter.java
// Path: core/src/event/ControllerChangeEvent.java // public class ControllerChangeEvent extends Event { // // private final int index; // // public ControllerChangeEvent(int ctrlIndex) { // this.index = ctrlIndex; // } // // public int getControllerIndex() { // return index; // } // }
import model.ModelManager; import model.battlefield.lighting.SunLight; import model.editor.ToolManager; import com.jme3.input.InputManager; import com.jme3.input.KeyInput; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseButtonTrigger; import controller.InputInterpreter; import controller.Reporter; import event.ControllerChangeEvent; import event.EventManager;
break; } } } @Override public void onAction(String name, boolean isPressed, float tpf) { if (!isPressed) { switch (name) { case PRIMARY_ACTION: ToolManager.primaryAction(); analogUnpressed = true; break; case SECONDARY_ACTION: ToolManager.secondaryAction(); analogUnpressed = true; break; case INC_DAYTIME: case DEC_DAYTIME: case COMPASS_EAST: case COMPASS_WEST: case INC_INTENSITY: case DEC_INTENSITY: case DEC_RED: case DEC_GREEN: case DEC_BLUE: analogUnpressed = true; break; case SWITCH_CTRL_1:
// Path: core/src/event/ControllerChangeEvent.java // public class ControllerChangeEvent extends Event { // // private final int index; // // public ControllerChangeEvent(int ctrlIndex) { // this.index = ctrlIndex; // } // // public int getControllerIndex() { // return index; // } // } // Path: core/src/controller/editor/EditorInputInterpreter.java import model.ModelManager; import model.battlefield.lighting.SunLight; import model.editor.ToolManager; import com.jme3.input.InputManager; import com.jme3.input.KeyInput; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseButtonTrigger; import controller.InputInterpreter; import controller.Reporter; import event.ControllerChangeEvent; import event.EventManager; break; } } } @Override public void onAction(String name, boolean isPressed, float tpf) { if (!isPressed) { switch (name) { case PRIMARY_ACTION: ToolManager.primaryAction(); analogUnpressed = true; break; case SECONDARY_ACTION: ToolManager.secondaryAction(); analogUnpressed = true; break; case INC_DAYTIME: case DEC_DAYTIME: case COMPASS_EAST: case COMPASS_WEST: case INC_INTENSITY: case DEC_INTENSITY: case DEC_RED: case DEC_GREEN: case DEC_BLUE: analogUnpressed = true; break; case SWITCH_CTRL_1:
EventManager.post(new ControllerChangeEvent(0));
methusalah/OpenRTS
core/src/model/battlefield/army/Engagement.java
// Path: core/src/model/battlefield/army/components/UnitMemento.java // public class UnitMemento { // @JsonProperty // private String builderID; // @JsonProperty // private String factionName; // @JsonProperty // private Point3D pos; // @JsonProperty // private double orientation; // // public UnitMemento() { // // } // // public UnitMemento(Unit u) { // builderID = u.builderID; // factionName = u.faction.getName(); // pos = u.pos; // orientation = u.getOrientation(); // } // // public Unit getUnit(List<Faction> factions) { // for(Faction f : factions) { // if (f.getName().equals(factionName)) { // Unit u = BuilderManager.getUnitBuilder(builderID).build(f, pos, orientation); // u.drawOnBattlefield(); // return u; // } // } // throw new RuntimeException("impossible to build unit, check faction names"); // } // }
import java.awt.Color; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import model.battlefield.army.components.Unit; import model.battlefield.army.components.UnitMemento; import model.battlefield.warfare.Faction; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty;
package model.battlefield.army; /** * Stores units and factions, and provide a serializable version of the initial situation */ public class Engagement { private static final Logger logger = Logger.getLogger(Engagement.class.getName()); @JsonIgnore private List<Faction> factions = new ArrayList<>(); @JsonProperty
// Path: core/src/model/battlefield/army/components/UnitMemento.java // public class UnitMemento { // @JsonProperty // private String builderID; // @JsonProperty // private String factionName; // @JsonProperty // private Point3D pos; // @JsonProperty // private double orientation; // // public UnitMemento() { // // } // // public UnitMemento(Unit u) { // builderID = u.builderID; // factionName = u.faction.getName(); // pos = u.pos; // orientation = u.getOrientation(); // } // // public Unit getUnit(List<Faction> factions) { // for(Faction f : factions) { // if (f.getName().equals(factionName)) { // Unit u = BuilderManager.getUnitBuilder(builderID).build(f, pos, orientation); // u.drawOnBattlefield(); // return u; // } // } // throw new RuntimeException("impossible to build unit, check faction names"); // } // } // Path: core/src/model/battlefield/army/Engagement.java import java.awt.Color; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import model.battlefield.army.components.Unit; import model.battlefield.army.components.UnitMemento; import model.battlefield.warfare.Faction; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; package model.battlefield.army; /** * Stores units and factions, and provide a serializable version of the initial situation */ public class Engagement { private static final Logger logger = Logger.getLogger(Engagement.class.getName()); @JsonIgnore private List<Faction> factions = new ArrayList<>(); @JsonProperty
private List<UnitMemento> initialEngagement = new ArrayList<>();
methusalah/OpenRTS
core/src/controller/battlefield/BattlefieldInputInterpreter.java
// Path: core/src/event/ControllerChangeEvent.java // public class ControllerChangeEvent extends Event { // // private final int index; // // public ControllerChangeEvent(int ctrlIndex) { // this.index = ctrlIndex; // } // // public int getControllerIndex() { // return index; // } // }
import event.ControllerChangeEvent; import event.EventManager; import geometry.geom2d.Point2D; import java.util.logging.Logger; import model.CommandManager; import com.jme3.input.InputManager; import com.jme3.input.KeyInput; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseButtonTrigger; import controller.InputInterpreter;
inputManager.addMapping(MOVE_ATTACK, new KeyTrigger(KeyInput.KEY_A)); inputManager.addMapping(MULTIPLE_SELECTION, new KeyTrigger(KeyInput.KEY_LCONTROL), new KeyTrigger(KeyInput.KEY_RCONTROL)); inputManager.addMapping(HOLD, new KeyTrigger(KeyInput.KEY_H)); inputManager.addMapping(PAUSE, new KeyTrigger(KeyInput.KEY_SPACE)); inputManager.addListener(this, mappings); logger.info("battlefield controller online"); } @Override protected void unregisterInputs(InputManager inputManager) { for (String s : mappings) { if (inputManager.hasMapping(s)) { inputManager.deleteMapping(s); } } inputManager.removeListener(this); } @Override public void onAnalog(String name, float value, float tpf) { } @Override public void onAction(String name, boolean isPressed, float tpf) { if (!isPressed) { switch (name) { case SWITCH_CTRL_1:
// Path: core/src/event/ControllerChangeEvent.java // public class ControllerChangeEvent extends Event { // // private final int index; // // public ControllerChangeEvent(int ctrlIndex) { // this.index = ctrlIndex; // } // // public int getControllerIndex() { // return index; // } // } // Path: core/src/controller/battlefield/BattlefieldInputInterpreter.java import event.ControllerChangeEvent; import event.EventManager; import geometry.geom2d.Point2D; import java.util.logging.Logger; import model.CommandManager; import com.jme3.input.InputManager; import com.jme3.input.KeyInput; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseButtonTrigger; import controller.InputInterpreter; inputManager.addMapping(MOVE_ATTACK, new KeyTrigger(KeyInput.KEY_A)); inputManager.addMapping(MULTIPLE_SELECTION, new KeyTrigger(KeyInput.KEY_LCONTROL), new KeyTrigger(KeyInput.KEY_RCONTROL)); inputManager.addMapping(HOLD, new KeyTrigger(KeyInput.KEY_H)); inputManager.addMapping(PAUSE, new KeyTrigger(KeyInput.KEY_SPACE)); inputManager.addListener(this, mappings); logger.info("battlefield controller online"); } @Override protected void unregisterInputs(InputManager inputManager) { for (String s : mappings) { if (inputManager.hasMapping(s)) { inputManager.deleteMapping(s); } } inputManager.removeListener(this); } @Override public void onAnalog(String name, float value, float tpf) { } @Override public void onAction(String name, boolean isPressed, float tpf) { if (!isPressed) { switch (name) { case SWITCH_CTRL_1:
EventManager.post(new ControllerChangeEvent(0));
google/live-transcribe-speech-engine
app/src/main/java/com/google/audio/asr/TranscriptionResultReceiver.java
// Path: app/src/main/java/com/google/audio/asr/RequestForRecognitionThread.java // public enum Action { // NO_ACTION, // HANDLE_NETWORK_CONNECTION_FATAL_ERROR, // HANDLE_NON_NETWORK_CONNECTION_FATAL_ERROR, // OK_TO_TERMINATE_SESSION, // POST_RESULTS, // REQUEST_TO_END_SESSION, // RESET_SESSION, // RESET_SESSION_AND_CLEAR_TRANSCRIPT, // }
import com.google.audio.asr.RequestForRecognitionThread.Action; import com.google.common.base.Objects; import com.google.common.flogger.FluentLogger; import java.lang.ref.WeakReference;
/* * Copyright 2019 Google LLC * * 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 * * https://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.audio.asr; /** * Handles results as they come in from the recognition module and posts them back to the * RepeatingRecognitionSession. */ class TranscriptionResultReceiver implements SpeechSessionListener { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final WeakReference<RepeatingRecognitionSession.PostHandler> postHandlerRef; public TranscriptionResultReceiver(RepeatingRecognitionSession.PostHandler postHandler) { this.postHandlerRef = new WeakReference<>(postHandler); } @Override public void onSessionFatalError(int sessionID, Throwable error) { logger.atSevere().withCause(error).log("Session #%d ended fatally.", sessionID); post( RequestForRecognitionThread.newBuilder() .setAction( errorIndicatesLossOfConnection(error)
// Path: app/src/main/java/com/google/audio/asr/RequestForRecognitionThread.java // public enum Action { // NO_ACTION, // HANDLE_NETWORK_CONNECTION_FATAL_ERROR, // HANDLE_NON_NETWORK_CONNECTION_FATAL_ERROR, // OK_TO_TERMINATE_SESSION, // POST_RESULTS, // REQUEST_TO_END_SESSION, // RESET_SESSION, // RESET_SESSION_AND_CLEAR_TRANSCRIPT, // } // Path: app/src/main/java/com/google/audio/asr/TranscriptionResultReceiver.java import com.google.audio.asr.RequestForRecognitionThread.Action; import com.google.common.base.Objects; import com.google.common.flogger.FluentLogger; import java.lang.ref.WeakReference; /* * Copyright 2019 Google LLC * * 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 * * https://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.audio.asr; /** * Handles results as they come in from the recognition module and posts them back to the * RepeatingRecognitionSession. */ class TranscriptionResultReceiver implements SpeechSessionListener { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final WeakReference<RepeatingRecognitionSession.PostHandler> postHandlerRef; public TranscriptionResultReceiver(RepeatingRecognitionSession.PostHandler postHandler) { this.postHandlerRef = new WeakReference<>(postHandler); } @Override public void onSessionFatalError(int sessionID, Throwable error) { logger.atSevere().withCause(error).log("Session #%d ended fatally.", sessionID); post( RequestForRecognitionThread.newBuilder() .setAction( errorIndicatesLossOfConnection(error)
? Action.HANDLE_NETWORK_CONNECTION_FATAL_ERROR
google/live-transcribe-speech-engine
app/src/main/java/com/google/audio/asr/cloud/CloudSpeechStreamObserver.java
// Path: app/src/main/java/com/google/audio/asr/SpeechSessionListener.java // public interface SpeechSessionListener { // /** // * Tells the client that the recognizer has had an error from which we cannot recover. It is safe // * to terminate the session. // */ // void onSessionFatalError(int sessionID, Throwable error); // // /** // * Notifies that a new transcription result is available. If resultIsFinal is false, the results // * are subject to change. // */ // void onResults(int sessionID, TranscriptionResult result, boolean resultIsFinal); // // /** Signals that no more audio should be sent to the recognizer. */ // void onDoneListening(int sessionID); // // /** // * Notifies that it is safe to kill the session. Called when the recognizer is done returning // * results. // */ // void onOkToTerminateSession(int sessionID); // } // // Path: app/src/main/java/com/google/audio/asr/TimeUtil.java // public final class TimeUtil { // public static Instant toInstant(Timestamp t) { // return new Instant(Timestamps.toMillis(t)); // } // // public static Timestamp toTimestamp(Instant t) { // return Timestamps.fromMillis(t.getMillis()); // } // // public static Duration convert(com.google.protobuf.Duration d) { // return Duration.millis(Durations.toMillis(d)); // } // // public static com.google.protobuf.Duration convert(Duration d) { // return Durations.fromMillis(d.getMillis()); // } // private TimeUtil() {} // }
import org.joda.time.Duration; import org.joda.time.Instant; import com.google.audio.asr.CloudSpeechStreamObserverParams; import com.google.audio.asr.SpeechSessionListener; import com.google.audio.asr.TimeUtil; import com.google.audio.asr.TranscriptionResult; import com.google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative; import com.google.cloud.speech.v1p1beta1.StreamingRecognitionResult; import com.google.cloud.speech.v1p1beta1.StreamingRecognizeResponse; import com.google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.SpeechEventType; import com.google.cloud.speech.v1p1beta1.WordInfo; import com.google.common.base.Optional; import com.google.common.flogger.FluentLogger; import io.grpc.stub.StreamObserver; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference;
/* * Copyright 2019 Google LLC * * 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 * * https://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.audio.asr.cloud; /** * Parses Cloud Speech API GRPC StreamingRecognizeResponse events into CloudSpeechSessionListener * events. * NOTE: that this object is stateful and needs to be re-instantiated for each streaming * request. * * Threading: All methods that implement the StreamObserver interface are to be called by gRPC. This * is the "results thread" as documented in the RepeatingRecognitionSession. The other public * functions are safe to call from another thread, they are called by CloudSpeechSession in the * current implementation. */ public class CloudSpeechStreamObserver implements StreamObserver<StreamingRecognizeResponse> { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); // The CloudSpeech API imposes a maximum streaming time of 5 minutes. In order to avoid hitting // this, but still be compatible with singleUtterance = false mode, which is required by some // models, we attempt to close the session after receiving a finalized result after being opened // for MIN_TIME_TO_KEEP_SESSION_OPEN. private static final Duration MIN_TIME_TO_KEEP_SESSION_OPEN = Duration.standardMinutes(4).plus(Duration.standardSeconds(30));
// Path: app/src/main/java/com/google/audio/asr/SpeechSessionListener.java // public interface SpeechSessionListener { // /** // * Tells the client that the recognizer has had an error from which we cannot recover. It is safe // * to terminate the session. // */ // void onSessionFatalError(int sessionID, Throwable error); // // /** // * Notifies that a new transcription result is available. If resultIsFinal is false, the results // * are subject to change. // */ // void onResults(int sessionID, TranscriptionResult result, boolean resultIsFinal); // // /** Signals that no more audio should be sent to the recognizer. */ // void onDoneListening(int sessionID); // // /** // * Notifies that it is safe to kill the session. Called when the recognizer is done returning // * results. // */ // void onOkToTerminateSession(int sessionID); // } // // Path: app/src/main/java/com/google/audio/asr/TimeUtil.java // public final class TimeUtil { // public static Instant toInstant(Timestamp t) { // return new Instant(Timestamps.toMillis(t)); // } // // public static Timestamp toTimestamp(Instant t) { // return Timestamps.fromMillis(t.getMillis()); // } // // public static Duration convert(com.google.protobuf.Duration d) { // return Duration.millis(Durations.toMillis(d)); // } // // public static com.google.protobuf.Duration convert(Duration d) { // return Durations.fromMillis(d.getMillis()); // } // private TimeUtil() {} // } // Path: app/src/main/java/com/google/audio/asr/cloud/CloudSpeechStreamObserver.java import org.joda.time.Duration; import org.joda.time.Instant; import com.google.audio.asr.CloudSpeechStreamObserverParams; import com.google.audio.asr.SpeechSessionListener; import com.google.audio.asr.TimeUtil; import com.google.audio.asr.TranscriptionResult; import com.google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative; import com.google.cloud.speech.v1p1beta1.StreamingRecognitionResult; import com.google.cloud.speech.v1p1beta1.StreamingRecognizeResponse; import com.google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.SpeechEventType; import com.google.cloud.speech.v1p1beta1.WordInfo; import com.google.common.base.Optional; import com.google.common.flogger.FluentLogger; import io.grpc.stub.StreamObserver; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /* * Copyright 2019 Google LLC * * 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 * * https://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.audio.asr.cloud; /** * Parses Cloud Speech API GRPC StreamingRecognizeResponse events into CloudSpeechSessionListener * events. * NOTE: that this object is stateful and needs to be re-instantiated for each streaming * request. * * Threading: All methods that implement the StreamObserver interface are to be called by gRPC. This * is the "results thread" as documented in the RepeatingRecognitionSession. The other public * functions are safe to call from another thread, they are called by CloudSpeechSession in the * current implementation. */ public class CloudSpeechStreamObserver implements StreamObserver<StreamingRecognizeResponse> { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); // The CloudSpeech API imposes a maximum streaming time of 5 minutes. In order to avoid hitting // this, but still be compatible with singleUtterance = false mode, which is required by some // models, we attempt to close the session after receiving a finalized result after being opened // for MIN_TIME_TO_KEEP_SESSION_OPEN. private static final Duration MIN_TIME_TO_KEEP_SESSION_OPEN = Duration.standardMinutes(4).plus(Duration.standardSeconds(30));
private final SpeechSessionListener speechSessionListener;
google/live-transcribe-speech-engine
app/src/main/java/com/google/audio/asr/cloud/TimestampCalculator.java
// Path: app/src/main/java/com/google/audio/asr/TimeUtil.java // public final class TimeUtil { // public static Instant toInstant(Timestamp t) { // return new Instant(Timestamps.toMillis(t)); // } // // public static Timestamp toTimestamp(Instant t) { // return Timestamps.fromMillis(t.getMillis()); // } // // public static Duration convert(com.google.protobuf.Duration d) { // return Duration.millis(Durations.toMillis(d)); // } // // public static com.google.protobuf.Duration convert(Duration d) { // return Durations.fromMillis(d.getMillis()); // } // private TimeUtil() {} // }
import com.google.audio.asr.TimeUtil; import com.google.audio.asr.TranscriptionResult; import com.google.cloud.speech.v1p1beta1.WordInfo; import com.google.common.base.Splitter; import com.google.protobuf.Timestamp; import java.util.ArrayList; import java.util.List; import org.joda.time.Duration; import org.joda.time.Instant;
/* * Copyright 2019 Google LLC * * 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 * * https://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.audio.asr.cloud; /** * Calculates unfinalized and finalized timestamps and adds them to the word-level details of * utterances. Finalized timestamps are simply copied from the corresponding timestamps returned by * the cloud. Unfinalized timestamps do not exist in the response returned by the cloud, so they are * computed from the returned transcript instead. */ public class TimestampCalculator { /** * Keeps track of the session start time because the finalized word times are relative to the time * of the beginning of the session. */ private final Instant sessionStartTime; /** * Stores the time instants of each word in the un-finalized utterance. As the utterance is * updated with more words, this array marks the time of the new words. */ private final ArrayList<Instant> unfinalizedWordInstants = new ArrayList<>(); private static final int NANOS_PER_MILLIS = 1_000_000; public TimestampCalculator(Instant newSessionStartTime) { this.sessionStartTime = newSessionStartTime; } public Timestamp getFinalizedStartTimestamp(WordInfo wordInfo) { Duration startOffset = Duration.standardSeconds(wordInfo.getStartTime().getSeconds()) .plus(Duration.millis(wordInfo.getStartTime().getNanos() / NANOS_PER_MILLIS));
// Path: app/src/main/java/com/google/audio/asr/TimeUtil.java // public final class TimeUtil { // public static Instant toInstant(Timestamp t) { // return new Instant(Timestamps.toMillis(t)); // } // // public static Timestamp toTimestamp(Instant t) { // return Timestamps.fromMillis(t.getMillis()); // } // // public static Duration convert(com.google.protobuf.Duration d) { // return Duration.millis(Durations.toMillis(d)); // } // // public static com.google.protobuf.Duration convert(Duration d) { // return Durations.fromMillis(d.getMillis()); // } // private TimeUtil() {} // } // Path: app/src/main/java/com/google/audio/asr/cloud/TimestampCalculator.java import com.google.audio.asr.TimeUtil; import com.google.audio.asr.TranscriptionResult; import com.google.cloud.speech.v1p1beta1.WordInfo; import com.google.common.base.Splitter; import com.google.protobuf.Timestamp; import java.util.ArrayList; import java.util.List; import org.joda.time.Duration; import org.joda.time.Instant; /* * Copyright 2019 Google LLC * * 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 * * https://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.audio.asr.cloud; /** * Calculates unfinalized and finalized timestamps and adds them to the word-level details of * utterances. Finalized timestamps are simply copied from the corresponding timestamps returned by * the cloud. Unfinalized timestamps do not exist in the response returned by the cloud, so they are * computed from the returned transcript instead. */ public class TimestampCalculator { /** * Keeps track of the session start time because the finalized word times are relative to the time * of the beginning of the session. */ private final Instant sessionStartTime; /** * Stores the time instants of each word in the un-finalized utterance. As the utterance is * updated with more words, this array marks the time of the new words. */ private final ArrayList<Instant> unfinalizedWordInstants = new ArrayList<>(); private static final int NANOS_PER_MILLIS = 1_000_000; public TimestampCalculator(Instant newSessionStartTime) { this.sessionStartTime = newSessionStartTime; } public Timestamp getFinalizedStartTimestamp(WordInfo wordInfo) { Duration startOffset = Duration.standardSeconds(wordInfo.getStartTime().getSeconds()) .plus(Duration.millis(wordInfo.getStartTime().getNanos() / NANOS_PER_MILLIS));
return TimeUtil.toTimestamp(sessionStartTime.plus(startOffset));
statful/statful-client-vertx
src/test/java/com/statful/client/IntegrationTestCase.java
// Path: src/main/java/com/statful/tag/Tags.java // public enum Tags { // // /** // * Used to identify requests that you want to track // */ // TRACK_HEADER("X-Statful"); // // /** // * Value that will be used has header // */ // private final String value; // // Tags(final String value) { // this.value = value; // } // // @Override // public String toString() { // return value; // } // }
import com.statful.tag.Tags; import io.netty.util.internal.ThreadLocalRandom; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpServer; import io.vertx.ext.unit.TestContext; import java.util.List;
package com.statful.client; class IntegrationTestCase { private static final int HTTP_PORT = 1235; private static final String HOST = "0.0.0.0"; private HttpServer httpReceiver; void setUpHttpReceiver(Vertx vertx) { this.httpReceiver = vertx.createHttpServer(); } void configureHttpReceiver(final Vertx vertx, final TestContext context, final List<String> requestsWithIgnore) { httpReceiver.requestHandler(request -> { // create a delay to simulate a lengthy api call long delay = ThreadLocalRandom.current().nextInt(200, 1000 + 1); vertx.setTimer(delay, event -> request.response().end("hey!")); }).listen(HTTP_PORT, HOST, listenResult -> { if (listenResult.succeeded()) { this.makeHttpRequests(vertx, context, requestsWithIgnore); } else { context.fail(listenResult.cause()); } }); } private void makeHttpRequests(Vertx vertx, TestContext context, List<String> requests) { requests.forEach(requestValue -> { // confirm that all requests have a 200 status code HttpClientRequest request = vertx.createHttpClient().get(HTTP_PORT, HOST, "/" + requestValue, event -> context.assertTrue(event.statusCode() == 200));
// Path: src/main/java/com/statful/tag/Tags.java // public enum Tags { // // /** // * Used to identify requests that you want to track // */ // TRACK_HEADER("X-Statful"); // // /** // * Value that will be used has header // */ // private final String value; // // Tags(final String value) { // this.value = value; // } // // @Override // public String toString() { // return value; // } // } // Path: src/test/java/com/statful/client/IntegrationTestCase.java import com.statful.tag.Tags; import io.netty.util.internal.ThreadLocalRandom; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpServer; import io.vertx.ext.unit.TestContext; import java.util.List; package com.statful.client; class IntegrationTestCase { private static final int HTTP_PORT = 1235; private static final String HOST = "0.0.0.0"; private HttpServer httpReceiver; void setUpHttpReceiver(Vertx vertx) { this.httpReceiver = vertx.createHttpServer(); } void configureHttpReceiver(final Vertx vertx, final TestContext context, final List<String> requestsWithIgnore) { httpReceiver.requestHandler(request -> { // create a delay to simulate a lengthy api call long delay = ThreadLocalRandom.current().nextInt(200, 1000 + 1); vertx.setTimer(delay, event -> request.response().end("hey!")); }).listen(HTTP_PORT, HOST, listenResult -> { if (listenResult.succeeded()) { this.makeHttpRequests(vertx, context, requestsWithIgnore); } else { context.fail(listenResult.cause()); } }); } private void makeHttpRequests(Vertx vertx, TestContext context, List<String> requests) { requests.forEach(requestValue -> { // confirm that all requests have a 200 status code HttpClientRequest request = vertx.createHttpClient().get(HTTP_PORT, HOST, "/" + requestValue, event -> context.assertTrue(event.statusCode() == 200));
request.headers().add(Tags.TRACK_HEADER.toString(), requestValue);
statful/statful-client-vertx
src/main/java/com/statful/client/VertxMetricsImpl.java
// Path: src/main/java/com/statful/sender/Sender.java // public interface Sender { // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // * @param sentHandler handler called if you want to be notified after the metrics are sent. // */ // void send(@Nonnull List<DataPoint> metrics, @Nonnull Handler<AsyncResult<Void>> sentHandler); // // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // */ // void send(@Nonnull List<DataPoint> metrics); // // /** // * Stores metric in a buffer to be sent // * // * @param dataPoint metric to be stored // * @return true if the metric was inserted false otherwise // */ // boolean addMetric(final DataPoint dataPoint); // // /** // * Closes the sender // * // * @param handler to execute when closed // */ // void close(final Handler<AsyncResult<Void>> handler); // } // // Path: src/main/java/com/statful/sender/SenderFactory.java // public final class SenderFactory { // // private static final Logger LOGGER = LoggerFactory.getLogger(SenderFactory.class); // // /** // * @param vertx Vertx instance to create the senders // * @param options statful options to configure the sender // * @return correct client instance for the configuration provided // */ // @Nonnull // public Sender create(final Vertx vertx, @Nonnull final StatfulMetricsOptions options) { // Objects.requireNonNull(options); // // Transport transport = options.getTransport(); // if (Transport.UDP.equals(transport)) { // LOGGER.info("creating udp sender"); // return new UDPSender(vertx, options); // } else if (Transport.HTTP.equals(transport)) { // LOGGER.info("creating http sender"); // return new HttpSender(vertx, options); // } // throw new UnsupportedOperationException("currently only UDP and HTTP are supported. Requested: " + options.getTransport()); // } // }
import com.statful.collector.*; import com.statful.sender.Sender; import com.statful.sender.SenderFactory; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.net.SocketAddress; import io.vertx.core.spi.metrics.HttpClientMetrics; import io.vertx.core.spi.metrics.HttpServerMetrics; import io.vertx.core.spi.metrics.PoolMetrics; import io.vertx.core.spi.metrics.VertxMetrics; import java.util.concurrent.LinkedBlockingQueue;
package com.statful.client; /** * VertxMetrics SPI implementation for statful metrics collection */ final class VertxMetricsImpl implements VertxMetrics { /** * Collectors and client configuration */ private final StatfulMetricsOptions statfulMetricsOptions; /** * Instance of a sender to push metrics to statful. */
// Path: src/main/java/com/statful/sender/Sender.java // public interface Sender { // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // * @param sentHandler handler called if you want to be notified after the metrics are sent. // */ // void send(@Nonnull List<DataPoint> metrics, @Nonnull Handler<AsyncResult<Void>> sentHandler); // // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // */ // void send(@Nonnull List<DataPoint> metrics); // // /** // * Stores metric in a buffer to be sent // * // * @param dataPoint metric to be stored // * @return true if the metric was inserted false otherwise // */ // boolean addMetric(final DataPoint dataPoint); // // /** // * Closes the sender // * // * @param handler to execute when closed // */ // void close(final Handler<AsyncResult<Void>> handler); // } // // Path: src/main/java/com/statful/sender/SenderFactory.java // public final class SenderFactory { // // private static final Logger LOGGER = LoggerFactory.getLogger(SenderFactory.class); // // /** // * @param vertx Vertx instance to create the senders // * @param options statful options to configure the sender // * @return correct client instance for the configuration provided // */ // @Nonnull // public Sender create(final Vertx vertx, @Nonnull final StatfulMetricsOptions options) { // Objects.requireNonNull(options); // // Transport transport = options.getTransport(); // if (Transport.UDP.equals(transport)) { // LOGGER.info("creating udp sender"); // return new UDPSender(vertx, options); // } else if (Transport.HTTP.equals(transport)) { // LOGGER.info("creating http sender"); // return new HttpSender(vertx, options); // } // throw new UnsupportedOperationException("currently only UDP and HTTP are supported. Requested: " + options.getTransport()); // } // } // Path: src/main/java/com/statful/client/VertxMetricsImpl.java import com.statful.collector.*; import com.statful.sender.Sender; import com.statful.sender.SenderFactory; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.net.SocketAddress; import io.vertx.core.spi.metrics.HttpClientMetrics; import io.vertx.core.spi.metrics.HttpServerMetrics; import io.vertx.core.spi.metrics.PoolMetrics; import io.vertx.core.spi.metrics.VertxMetrics; import java.util.concurrent.LinkedBlockingQueue; package com.statful.client; /** * VertxMetrics SPI implementation for statful metrics collection */ final class VertxMetricsImpl implements VertxMetrics { /** * Collectors and client configuration */ private final StatfulMetricsOptions statfulMetricsOptions; /** * Instance of a sender to push metrics to statful. */
private Sender sender;
statful/statful-client-vertx
src/main/java/com/statful/client/VertxMetricsImpl.java
// Path: src/main/java/com/statful/sender/Sender.java // public interface Sender { // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // * @param sentHandler handler called if you want to be notified after the metrics are sent. // */ // void send(@Nonnull List<DataPoint> metrics, @Nonnull Handler<AsyncResult<Void>> sentHandler); // // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // */ // void send(@Nonnull List<DataPoint> metrics); // // /** // * Stores metric in a buffer to be sent // * // * @param dataPoint metric to be stored // * @return true if the metric was inserted false otherwise // */ // boolean addMetric(final DataPoint dataPoint); // // /** // * Closes the sender // * // * @param handler to execute when closed // */ // void close(final Handler<AsyncResult<Void>> handler); // } // // Path: src/main/java/com/statful/sender/SenderFactory.java // public final class SenderFactory { // // private static final Logger LOGGER = LoggerFactory.getLogger(SenderFactory.class); // // /** // * @param vertx Vertx instance to create the senders // * @param options statful options to configure the sender // * @return correct client instance for the configuration provided // */ // @Nonnull // public Sender create(final Vertx vertx, @Nonnull final StatfulMetricsOptions options) { // Objects.requireNonNull(options); // // Transport transport = options.getTransport(); // if (Transport.UDP.equals(transport)) { // LOGGER.info("creating udp sender"); // return new UDPSender(vertx, options); // } else if (Transport.HTTP.equals(transport)) { // LOGGER.info("creating http sender"); // return new HttpSender(vertx, options); // } // throw new UnsupportedOperationException("currently only UDP and HTTP are supported. Requested: " + options.getTransport()); // } // }
import com.statful.collector.*; import com.statful.sender.Sender; import com.statful.sender.SenderFactory; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.net.SocketAddress; import io.vertx.core.spi.metrics.HttpClientMetrics; import io.vertx.core.spi.metrics.HttpServerMetrics; import io.vertx.core.spi.metrics.PoolMetrics; import io.vertx.core.spi.metrics.VertxMetrics; import java.util.concurrent.LinkedBlockingQueue;
} return httpClientMetrics; } /** * We lazy load the pool metrics sender because it needs a vertx instance, and it is called before it is created because * of vertx's own thread pool instantiated on creation. */ @Override public PoolMetrics<?> createPoolMetrics(final String poolType, final String poolName, final int maxPoolSize) { PoolMetricsImpl poolMetrics = null; if (statfulMetricsOptions.isEnablePoolMetrics()) { poolMetrics = new PoolMetricsImpl(statfulMetricsOptions, poolType, poolName, maxPoolSize); collectors.add(poolMetrics); } return poolMetrics; } @Override public void vertxCreated(final Vertx createdVertx) { this.vertx = createdVertx; this.customMetricsConsumer = new CustomMetricsConsumer(createdVertx.eventBus(), this.getOrCreateSender(createdVertx), statfulMetricsOptions); this.collectors.forEach(collector -> { collector.setVertx(createdVertx); collector.setSender(this.getOrCreateSender(createdVertx)); }); } private Sender getOrCreateSender(final Vertx senderVertx) { if (this.sender == null) {
// Path: src/main/java/com/statful/sender/Sender.java // public interface Sender { // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // * @param sentHandler handler called if you want to be notified after the metrics are sent. // */ // void send(@Nonnull List<DataPoint> metrics, @Nonnull Handler<AsyncResult<Void>> sentHandler); // // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // */ // void send(@Nonnull List<DataPoint> metrics); // // /** // * Stores metric in a buffer to be sent // * // * @param dataPoint metric to be stored // * @return true if the metric was inserted false otherwise // */ // boolean addMetric(final DataPoint dataPoint); // // /** // * Closes the sender // * // * @param handler to execute when closed // */ // void close(final Handler<AsyncResult<Void>> handler); // } // // Path: src/main/java/com/statful/sender/SenderFactory.java // public final class SenderFactory { // // private static final Logger LOGGER = LoggerFactory.getLogger(SenderFactory.class); // // /** // * @param vertx Vertx instance to create the senders // * @param options statful options to configure the sender // * @return correct client instance for the configuration provided // */ // @Nonnull // public Sender create(final Vertx vertx, @Nonnull final StatfulMetricsOptions options) { // Objects.requireNonNull(options); // // Transport transport = options.getTransport(); // if (Transport.UDP.equals(transport)) { // LOGGER.info("creating udp sender"); // return new UDPSender(vertx, options); // } else if (Transport.HTTP.equals(transport)) { // LOGGER.info("creating http sender"); // return new HttpSender(vertx, options); // } // throw new UnsupportedOperationException("currently only UDP and HTTP are supported. Requested: " + options.getTransport()); // } // } // Path: src/main/java/com/statful/client/VertxMetricsImpl.java import com.statful.collector.*; import com.statful.sender.Sender; import com.statful.sender.SenderFactory; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.net.SocketAddress; import io.vertx.core.spi.metrics.HttpClientMetrics; import io.vertx.core.spi.metrics.HttpServerMetrics; import io.vertx.core.spi.metrics.PoolMetrics; import io.vertx.core.spi.metrics.VertxMetrics; import java.util.concurrent.LinkedBlockingQueue; } return httpClientMetrics; } /** * We lazy load the pool metrics sender because it needs a vertx instance, and it is called before it is created because * of vertx's own thread pool instantiated on creation. */ @Override public PoolMetrics<?> createPoolMetrics(final String poolType, final String poolName, final int maxPoolSize) { PoolMetricsImpl poolMetrics = null; if (statfulMetricsOptions.isEnablePoolMetrics()) { poolMetrics = new PoolMetricsImpl(statfulMetricsOptions, poolType, poolName, maxPoolSize); collectors.add(poolMetrics); } return poolMetrics; } @Override public void vertxCreated(final Vertx createdVertx) { this.vertx = createdVertx; this.customMetricsConsumer = new CustomMetricsConsumer(createdVertx.eventBus(), this.getOrCreateSender(createdVertx), statfulMetricsOptions); this.collectors.forEach(collector -> { collector.setVertx(createdVertx); collector.setSender(this.getOrCreateSender(createdVertx)); }); } private Sender getOrCreateSender(final Vertx senderVertx) { if (this.sender == null) {
this.sender = new SenderFactory().create(senderVertx, statfulMetricsOptions);
statful/statful-client-vertx
src/main/java/com/statful/client/CustomMetricsConsumer.java
// Path: src/main/java/com/statful/sender/Sender.java // public interface Sender { // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // * @param sentHandler handler called if you want to be notified after the metrics are sent. // */ // void send(@Nonnull List<DataPoint> metrics, @Nonnull Handler<AsyncResult<Void>> sentHandler); // // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // */ // void send(@Nonnull List<DataPoint> metrics); // // /** // * Stores metric in a buffer to be sent // * // * @param dataPoint metric to be stored // * @return true if the metric was inserted false otherwise // */ // boolean addMetric(final DataPoint dataPoint); // // /** // * Closes the sender // * // * @param handler to execute when closed // */ // void close(final Handler<AsyncResult<Void>> handler); // }
import com.statful.sender.Sender; import io.vertx.core.eventbus.EventBus;
package com.statful.client; /** * Allows consumers to send custom metrics through the event bus */ public final class CustomMetricsConsumer { /** * Event bus address for custom metrics */ public static final String ADDRESS = "com.statful.client.custom.metrics"; /** * Event bus to listen to metrics messages */ private final EventBus eventBus; /** * Metrics sender */
// Path: src/main/java/com/statful/sender/Sender.java // public interface Sender { // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // * @param sentHandler handler called if you want to be notified after the metrics are sent. // */ // void send(@Nonnull List<DataPoint> metrics, @Nonnull Handler<AsyncResult<Void>> sentHandler); // // /** // * Sender method that gets a list of datapoints and sends them // * // * @param metrics metrics to be sent. Each instance is responsible for creating the full metric line including tags // */ // void send(@Nonnull List<DataPoint> metrics); // // /** // * Stores metric in a buffer to be sent // * // * @param dataPoint metric to be stored // * @return true if the metric was inserted false otherwise // */ // boolean addMetric(final DataPoint dataPoint); // // /** // * Closes the sender // * // * @param handler to execute when closed // */ // void close(final Handler<AsyncResult<Void>> handler); // } // Path: src/main/java/com/statful/client/CustomMetricsConsumer.java import com.statful.sender.Sender; import io.vertx.core.eventbus.EventBus; package com.statful.client; /** * Allows consumers to send custom metrics through the event bus */ public final class CustomMetricsConsumer { /** * Event bus address for custom metrics */ public static final String ADDRESS = "com.statful.client.custom.metrics"; /** * Event bus to listen to metrics messages */ private final EventBus eventBus; /** * Metrics sender */
private final Sender sender;
statful/statful-client-vertx
src/test/java/com/statful/metric/MetricLineBuilderTest.java
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // }
import com.google.common.collect.Lists; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals;
package com.statful.metric; public class MetricLineBuilderTest { private MetricLineBuilder victim; @Before public void setup() { victim = new MetricLineBuilder(); victim.withNamespace("namespace"); victim.withMetricName("execution"); victim.withTag("tagName", "tagValue"); victim.withTimestamp(1); victim.withValue("value"); victim.withSampleRate(100); } @Test public void testBuildWithMetricType() {
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // } // Path: src/test/java/com/statful/metric/MetricLineBuilderTest.java import com.google.common.collect.Lists; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; package com.statful.metric; public class MetricLineBuilderTest { private MetricLineBuilder victim; @Before public void setup() { victim = new MetricLineBuilder(); victim.withNamespace("namespace"); victim.withMetricName("execution"); victim.withTag("tagName", "tagValue"); victim.withTimestamp(1); victim.withValue("value"); victim.withSampleRate(100); } @Test public void testBuildWithMetricType() {
victim.withMetricType(MetricType.TIMER);
statful/statful-client-vertx
src/test/java/com/statful/metric/MetricLineBuilderTest.java
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // }
import com.google.common.collect.Lists; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals;
victim.withMetricType(MetricType.TIMER); String result = victim.build(); String expected = "namespace.timer.execution,tagName=tagValue value 1 100"; assertEquals(expected, result); } @Test public void testBuildWithoutAggregations() { String result = victim.build(); String expected = "namespace.execution,tagName=tagValue value 1 100"; assertEquals(expected, result); } @Test public void testBuildWithoutAggregationsWithoutTags() { victim = new MetricLineBuilder(); victim.withNamespace("namespace"); victim.withMetricName("execution"); victim.withTimestamp(1); victim.withValue("value"); victim.withSampleRate(100); String result = victim.build(); String expected = "namespace.execution value 1 100"; assertEquals(expected, result); } @Test public void testBuildWithoutAggregationsWithFrequencies() {
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // } // Path: src/test/java/com/statful/metric/MetricLineBuilderTest.java import com.google.common.collect.Lists; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; victim.withMetricType(MetricType.TIMER); String result = victim.build(); String expected = "namespace.timer.execution,tagName=tagValue value 1 100"; assertEquals(expected, result); } @Test public void testBuildWithoutAggregations() { String result = victim.build(); String expected = "namespace.execution,tagName=tagValue value 1 100"; assertEquals(expected, result); } @Test public void testBuildWithoutAggregationsWithoutTags() { victim = new MetricLineBuilder(); victim.withNamespace("namespace"); victim.withMetricName("execution"); victim.withTimestamp(1); victim.withValue("value"); victim.withSampleRate(100); String result = victim.build(); String expected = "namespace.execution value 1 100"; assertEquals(expected, result); } @Test public void testBuildWithoutAggregationsWithFrequencies() {
victim.withAggregationFrequency(AggregationFreq.FREQ_120);
statful/statful-client-vertx
src/test/java/com/statful/metric/MetricLineBuilderTest.java
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // }
import com.google.common.collect.Lists; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals;
assertEquals(expected, result); } @Test public void testBuildWithoutAggregationsWithoutTags() { victim = new MetricLineBuilder(); victim.withNamespace("namespace"); victim.withMetricName("execution"); victim.withTimestamp(1); victim.withValue("value"); victim.withSampleRate(100); String result = victim.build(); String expected = "namespace.execution value 1 100"; assertEquals(expected, result); } @Test public void testBuildWithoutAggregationsWithFrequencies() { victim.withAggregationFrequency(AggregationFreq.FREQ_120); String result = victim.build(); String expected = "namespace.execution,tagName=tagValue value 1 100"; assertEquals(expected, result); } @Test public void testBuildWithAggregationsAndFrequencies() {
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // } // Path: src/test/java/com/statful/metric/MetricLineBuilderTest.java import com.google.common.collect.Lists; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; assertEquals(expected, result); } @Test public void testBuildWithoutAggregationsWithoutTags() { victim = new MetricLineBuilder(); victim.withNamespace("namespace"); victim.withMetricName("execution"); victim.withTimestamp(1); victim.withValue("value"); victim.withSampleRate(100); String result = victim.build(); String expected = "namespace.execution value 1 100"; assertEquals(expected, result); } @Test public void testBuildWithoutAggregationsWithFrequencies() { victim.withAggregationFrequency(AggregationFreq.FREQ_120); String result = victim.build(); String expected = "namespace.execution,tagName=tagValue value 1 100"; assertEquals(expected, result); } @Test public void testBuildWithAggregationsAndFrequencies() {
victim.withAggregations(Lists.newArrayList(Aggregation.AVG));
statful/statful-client-vertx
src/test/java/com/statful/client/StatfulMetricsOptionsTest.java
// Path: src/main/java/com/statful/utils/Pair.java // public final class Pair<L, R> { // // /** // * Left element of the Pair // */ // private L left; // /** // * Right element of the Pair // */ // private R right; // // /** // * Pair constructor // * // * @param left element of the pair // * @param right element of the pair // */ // public Pair(final L left, final R right) { // this.left = left; // this.right = right; // } // // /** // * @return gets the value of the left element // */ // public L getLeft() { // return left; // } // // /** // * @return gets the value of the right element // */ // public R getRight() { // return right; // } // // @Override // public String toString() { // return "Pair{" + "left=" + left + ", right=" + right + '}'; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) // && Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // }
import com.google.common.collect.Lists; import com.statful.utils.Pair; import io.vertx.core.json.JsonObject; import org.junit.Before; import org.junit.Test; import java.util.Collections; import java.util.List; import static org.junit.Assert.*;
victim.getToken(); } @Test public void testSetToken() { assertEquals("token", victim.setToken("token").getToken()); } @Test public void testDefaultApp() { assertFalse(victim.getApp().isPresent()); } @Test public void testSetApp() { assertTrue(victim.setApp("app").getApp().filter(value -> value.equals("app")).isPresent()); } @Test public void testDefaultDryRun() { assertFalse(victim.isDryrun()); } @Test public void testSetDryRun() { assertTrue(victim.setDryrun(true).isDryrun()); } @Test public void testDefaultTagList() {
// Path: src/main/java/com/statful/utils/Pair.java // public final class Pair<L, R> { // // /** // * Left element of the Pair // */ // private L left; // /** // * Right element of the Pair // */ // private R right; // // /** // * Pair constructor // * // * @param left element of the pair // * @param right element of the pair // */ // public Pair(final L left, final R right) { // this.left = left; // this.right = right; // } // // /** // * @return gets the value of the left element // */ // public L getLeft() { // return left; // } // // /** // * @return gets the value of the right element // */ // public R getRight() { // return right; // } // // @Override // public String toString() { // return "Pair{" + "left=" + left + ", right=" + right + '}'; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) // && Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // } // Path: src/test/java/com/statful/client/StatfulMetricsOptionsTest.java import com.google.common.collect.Lists; import com.statful.utils.Pair; import io.vertx.core.json.JsonObject; import org.junit.Before; import org.junit.Test; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; victim.getToken(); } @Test public void testSetToken() { assertEquals("token", victim.setToken("token").getToken()); } @Test public void testDefaultApp() { assertFalse(victim.getApp().isPresent()); } @Test public void testSetApp() { assertTrue(victim.setApp("app").getApp().filter(value -> value.equals("app")).isPresent()); } @Test public void testDefaultDryRun() { assertFalse(victim.isDryrun()); } @Test public void testSetDryRun() { assertTrue(victim.setDryrun(true).isDryrun()); } @Test public void testDefaultTagList() {
assertEquals(Collections.<Pair<String, String>>emptyList(), victim.getTags());
statful/statful-client-vertx
src/test/java/com/statful/client/StatfulHttpClientIntegrationTest.java
// Path: src/main/java/com/statful/utils/Pair.java // public final class Pair<L, R> { // // /** // * Left element of the Pair // */ // private L left; // /** // * Right element of the Pair // */ // private R right; // // /** // * Pair constructor // * // * @param left element of the pair // * @param right element of the pair // */ // public Pair(final L left, final R right) { // this.left = left; // this.right = right; // } // // /** // * @return gets the value of the left element // */ // public L getLeft() { // return left; // } // // /** // * @return gets the value of the right element // */ // public R getRight() { // return right; // } // // @Override // public String toString() { // return "Pair{" + "left=" + left + ", right=" + right + '}'; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) // && Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // }
import com.google.common.collect.Lists; import com.statful.utils.Pair; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.core.http.HttpServer; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import static java.util.Objects.nonNull;
package com.statful.client; @RunWith(VertxUnitRunner.class) public class StatfulHttpClientIntegrationTest extends IntegrationTestCase { private static final Logger LOGGER = LoggerFactory.getLogger(StatfulHttpClientIntegrationTest.class); private static final String HOST = "0.0.0.0"; private static final int HTTP_SENDER_PORT = 1236; private HttpServer httpMetricsReceiver; private Vertx vertx; @SuppressWarnings("unchecked") @Before public void setUp() throws Exception {
// Path: src/main/java/com/statful/utils/Pair.java // public final class Pair<L, R> { // // /** // * Left element of the Pair // */ // private L left; // /** // * Right element of the Pair // */ // private R right; // // /** // * Pair constructor // * // * @param left element of the pair // * @param right element of the pair // */ // public Pair(final L left, final R right) { // this.left = left; // this.right = right; // } // // /** // * @return gets the value of the left element // */ // public L getLeft() { // return left; // } // // /** // * @return gets the value of the right element // */ // public R getRight() { // return right; // } // // @Override // public String toString() { // return "Pair{" + "left=" + left + ", right=" + right + '}'; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) // && Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // } // Path: src/test/java/com/statful/client/StatfulHttpClientIntegrationTest.java import com.google.common.collect.Lists; import com.statful.utils.Pair; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.core.http.HttpServer; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import static java.util.Objects.nonNull; package com.statful.client; @RunWith(VertxUnitRunner.class) public class StatfulHttpClientIntegrationTest extends IntegrationTestCase { private static final Logger LOGGER = LoggerFactory.getLogger(StatfulHttpClientIntegrationTest.class); private static final String HOST = "0.0.0.0"; private static final int HTTP_SENDER_PORT = 1236; private HttpServer httpMetricsReceiver; private Vertx vertx; @SuppressWarnings("unchecked") @Before public void setUp() throws Exception {
List<Pair<String, String>> matchReplace = Lists.newArrayList();
statful/statful-client-vertx
src/main/java/com/statful/metric/MetricLineBuilder.java
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // }
import com.google.common.base.Strings; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import javax.annotation.Nonnull; import java.util.*; import java.util.stream.Collectors; import static java.util.Objects.isNull;
package com.statful.metric; /** * Statful metric line builder. Builds metrics lines according to Statful specification */ public final class MetricLineBuilder { /** * Optional application name to be added to the tag list */ private String app; /** * Namespace to be set in the metric */ private String namespace; /** * Optional metric type to be set in the metric */
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // } // Path: src/main/java/com/statful/metric/MetricLineBuilder.java import com.google.common.base.Strings; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import javax.annotation.Nonnull; import java.util.*; import java.util.stream.Collectors; import static java.util.Objects.isNull; package com.statful.metric; /** * Statful metric line builder. Builds metrics lines according to Statful specification */ public final class MetricLineBuilder { /** * Optional application name to be added to the tag list */ private String app; /** * Namespace to be set in the metric */ private String namespace; /** * Optional metric type to be set in the metric */
private MetricType metricType;
statful/statful-client-vertx
src/main/java/com/statful/metric/MetricLineBuilder.java
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // }
import com.google.common.base.Strings; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import javax.annotation.Nonnull; import java.util.*; import java.util.stream.Collectors; import static java.util.Objects.isNull;
package com.statful.metric; /** * Statful metric line builder. Builds metrics lines according to Statful specification */ public final class MetricLineBuilder { /** * Optional application name to be added to the tag list */ private String app; /** * Namespace to be set in the metric */ private String namespace; /** * Optional metric type to be set in the metric */ private MetricType metricType; /** * Metric name to be added to the metric */ private String metricName; /** * Tags to be applied in the metric */ private Map<String, String> tags; /** * Metric value to be sent */ private String value; /** * Timestamp of when the metric was collected */ private long timestamp; /** * List of aggregations to be applied to the sent metric */
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // } // Path: src/main/java/com/statful/metric/MetricLineBuilder.java import com.google.common.base.Strings; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import javax.annotation.Nonnull; import java.util.*; import java.util.stream.Collectors; import static java.util.Objects.isNull; package com.statful.metric; /** * Statful metric line builder. Builds metrics lines according to Statful specification */ public final class MetricLineBuilder { /** * Optional application name to be added to the tag list */ private String app; /** * Namespace to be set in the metric */ private String namespace; /** * Optional metric type to be set in the metric */ private MetricType metricType; /** * Metric name to be added to the metric */ private String metricName; /** * Tags to be applied in the metric */ private Map<String, String> tags; /** * Metric value to be sent */ private String value; /** * Timestamp of when the metric was collected */ private long timestamp; /** * List of aggregations to be applied to the sent metric */
private List<Aggregation> aggregations = new ArrayList<>();
statful/statful-client-vertx
src/main/java/com/statful/metric/MetricLineBuilder.java
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // }
import com.google.common.base.Strings; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import javax.annotation.Nonnull; import java.util.*; import java.util.stream.Collectors; import static java.util.Objects.isNull;
package com.statful.metric; /** * Statful metric line builder. Builds metrics lines according to Statful specification */ public final class MetricLineBuilder { /** * Optional application name to be added to the tag list */ private String app; /** * Namespace to be set in the metric */ private String namespace; /** * Optional metric type to be set in the metric */ private MetricType metricType; /** * Metric name to be added to the metric */ private String metricName; /** * Tags to be applied in the metric */ private Map<String, String> tags; /** * Metric value to be sent */ private String value; /** * Timestamp of when the metric was collected */ private long timestamp; /** * List of aggregations to be applied to the sent metric */ private List<Aggregation> aggregations = new ArrayList<>(); /** * Frequency of aggregation to be applied to the metric */
// Path: src/main/java/com/statful/client/Aggregation.java // public enum Aggregation { // /** // * Average aggregation // */ // AVG("avg"), // /** // * Percentile 90 aggregation // */ // P90("p90"), // /** // * Count aggregation // */ // COUNT("count"), // /** // * Last aggregation // */ // LAST("last"), // /** // * Summatory aggregation // */ // SUM("sum"), // /** // * First aggregation // */ // FIRST("first"), // /** // * Percentile 95 aggregation // */ // P95("p95"), // /** // * Percentile 99 aggregation // */ // P99("p99"), // /** // * Aggregate by min value // */ // MIN("min"), // /** // * Aggregate by max value // */ // MAX("max"); // // /** // * String representation of the aggregation // */ // private final String name; // // /** // * private constructor to force that all entries have a name // * // * @param name String representation of the aggregation // */ // Aggregation(final String name) { // this.name = name; // } // // /** // * Gets the string value of the aggregation, to be used to build metric lines // * // * @return String with the aggregation representation // */ // public final String getName() { // return name; // } // } // // Path: src/main/java/com/statful/client/AggregationFreq.java // public enum AggregationFreq { // // /** // * 10 seconds aggregation // */ // FREQ_10("10"), // // /** // * 30 seconds aggregation // */ // FREQ_30("30"), // // /** // * 60 seconds aggregation // */ // FREQ_60("60"), // // /** // * 120 seconds aggregation // */ // FREQ_120("120"), // // /** // * 180 seconds aggregation // */ // FREQ_180("180"), // // /** // * 300 seconds aggregation // */ // FREQ_300("300"); // // /** // * Number of seconds desired for the aggregation // */ // private String value; // // // /** // * private constructor to force that all entries have a frequency string representation // * // * @param value String representation of the frequency // */ // AggregationFreq(final String value) { // this.value = value; // } // // /** // * Gets the string value of the frequency, to be used to build metric lines // * // * @return String with the frequency representation // */ // public String getValue() { // return this.value; // } // } // // Path: src/main/java/com/statful/client/MetricType.java // public enum MetricType { // /** // * Type for gauge metrics // */ // GAUGE("gauge"), // /** // * Type for counter metrics // */ // COUNTER("counter"), // /** // * Type for timer metrics // */ // TIMER("timer"); // // /** // * String representation of this metric type // */ // private String value; // // MetricType(final String value) { // this.value = value; // } // // /** // * Returns the default aggregation list for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return List of {@link Aggregation} // */ // public List<Aggregation> getDefaultAggregationFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeAggregations(); // case COUNTER: // return statfulMetricsOptions.getCounterAggregations(); // case TIMER: // return statfulMetricsOptions.getTimerAggregations(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // /** // * Returns the default aggregation frequency for this metric type. // * // * @param statfulMetricsOptions Configured statful client metric options // * @return An {@link AggregationFreq} // */ // public AggregationFreq getDefaultAggregationFrequencyFromOptions(final StatfulMetricsOptions statfulMetricsOptions) { // switch (this) { // case GAUGE: // return statfulMetricsOptions.getGaugeFrequency(); // case COUNTER: // return statfulMetricsOptions.getCounterFrequency(); // case TIMER: // return statfulMetricsOptions.getTimerFrequency(); // default: // throw new IllegalArgumentException("Invalid metric type."); // } // } // // @Override // public String toString() { // return this.value; // } // } // Path: src/main/java/com/statful/metric/MetricLineBuilder.java import com.google.common.base.Strings; import com.statful.client.Aggregation; import com.statful.client.AggregationFreq; import com.statful.client.MetricType; import javax.annotation.Nonnull; import java.util.*; import java.util.stream.Collectors; import static java.util.Objects.isNull; package com.statful.metric; /** * Statful metric line builder. Builds metrics lines according to Statful specification */ public final class MetricLineBuilder { /** * Optional application name to be added to the tag list */ private String app; /** * Namespace to be set in the metric */ private String namespace; /** * Optional metric type to be set in the metric */ private MetricType metricType; /** * Metric name to be added to the metric */ private String metricName; /** * Tags to be applied in the metric */ private Map<String, String> tags; /** * Metric value to be sent */ private String value; /** * Timestamp of when the metric was collected */ private long timestamp; /** * List of aggregations to be applied to the sent metric */ private List<Aggregation> aggregations = new ArrayList<>(); /** * Frequency of aggregation to be applied to the metric */
private AggregationFreq frequency = AggregationFreq.FREQ_10;
statful/statful-client-vertx
src/test/java/com/statful/client/StatfulUDPClientIntegrationTest.java
// Path: src/main/java/com/statful/utils/Pair.java // public final class Pair<L, R> { // // /** // * Left element of the Pair // */ // private L left; // /** // * Right element of the Pair // */ // private R right; // // /** // * Pair constructor // * // * @param left element of the pair // * @param right element of the pair // */ // public Pair(final L left, final R right) { // this.left = left; // this.right = right; // } // // /** // * @return gets the value of the left element // */ // public L getLeft() { // return left; // } // // /** // * @return gets the value of the right element // */ // public R getRight() { // return right; // } // // @Override // public String toString() { // return "Pair{" + "left=" + left + ", right=" + right + '}'; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) // && Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // }
import com.google.common.collect.Lists; import com.statful.utils.Pair; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.core.datagram.DatagramSocket; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import static java.util.Objects.nonNull;
package com.statful.client; @RunWith(VertxUnitRunner.class) public class StatfulUDPClientIntegrationTest extends IntegrationTestCase { private static final Logger LOGGER = LoggerFactory.getLogger(StatfulUDPClientIntegrationTest.class); private static final String HOST = "0.0.0.0"; private static final int UDP_PORT = 1234; private DatagramSocket metricsReceiver; private Vertx vertx; @SuppressWarnings("unchecked") @Before public void setUp() throws Exception {
// Path: src/main/java/com/statful/utils/Pair.java // public final class Pair<L, R> { // // /** // * Left element of the Pair // */ // private L left; // /** // * Right element of the Pair // */ // private R right; // // /** // * Pair constructor // * // * @param left element of the pair // * @param right element of the pair // */ // public Pair(final L left, final R right) { // this.left = left; // this.right = right; // } // // /** // * @return gets the value of the left element // */ // public L getLeft() { // return left; // } // // /** // * @return gets the value of the right element // */ // public R getRight() { // return right; // } // // @Override // public String toString() { // return "Pair{" + "left=" + left + ", right=" + right + '}'; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) // && Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // } // Path: src/test/java/com/statful/client/StatfulUDPClientIntegrationTest.java import com.google.common.collect.Lists; import com.statful.utils.Pair; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.core.datagram.DatagramSocket; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import static java.util.Objects.nonNull; package com.statful.client; @RunWith(VertxUnitRunner.class) public class StatfulUDPClientIntegrationTest extends IntegrationTestCase { private static final Logger LOGGER = LoggerFactory.getLogger(StatfulUDPClientIntegrationTest.class); private static final String HOST = "0.0.0.0"; private static final int UDP_PORT = 1234; private DatagramSocket metricsReceiver; private Vertx vertx; @SuppressWarnings("unchecked") @Before public void setUp() throws Exception {
List<Pair<String, String>> matchReplace = Lists.newArrayList();
statful/statful-client-vertx
src/test/java/com/statful/client/StatfulCustomMetricIntegrationTest.java
// Path: src/main/java/com/statful/utils/Pair.java // public final class Pair<L, R> { // // /** // * Left element of the Pair // */ // private L left; // /** // * Right element of the Pair // */ // private R right; // // /** // * Pair constructor // * // * @param left element of the pair // * @param right element of the pair // */ // public Pair(final L left, final R right) { // this.left = left; // this.right = right; // } // // /** // * @return gets the value of the left element // */ // public L getLeft() { // return left; // } // // /** // * @return gets the value of the right element // */ // public R getRight() { // return right; // } // // @Override // public String toString() { // return "Pair{" + "left=" + left + ", right=" + right + '}'; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) // && Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // }
import com.google.common.collect.Lists; import com.statful.utils.Pair; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.core.http.HttpServer; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import static java.util.Objects.nonNull;
@Test public void testCustomMetricWithGlobalAppTag(TestContext context) throws Exception { StatfulMetricsOptions options = getCommonStatfulMetricsOptions(); options.setApp("customApp"); setupVertxTestContext(options); Async async = context.async(); this.httpMetricsReceiver.requestHandler(packet -> packet.bodyHandler(body -> { String metric = body.toString(); context.assertTrue(metric.contains("customMetricName")); context.assertTrue(metric.contains("app=customApp")); teardown(async, context, null); })).listen(HTTP_SENDER_PORT, HOST, event -> { if (event.failed()) { teardown(async, context, event.cause()); } }); CustomMetric metric = new CustomMetric.Builder() .withMetricName("customMetricName") .withValue(1L) .build(); this.vertx.eventBus().send(CustomMetricsConsumer.ADDRESS, metric); } @Test public void testCustomMetricWithCustomTagsAndGlobalTags(TestContext context) throws Exception {
// Path: src/main/java/com/statful/utils/Pair.java // public final class Pair<L, R> { // // /** // * Left element of the Pair // */ // private L left; // /** // * Right element of the Pair // */ // private R right; // // /** // * Pair constructor // * // * @param left element of the pair // * @param right element of the pair // */ // public Pair(final L left, final R right) { // this.left = left; // this.right = right; // } // // /** // * @return gets the value of the left element // */ // public L getLeft() { // return left; // } // // /** // * @return gets the value of the right element // */ // public R getRight() { // return right; // } // // @Override // public String toString() { // return "Pair{" + "left=" + left + ", right=" + right + '}'; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) // && Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // } // Path: src/test/java/com/statful/client/StatfulCustomMetricIntegrationTest.java import com.google.common.collect.Lists; import com.statful.utils.Pair; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.core.http.HttpServer; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import static java.util.Objects.nonNull; @Test public void testCustomMetricWithGlobalAppTag(TestContext context) throws Exception { StatfulMetricsOptions options = getCommonStatfulMetricsOptions(); options.setApp("customApp"); setupVertxTestContext(options); Async async = context.async(); this.httpMetricsReceiver.requestHandler(packet -> packet.bodyHandler(body -> { String metric = body.toString(); context.assertTrue(metric.contains("customMetricName")); context.assertTrue(metric.contains("app=customApp")); teardown(async, context, null); })).listen(HTTP_SENDER_PORT, HOST, event -> { if (event.failed()) { teardown(async, context, event.cause()); } }); CustomMetric metric = new CustomMetric.Builder() .withMetricName("customMetricName") .withValue(1L) .build(); this.vertx.eventBus().send(CustomMetricsConsumer.ADDRESS, metric); } @Test public void testCustomMetricWithCustomTagsAndGlobalTags(TestContext context) throws Exception {
List<Pair<String, String>> globalTags = new ArrayList<>(1);
statful/statful-client-vertx
src/main/java/com/statful/client/StatfulMetricsOptions.java
// Path: src/main/java/com/statful/utils/Pair.java // public final class Pair<L, R> { // // /** // * Left element of the Pair // */ // private L left; // /** // * Right element of the Pair // */ // private R right; // // /** // * Pair constructor // * // * @param left element of the pair // * @param right element of the pair // */ // public Pair(final L left, final R right) { // this.left = left; // this.right = right; // } // // /** // * @return gets the value of the left element // */ // public L getLeft() { // return left; // } // // /** // * @return gets the value of the right element // */ // public R getRight() { // return right; // } // // @Override // public String toString() { // return "Pair{" + "left=" + left + ", right=" + right + '}'; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) // && Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // }
import com.google.common.collect.Lists; import com.statful.utils.Pair; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.metrics.MetricsOptions; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.stream.Collectors; import static java.util.Objects.requireNonNull;
package com.statful.client; /** * Vert.x Statful metrics configuration */ public class StatfulMetricsOptions extends MetricsOptions { /** * Default Statful host constant */ private static final String DEFAULT_HOST = "api.statful.com"; /** * Default port Statful port */ private static final int DEFAULT_PORT = 443; /** * Default value for a secure connection (https) */ private static final Boolean DEFAULT_SECURE = true; /** * Default timeout value to be used by the client to connect to Statful */ private static final int DEFAULT_TIMEOUT = 2000; /** * Default value for dry run configuration */ private static final Boolean DEFAULT_DRY_RUN = false; /** * Maximum value allowed for the sample rate */ public static final Integer MAX_SAMPLE_RATE = 100; /** * Minimum value allowed for the sample rate */ private static final Integer MIN_SAMPLE_RATE = 1; /** * Default sample rate to applied to all metrics */ private static final Integer DEFAULT_SAMPLE_RATE = MAX_SAMPLE_RATE; /** * Default namespace to be applied in all metrics */ private static final String DEFAULT_NAMESPACE = "application"; /** * Default size of elements that the buffer can old before flushing */ private static final int DEFAULT_FLUSH_SIZE = 10; /** * Default flush interval at which metrics are sent */ private static final long DEFAULT_FLUSH_INTERVAL = 30000; /** * Default transport definition */ private static final Transport DEFAULT_TRANSPORT = Transport.HTTP; /** * Default aggregations to be applied for Timer metrics */ private static final List<Aggregation> DEFAULT_TIMER_AGGREGATIONS = Lists.newArrayList(Aggregation.AVG, Aggregation.P90, Aggregation.COUNT); /** * Default aggregations to be applied for Gauge metrics */ private static final List<Aggregation> DEFAULT_GAUGE_AGGREGATIONS = Lists.newArrayList(Aggregation.LAST, Aggregation.MAX, Aggregation.AVG); /** * Default aggregations to be applied for Counter metrics */ private static final List<Aggregation> DEFAULT_COUNTER_AGGREGATIONS = Lists.newArrayList(Aggregation.COUNT, Aggregation.SUM); /** * Default value for Aggregations Frequency for metrics */ private static final AggregationFreq DEFAULT_FREQUENCY = AggregationFreq.FREQ_10; /** * Default value for gauge reporting in milliseconds */ private static final long DEFAULT_GAUGE_REPORTING_INTERVAL = 5000; /** * Default to enable/disable all the available collectors */ private static final boolean DEFAULT_METRIC_COLLECTION = false; /** * Default maximum theoretical buffer size that holds metrics in memory between flushes */ private static final int DEFAULT_MAX_BUFFER_SIZE = 5000; /** * Default Http path to store metrics */ private static final String DEFAULT_HTTP_METRICS_PATH = "/tel/v2.0/metrics"; /** * Statful host, default value {@value #DEFAULT_HOST} */ private String host = DEFAULT_HOST; /** * Optional Statful default port, default value {@value #DEFAULT_PORT} */ private int port = DEFAULT_PORT; /** * Defines the transport to be used to set which type of transport will be used to push the metrics. */ private Transport transport = DEFAULT_TRANSPORT; /** * Defines whether to use https or not, default value {@value #DEFAULT_SECURE} */ private boolean secure = DEFAULT_SECURE; /** * Defines timeout for the client reporter (http / tcp transports), default value {@value #DEFAULT_TIMEOUT} */ private int timeout = DEFAULT_TIMEOUT; /** * Application token, to be used by the http transport */ private String token; /** * Optional value to map to an extra TAG defining the application */ private String app; /** * Optional configuration to not send any metrics when flushing the buffer, default value {@value #DEFAULT_DRY_RUN} */ private boolean dryrun = DEFAULT_DRY_RUN; /** * Tags to be applied, default value {@link Collections#emptyList()} */
// Path: src/main/java/com/statful/utils/Pair.java // public final class Pair<L, R> { // // /** // * Left element of the Pair // */ // private L left; // /** // * Right element of the Pair // */ // private R right; // // /** // * Pair constructor // * // * @param left element of the pair // * @param right element of the pair // */ // public Pair(final L left, final R right) { // this.left = left; // this.right = right; // } // // /** // * @return gets the value of the left element // */ // public L getLeft() { // return left; // } // // /** // * @return gets the value of the right element // */ // public R getRight() { // return right; // } // // @Override // public String toString() { // return "Pair{" + "left=" + left + ", right=" + right + '}'; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) // && Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // } // Path: src/main/java/com/statful/client/StatfulMetricsOptions.java import com.google.common.collect.Lists; import com.statful.utils.Pair; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.metrics.MetricsOptions; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.stream.Collectors; import static java.util.Objects.requireNonNull; package com.statful.client; /** * Vert.x Statful metrics configuration */ public class StatfulMetricsOptions extends MetricsOptions { /** * Default Statful host constant */ private static final String DEFAULT_HOST = "api.statful.com"; /** * Default port Statful port */ private static final int DEFAULT_PORT = 443; /** * Default value for a secure connection (https) */ private static final Boolean DEFAULT_SECURE = true; /** * Default timeout value to be used by the client to connect to Statful */ private static final int DEFAULT_TIMEOUT = 2000; /** * Default value for dry run configuration */ private static final Boolean DEFAULT_DRY_RUN = false; /** * Maximum value allowed for the sample rate */ public static final Integer MAX_SAMPLE_RATE = 100; /** * Minimum value allowed for the sample rate */ private static final Integer MIN_SAMPLE_RATE = 1; /** * Default sample rate to applied to all metrics */ private static final Integer DEFAULT_SAMPLE_RATE = MAX_SAMPLE_RATE; /** * Default namespace to be applied in all metrics */ private static final String DEFAULT_NAMESPACE = "application"; /** * Default size of elements that the buffer can old before flushing */ private static final int DEFAULT_FLUSH_SIZE = 10; /** * Default flush interval at which metrics are sent */ private static final long DEFAULT_FLUSH_INTERVAL = 30000; /** * Default transport definition */ private static final Transport DEFAULT_TRANSPORT = Transport.HTTP; /** * Default aggregations to be applied for Timer metrics */ private static final List<Aggregation> DEFAULT_TIMER_AGGREGATIONS = Lists.newArrayList(Aggregation.AVG, Aggregation.P90, Aggregation.COUNT); /** * Default aggregations to be applied for Gauge metrics */ private static final List<Aggregation> DEFAULT_GAUGE_AGGREGATIONS = Lists.newArrayList(Aggregation.LAST, Aggregation.MAX, Aggregation.AVG); /** * Default aggregations to be applied for Counter metrics */ private static final List<Aggregation> DEFAULT_COUNTER_AGGREGATIONS = Lists.newArrayList(Aggregation.COUNT, Aggregation.SUM); /** * Default value for Aggregations Frequency for metrics */ private static final AggregationFreq DEFAULT_FREQUENCY = AggregationFreq.FREQ_10; /** * Default value for gauge reporting in milliseconds */ private static final long DEFAULT_GAUGE_REPORTING_INTERVAL = 5000; /** * Default to enable/disable all the available collectors */ private static final boolean DEFAULT_METRIC_COLLECTION = false; /** * Default maximum theoretical buffer size that holds metrics in memory between flushes */ private static final int DEFAULT_MAX_BUFFER_SIZE = 5000; /** * Default Http path to store metrics */ private static final String DEFAULT_HTTP_METRICS_PATH = "/tel/v2.0/metrics"; /** * Statful host, default value {@value #DEFAULT_HOST} */ private String host = DEFAULT_HOST; /** * Optional Statful default port, default value {@value #DEFAULT_PORT} */ private int port = DEFAULT_PORT; /** * Defines the transport to be used to set which type of transport will be used to push the metrics. */ private Transport transport = DEFAULT_TRANSPORT; /** * Defines whether to use https or not, default value {@value #DEFAULT_SECURE} */ private boolean secure = DEFAULT_SECURE; /** * Defines timeout for the client reporter (http / tcp transports), default value {@value #DEFAULT_TIMEOUT} */ private int timeout = DEFAULT_TIMEOUT; /** * Application token, to be used by the http transport */ private String token; /** * Optional value to map to an extra TAG defining the application */ private String app; /** * Optional configuration to not send any metrics when flushing the buffer, default value {@value #DEFAULT_DRY_RUN} */ private boolean dryrun = DEFAULT_DRY_RUN; /** * Tags to be applied, default value {@link Collections#emptyList()} */
private List<Pair<String, String>> tags = Collections.emptyList();
idega/com.idega.openid
src/java/com/idega/openid/server/filter/OpenIDPagesRedirectHandler.java
// Path: src/java/com/idega/openid/util/OpenIDUtil.java // public class OpenIDUtil { // // private static final String WWW = "www"; // private static final String HTTP_PROTOCOL = "http://"; // private static final String HTTPS_PROTOCOL = "https://"; // // public String getSubDomain(String serverName) { // ICDomain domain = IWMainApplication.getDefaultIWApplicationContext().getDomain(); // if (domain.getServerName().equals(serverName)) { // return null; // } // // String subdomain = null; // if (serverName.indexOf(HTTPS_PROTOCOL) != -1) { // serverName = serverName.substring(serverName.indexOf(HTTPS_PROTOCOL) + 8); // } // if (serverName.indexOf(HTTP_PROTOCOL) != -1) { // serverName = serverName.substring(serverName.indexOf(HTTP_PROTOCOL) + 7); // } // if (serverName.indexOf(".") != -1 && serverName.indexOf(".") != serverName.lastIndexOf(".") && serverName.indexOf(WWW) == -1) { // subdomain = serverName.substring(0, serverName.indexOf(".")); // } // // return subdomain; // } // }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.idega.openid.util.OpenIDUtil; import com.idega.servlet.filter.util.PagesRedirectHandler;
package com.idega.openid.server.filter; public class OpenIDPagesRedirectHandler implements PagesRedirectHandler { @Override public boolean isForwardOnRootURIRequest(HttpServletRequest request, HttpServletResponse response) { String serverName = request.getServerName();
// Path: src/java/com/idega/openid/util/OpenIDUtil.java // public class OpenIDUtil { // // private static final String WWW = "www"; // private static final String HTTP_PROTOCOL = "http://"; // private static final String HTTPS_PROTOCOL = "https://"; // // public String getSubDomain(String serverName) { // ICDomain domain = IWMainApplication.getDefaultIWApplicationContext().getDomain(); // if (domain.getServerName().equals(serverName)) { // return null; // } // // String subdomain = null; // if (serverName.indexOf(HTTPS_PROTOCOL) != -1) { // serverName = serverName.substring(serverName.indexOf(HTTPS_PROTOCOL) + 8); // } // if (serverName.indexOf(HTTP_PROTOCOL) != -1) { // serverName = serverName.substring(serverName.indexOf(HTTP_PROTOCOL) + 7); // } // if (serverName.indexOf(".") != -1 && serverName.indexOf(".") != serverName.lastIndexOf(".") && serverName.indexOf(WWW) == -1) { // subdomain = serverName.substring(0, serverName.indexOf(".")); // } // // return subdomain; // } // } // Path: src/java/com/idega/openid/server/filter/OpenIDPagesRedirectHandler.java import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.idega.openid.util.OpenIDUtil; import com.idega.servlet.filter.util.PagesRedirectHandler; package com.idega.openid.server.filter; public class OpenIDPagesRedirectHandler implements PagesRedirectHandler { @Override public boolean isForwardOnRootURIRequest(HttpServletRequest request, HttpServletResponse response) { String serverName = request.getServerName();
String subDomain = new OpenIDUtil().getSubDomain(serverName);
idega/com.idega.openid
src/java/com/idega/openid/server/dao/OpenIDSignupDAO.java
// Path: src/java/com/idega/openid/server/data/OpenIdSignupInfo.java // @Entity // @Table(name = OpenIdSignupInfo.ENTITY_NAME) // @NamedQueries({ // @NamedQuery(name = "openidSignup.findAll", query = "select a from OpenIdSignupInfo a"), // @NamedQuery(name = OpenIdSignupInfo.QUERY_FIND_VALID_BY_CONFIRM_ATTRIBUTE_AND_CODE, query = "select a from OpenIdSignupInfo a where a.confirmAttribute = :confirmAttribute and a.confirmCode = :confirmCode and a.isValid != false"), // @NamedQuery(name = OpenIdSignupInfo.QUERY_FIND_VALID_BY_CONFIRM_ATTRIBUTE_AND_CODE_AND_PERSONAL_ID, query = "select a from OpenIdSignupInfo a where a.confirmAttribute = :confirmAttribute and a.confirmCode = :confirmCode and a.personalID = :personalID and a.isValid != false"), // @NamedQuery(name = OpenIdSignupInfo.QUERY_FIND_ALL_BY_PERSONAL_ID, query = "select a from OpenIdSignupInfo a where a.personalID = :personalID"), // @NamedQuery(name = OpenIdSignupInfo.QUERY_FIND_VALID_BY_PERSONAL_ID, query = "select a from OpenIdSignupInfo a where a.personalID = :personalID and a.isValid != false") // }) // public class OpenIdSignupInfo implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 5482743088144038538L; // // public static final String QUERY_FIND_VALID_BY_CONFIRM_ATTRIBUTE_AND_CODE = "openidSignup.findValidByConfirmAttributeAndCode"; // public static final String QUERY_FIND_VALID_BY_CONFIRM_ATTRIBUTE_AND_CODE_AND_PERSONAL_ID = "openidSignup.findValidByConfirmAttributeAndCodeAndPersonalID"; // public static final String QUERY_FIND_ALL_BY_PERSONAL_ID = "openidSignup.findAllByPersonalID"; // public static final String QUERY_FIND_VALID_BY_PERSONAL_ID = "openidSignup.findValidByPersonalID"; // // public static final String ENTITY_NAME = "openid_signup_info"; // // private static final String COLUMN_ID = "openid_signup_info_id"; // private static final String COLUMN_CONFIRM_ATTRIBUTE = "confirm_attribute"; // private static final String COLUMN_CONFIRM_CODE = "confirm_code"; // private static final String COLUMN_PERSONAL_ID = "personal_id"; // private static final String COLUMN_LOGIN_NAME = "login"; // private static final String COLUMN_EMAIL = "email"; // private static final String COLUMN_TIMESTAMP = "added_when"; // private static final String COLUMN_IS_VALID = "is_valid"; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = OpenIdSignupInfo.COLUMN_ID) // private Long id; // // @Column(name = OpenIdSignupInfo.COLUMN_CONFIRM_ATTRIBUTE, length = 40) // private String confirmAttribute; // @Column(name = OpenIdSignupInfo.COLUMN_CONFIRM_CODE, length = 30) // private String confirmCode; // @Column(name = OpenIdSignupInfo.COLUMN_PERSONAL_ID, length = 100) // private String personalID; // @Column(name = OpenIdSignupInfo.COLUMN_LOGIN_NAME, length = 100) // private String loginName; // @Column(name = OpenIdSignupInfo.COLUMN_EMAIL, length = 100) // private String email; // @Temporal(TemporalType.TIMESTAMP) // @Column(name = OpenIdSignupInfo.COLUMN_TIMESTAMP) // private Date addedWhen; // @Column(name = OpenIdSignupInfo.COLUMN_IS_VALID) // private boolean isValid; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getConfirmAttribute() { // return confirmAttribute; // } // public void setConfirmAttribute(String confirmAttribute) { // this.confirmAttribute = confirmAttribute; // } // public String getConfirmCode() { // return confirmCode; // } // public void setConfirmCode(String confirmCode) { // this.confirmCode = confirmCode; // } // public String getPersonalID() { // return personalID; // } // public void setPersonalID(String personalID) { // this.personalID = personalID; // } // public void setLoginName(String loginName) { // this.loginName = loginName; // } // // public String getLoginName() { // return loginName; // } // // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public Date getAddedWhen() { // return addedWhen; // } // public void setAddedWhen(Date addedWhen) { // this.addedWhen = addedWhen; // } // // public void setValid(boolean isValid) { // this.isValid = isValid; // } // // public boolean isValid() { // return isValid; // } // // // }
import javax.ejb.CreateException; import com.idega.openid.server.data.OpenIdSignupInfo;
package com.idega.openid.server.dao; public interface OpenIDSignupDAO { public void createOpenIDSignupInfo(String confirmAttribute, String confirmCode, String personalID, String email, String loginName);
// Path: src/java/com/idega/openid/server/data/OpenIdSignupInfo.java // @Entity // @Table(name = OpenIdSignupInfo.ENTITY_NAME) // @NamedQueries({ // @NamedQuery(name = "openidSignup.findAll", query = "select a from OpenIdSignupInfo a"), // @NamedQuery(name = OpenIdSignupInfo.QUERY_FIND_VALID_BY_CONFIRM_ATTRIBUTE_AND_CODE, query = "select a from OpenIdSignupInfo a where a.confirmAttribute = :confirmAttribute and a.confirmCode = :confirmCode and a.isValid != false"), // @NamedQuery(name = OpenIdSignupInfo.QUERY_FIND_VALID_BY_CONFIRM_ATTRIBUTE_AND_CODE_AND_PERSONAL_ID, query = "select a from OpenIdSignupInfo a where a.confirmAttribute = :confirmAttribute and a.confirmCode = :confirmCode and a.personalID = :personalID and a.isValid != false"), // @NamedQuery(name = OpenIdSignupInfo.QUERY_FIND_ALL_BY_PERSONAL_ID, query = "select a from OpenIdSignupInfo a where a.personalID = :personalID"), // @NamedQuery(name = OpenIdSignupInfo.QUERY_FIND_VALID_BY_PERSONAL_ID, query = "select a from OpenIdSignupInfo a where a.personalID = :personalID and a.isValid != false") // }) // public class OpenIdSignupInfo implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 5482743088144038538L; // // public static final String QUERY_FIND_VALID_BY_CONFIRM_ATTRIBUTE_AND_CODE = "openidSignup.findValidByConfirmAttributeAndCode"; // public static final String QUERY_FIND_VALID_BY_CONFIRM_ATTRIBUTE_AND_CODE_AND_PERSONAL_ID = "openidSignup.findValidByConfirmAttributeAndCodeAndPersonalID"; // public static final String QUERY_FIND_ALL_BY_PERSONAL_ID = "openidSignup.findAllByPersonalID"; // public static final String QUERY_FIND_VALID_BY_PERSONAL_ID = "openidSignup.findValidByPersonalID"; // // public static final String ENTITY_NAME = "openid_signup_info"; // // private static final String COLUMN_ID = "openid_signup_info_id"; // private static final String COLUMN_CONFIRM_ATTRIBUTE = "confirm_attribute"; // private static final String COLUMN_CONFIRM_CODE = "confirm_code"; // private static final String COLUMN_PERSONAL_ID = "personal_id"; // private static final String COLUMN_LOGIN_NAME = "login"; // private static final String COLUMN_EMAIL = "email"; // private static final String COLUMN_TIMESTAMP = "added_when"; // private static final String COLUMN_IS_VALID = "is_valid"; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = OpenIdSignupInfo.COLUMN_ID) // private Long id; // // @Column(name = OpenIdSignupInfo.COLUMN_CONFIRM_ATTRIBUTE, length = 40) // private String confirmAttribute; // @Column(name = OpenIdSignupInfo.COLUMN_CONFIRM_CODE, length = 30) // private String confirmCode; // @Column(name = OpenIdSignupInfo.COLUMN_PERSONAL_ID, length = 100) // private String personalID; // @Column(name = OpenIdSignupInfo.COLUMN_LOGIN_NAME, length = 100) // private String loginName; // @Column(name = OpenIdSignupInfo.COLUMN_EMAIL, length = 100) // private String email; // @Temporal(TemporalType.TIMESTAMP) // @Column(name = OpenIdSignupInfo.COLUMN_TIMESTAMP) // private Date addedWhen; // @Column(name = OpenIdSignupInfo.COLUMN_IS_VALID) // private boolean isValid; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getConfirmAttribute() { // return confirmAttribute; // } // public void setConfirmAttribute(String confirmAttribute) { // this.confirmAttribute = confirmAttribute; // } // public String getConfirmCode() { // return confirmCode; // } // public void setConfirmCode(String confirmCode) { // this.confirmCode = confirmCode; // } // public String getPersonalID() { // return personalID; // } // public void setPersonalID(String personalID) { // this.personalID = personalID; // } // public void setLoginName(String loginName) { // this.loginName = loginName; // } // // public String getLoginName() { // return loginName; // } // // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public Date getAddedWhen() { // return addedWhen; // } // public void setAddedWhen(Date addedWhen) { // this.addedWhen = addedWhen; // } // // public void setValid(boolean isValid) { // this.isValid = isValid; // } // // public boolean isValid() { // return isValid; // } // // // } // Path: src/java/com/idega/openid/server/dao/OpenIDSignupDAO.java import javax.ejb.CreateException; import com.idega.openid.server.data.OpenIdSignupInfo; package com.idega.openid.server.dao; public interface OpenIDSignupDAO { public void createOpenIDSignupInfo(String confirmAttribute, String confirmCode, String personalID, String email, String loginName);
public OpenIdSignupInfo getOpenIdSignupInfo(String confirmAttribute, String confirmCode);
idega/com.idega.openid
src/java/com/idega/openid/server/presentation/OpenIDAuthenticate.java
// Path: src/java/com/idega/openid/OpenIDConstants.java // public class OpenIDConstants { // // public static final String IW_BUNDLE_IDENTIFIER = "com.idega.openid"; // // public static final String PROPERTY_OPENID_PROVIDER = "openid.provider"; // public static final String PROPERTY_SERVER_URL = "openid.server.url"; // public static final String PROPERTY_END_POINT_URL = "openid.endpoint.url"; // public static final String PROPERTY_USER_SETUP_URL = "openid.user.setup.url"; // public static final String PROPERTY_AUTHENTICATION_URL = "openid.authentication.url"; // public static final String PROPERTY_CONSUMER_MANAGER_TIMEOUT = "openid.consumer_manager.timeout"; // public static final String PROPERTY_CONSUMER_MANAGER_CONNECTION_TIMEOUT = "openid.consumer_manager.connection_timeout"; // public static final String PROPERTY_CONSUMER_MANAGER_SOCKET_TIMEOUT = "openid.consumer_manager.socket_timeout"; // public static final String PROPERTY_CONSUMER_MANAGER_MAX_REDIRECTS = "openid.consumer_manager.max_redirects"; // public static final String PROPERTY_OPENID_IDENTITY_FORMAT = "openid.identity.format"; // public static final String PROPERTY_OPENID_AUTO_CREATE_USERS = "openid.auto.create.users"; // public static final String PROPERTY_OPENID_CLIENT_UPDATE_USER_INFO = "openid.client.update.user.info"; // public static final String PROPERTY_SIGN_EXTENSIONS = "openid.sign.extensions"; // // public static final String PARAMETER_RETURN = "openid_return"; // public static final String PARAMETER_IDENTIFIER = "openid_identifier"; // public static final String PARAMETER_REALM = "openid.realm"; // public static final String PARAMETER_ALLOWED = "openid.allowed"; // // public static final String PARAMETER_CHECK_AUTHENTICATION = "check_authentication"; // public static final String PARAMETER_CHECKID_IMMEDIATE = "checkid_immediate"; // public static final String PARAMETER_CHECKID_SETUP = "checkid_setup"; // public static final String PARAMETER_ASSOCIATE = "associate"; // public static final String PARAMETER_OPENID_MODE = "openid.mode"; // public static final String PARAMETER_ASSOCIATE_HANDLE = "openid.assoc_handle"; // // public static final String ATTRIBUTE_CONSUMER_MANAGER = "openid.consumer_manager"; // public static final String ATTRIBUTE_SERVER_MANAGER = "openid.server_manager"; // // // public static final String ATTRIBUTE_ALLOWED_REALM = "openid_allowed_realm"; // public static final String ATTRIBUTE_RETURN_URL = "openid_return_url"; // // public static final String STATUS_SUCCESS = "SUCCESS"; // // public static final String ATTRIBUTE_ALIAS_EMAIL = "email"; // public static final String ATTRIBUTE_ALIAS_PERSONAL_ID = "personalID"; // public static final String ATTRIBUTE_ALIAS_FULL_NAME = "fullname"; // public static final String ATTRIBUTE_ALIAS_DATE_OF_BIRTH = "dob"; // public static final String ATTRIBUTE_ALIAS_GENDER = "gender"; // public static final String ATTRIBUTE_ALIAS_NICKNAME = "nickname"; // public static final String ATTRIBUTE_ALIAS_POSTCODE = "postcode"; // public static final String ATTRIBUTE_ALIAS_COUNTRY = "country"; // public static final String ATTRIBUTE_ALIAS_LANGUAGE = "language"; // public static final String ATTRIBUTE_ALIAS_TIMEZONE = "timezone"; // // public static final String ATTRIBUTE_TYPE_EMAIL = "http://axschema.org/contact/email"; // public static final String ATTRIBUTE_TYPE_PERSONAL_ID = "http://www.elykill.is/contact/personalID"; // public static final String ATTRIBUTE_TYPE_FULL_NAME = "http://axschema.org/namePerson"; // public static final String ATTRIBUTE_TYPE_FRIENDLY_NAME = "http://axschema.org/namePerson/friendly"; // public static final String ATTRIBUTE_TYPE_DATE_OF_BIRTH = "http://axschema.org/birthDate"; // public static final String ATTRIBUTE_TYPE_GENDER = "http://axschema.org/person/gender"; // public static final String ATTRIBUTE_TYPE_POSTAL_CODE = "http://axschema.org/contact/postalCode/home"; // public static final String ATTRIBUTE_TYPE_COUNTRY = "http://axschema.org/contact/country/home"; // public static final String ATTRIBUTE_TYPE_LANGUAGE = "http://axschema.org/pref/language"; // public static final String ATTRIBUTE_TYPE_TIMEZONE = "http://axschema.org/pref/timezone"; // // public static final String LOGIN_TYPE = "openid"; // // }
import javax.faces.context.FacesContext; import org.springframework.beans.factory.annotation.Autowired; import com.idega.block.web2.business.JQuery; import com.idega.facelets.ui.FaceletComponent; import com.idega.openid.OpenIDConstants; import com.idega.presentation.IWBaseComponent; import com.idega.presentation.IWContext; import com.idega.util.PresentationUtil; import com.idega.util.expression.ELUtil;
package com.idega.openid.server.presentation; public class OpenIDAuthenticate extends IWBaseComponent { @Autowired private JQuery jQuery; public String getBundleIdentifier() {
// Path: src/java/com/idega/openid/OpenIDConstants.java // public class OpenIDConstants { // // public static final String IW_BUNDLE_IDENTIFIER = "com.idega.openid"; // // public static final String PROPERTY_OPENID_PROVIDER = "openid.provider"; // public static final String PROPERTY_SERVER_URL = "openid.server.url"; // public static final String PROPERTY_END_POINT_URL = "openid.endpoint.url"; // public static final String PROPERTY_USER_SETUP_URL = "openid.user.setup.url"; // public static final String PROPERTY_AUTHENTICATION_URL = "openid.authentication.url"; // public static final String PROPERTY_CONSUMER_MANAGER_TIMEOUT = "openid.consumer_manager.timeout"; // public static final String PROPERTY_CONSUMER_MANAGER_CONNECTION_TIMEOUT = "openid.consumer_manager.connection_timeout"; // public static final String PROPERTY_CONSUMER_MANAGER_SOCKET_TIMEOUT = "openid.consumer_manager.socket_timeout"; // public static final String PROPERTY_CONSUMER_MANAGER_MAX_REDIRECTS = "openid.consumer_manager.max_redirects"; // public static final String PROPERTY_OPENID_IDENTITY_FORMAT = "openid.identity.format"; // public static final String PROPERTY_OPENID_AUTO_CREATE_USERS = "openid.auto.create.users"; // public static final String PROPERTY_OPENID_CLIENT_UPDATE_USER_INFO = "openid.client.update.user.info"; // public static final String PROPERTY_SIGN_EXTENSIONS = "openid.sign.extensions"; // // public static final String PARAMETER_RETURN = "openid_return"; // public static final String PARAMETER_IDENTIFIER = "openid_identifier"; // public static final String PARAMETER_REALM = "openid.realm"; // public static final String PARAMETER_ALLOWED = "openid.allowed"; // // public static final String PARAMETER_CHECK_AUTHENTICATION = "check_authentication"; // public static final String PARAMETER_CHECKID_IMMEDIATE = "checkid_immediate"; // public static final String PARAMETER_CHECKID_SETUP = "checkid_setup"; // public static final String PARAMETER_ASSOCIATE = "associate"; // public static final String PARAMETER_OPENID_MODE = "openid.mode"; // public static final String PARAMETER_ASSOCIATE_HANDLE = "openid.assoc_handle"; // // public static final String ATTRIBUTE_CONSUMER_MANAGER = "openid.consumer_manager"; // public static final String ATTRIBUTE_SERVER_MANAGER = "openid.server_manager"; // // // public static final String ATTRIBUTE_ALLOWED_REALM = "openid_allowed_realm"; // public static final String ATTRIBUTE_RETURN_URL = "openid_return_url"; // // public static final String STATUS_SUCCESS = "SUCCESS"; // // public static final String ATTRIBUTE_ALIAS_EMAIL = "email"; // public static final String ATTRIBUTE_ALIAS_PERSONAL_ID = "personalID"; // public static final String ATTRIBUTE_ALIAS_FULL_NAME = "fullname"; // public static final String ATTRIBUTE_ALIAS_DATE_OF_BIRTH = "dob"; // public static final String ATTRIBUTE_ALIAS_GENDER = "gender"; // public static final String ATTRIBUTE_ALIAS_NICKNAME = "nickname"; // public static final String ATTRIBUTE_ALIAS_POSTCODE = "postcode"; // public static final String ATTRIBUTE_ALIAS_COUNTRY = "country"; // public static final String ATTRIBUTE_ALIAS_LANGUAGE = "language"; // public static final String ATTRIBUTE_ALIAS_TIMEZONE = "timezone"; // // public static final String ATTRIBUTE_TYPE_EMAIL = "http://axschema.org/contact/email"; // public static final String ATTRIBUTE_TYPE_PERSONAL_ID = "http://www.elykill.is/contact/personalID"; // public static final String ATTRIBUTE_TYPE_FULL_NAME = "http://axschema.org/namePerson"; // public static final String ATTRIBUTE_TYPE_FRIENDLY_NAME = "http://axschema.org/namePerson/friendly"; // public static final String ATTRIBUTE_TYPE_DATE_OF_BIRTH = "http://axschema.org/birthDate"; // public static final String ATTRIBUTE_TYPE_GENDER = "http://axschema.org/person/gender"; // public static final String ATTRIBUTE_TYPE_POSTAL_CODE = "http://axschema.org/contact/postalCode/home"; // public static final String ATTRIBUTE_TYPE_COUNTRY = "http://axschema.org/contact/country/home"; // public static final String ATTRIBUTE_TYPE_LANGUAGE = "http://axschema.org/pref/language"; // public static final String ATTRIBUTE_TYPE_TIMEZONE = "http://axschema.org/pref/timezone"; // // public static final String LOGIN_TYPE = "openid"; // // } // Path: src/java/com/idega/openid/server/presentation/OpenIDAuthenticate.java import javax.faces.context.FacesContext; import org.springframework.beans.factory.annotation.Autowired; import com.idega.block.web2.business.JQuery; import com.idega.facelets.ui.FaceletComponent; import com.idega.openid.OpenIDConstants; import com.idega.presentation.IWBaseComponent; import com.idega.presentation.IWContext; import com.idega.util.PresentationUtil; import com.idega.util.expression.ELUtil; package com.idega.openid.server.presentation; public class OpenIDAuthenticate extends IWBaseComponent { @Autowired private JQuery jQuery; public String getBundleIdentifier() {
return OpenIDConstants.IW_BUNDLE_IDENTIFIER;
idega/com.idega.openid
src/java/com/idega/openid/IWBundleStarter.java
// Path: src/java/com/idega/openid/server/dao/OpenIDServerDAO.java // public interface OpenIDServerDAO extends GenericDao { // // public void createAuthorizedAttribute(String userUUID, String realm, ExchangeAttribute attribute); // // public List<AuthorizedAttribute> getAuthorizedAttributes(String userUUID, String realm); // // public AuthorizedAttribute getAuthorizedAttributes(String userUUID, String realm, ExchangeAttribute attr); // // public void createLogEntry(String userUUID, String realm, String exchangedAttributes); // // public List<ExchangeAttribute> getAllExchangeAttributes(); // // public void createExchangeAttribute(String name, String type); // // public ExchangeAttribute getExchangeAttribute(String name); // // public ExchangeAttribute getExchangeAttribute(String name, String type); // // public void saveAuthorizedAttribute(AuthorizedAttribute attr); // // } // // Path: src/java/com/idega/openid/server/filter/OpenIDPagesRedirectHandler.java // public class OpenIDPagesRedirectHandler implements PagesRedirectHandler { // // @Override // public boolean isForwardOnRootURIRequest(HttpServletRequest request, HttpServletResponse response) { // String serverName = request.getServerName(); // String subDomain = new OpenIDUtil().getSubDomain(serverName); // // if (subDomain == null) { // return true; // } // return false; // } // }
import org.springframework.beans.factory.annotation.Autowired; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWBundleStartable; import com.idega.openid.server.dao.OpenIDServerDAO; import com.idega.openid.server.filter.OpenIDPagesRedirectHandler; import com.idega.servlet.filter.IWBundleResourceFilter; import com.idega.servlet.filter.util.PagesRedirectHandler; import com.idega.util.expression.ELUtil;
package com.idega.openid; public class IWBundleStarter implements IWBundleStartable { @Autowired
// Path: src/java/com/idega/openid/server/dao/OpenIDServerDAO.java // public interface OpenIDServerDAO extends GenericDao { // // public void createAuthorizedAttribute(String userUUID, String realm, ExchangeAttribute attribute); // // public List<AuthorizedAttribute> getAuthorizedAttributes(String userUUID, String realm); // // public AuthorizedAttribute getAuthorizedAttributes(String userUUID, String realm, ExchangeAttribute attr); // // public void createLogEntry(String userUUID, String realm, String exchangedAttributes); // // public List<ExchangeAttribute> getAllExchangeAttributes(); // // public void createExchangeAttribute(String name, String type); // // public ExchangeAttribute getExchangeAttribute(String name); // // public ExchangeAttribute getExchangeAttribute(String name, String type); // // public void saveAuthorizedAttribute(AuthorizedAttribute attr); // // } // // Path: src/java/com/idega/openid/server/filter/OpenIDPagesRedirectHandler.java // public class OpenIDPagesRedirectHandler implements PagesRedirectHandler { // // @Override // public boolean isForwardOnRootURIRequest(HttpServletRequest request, HttpServletResponse response) { // String serverName = request.getServerName(); // String subDomain = new OpenIDUtil().getSubDomain(serverName); // // if (subDomain == null) { // return true; // } // return false; // } // } // Path: src/java/com/idega/openid/IWBundleStarter.java import org.springframework.beans.factory.annotation.Autowired; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWBundleStartable; import com.idega.openid.server.dao.OpenIDServerDAO; import com.idega.openid.server.filter.OpenIDPagesRedirectHandler; import com.idega.servlet.filter.IWBundleResourceFilter; import com.idega.servlet.filter.util.PagesRedirectHandler; import com.idega.util.expression.ELUtil; package com.idega.openid; public class IWBundleStarter implements IWBundleStartable { @Autowired
private OpenIDServerDAO dao;
idega/com.idega.openid
src/java/com/idega/openid/IWBundleStarter.java
// Path: src/java/com/idega/openid/server/dao/OpenIDServerDAO.java // public interface OpenIDServerDAO extends GenericDao { // // public void createAuthorizedAttribute(String userUUID, String realm, ExchangeAttribute attribute); // // public List<AuthorizedAttribute> getAuthorizedAttributes(String userUUID, String realm); // // public AuthorizedAttribute getAuthorizedAttributes(String userUUID, String realm, ExchangeAttribute attr); // // public void createLogEntry(String userUUID, String realm, String exchangedAttributes); // // public List<ExchangeAttribute> getAllExchangeAttributes(); // // public void createExchangeAttribute(String name, String type); // // public ExchangeAttribute getExchangeAttribute(String name); // // public ExchangeAttribute getExchangeAttribute(String name, String type); // // public void saveAuthorizedAttribute(AuthorizedAttribute attr); // // } // // Path: src/java/com/idega/openid/server/filter/OpenIDPagesRedirectHandler.java // public class OpenIDPagesRedirectHandler implements PagesRedirectHandler { // // @Override // public boolean isForwardOnRootURIRequest(HttpServletRequest request, HttpServletResponse response) { // String serverName = request.getServerName(); // String subDomain = new OpenIDUtil().getSubDomain(serverName); // // if (subDomain == null) { // return true; // } // return false; // } // }
import org.springframework.beans.factory.annotation.Autowired; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWBundleStartable; import com.idega.openid.server.dao.OpenIDServerDAO; import com.idega.openid.server.filter.OpenIDPagesRedirectHandler; import com.idega.servlet.filter.IWBundleResourceFilter; import com.idega.servlet.filter.util.PagesRedirectHandler; import com.idega.util.expression.ELUtil;
package com.idega.openid; public class IWBundleStarter implements IWBundleStartable { @Autowired private OpenIDServerDAO dao; public void start(IWBundle starterBundle) { String handlerClass = starterBundle.getApplication().getSettings().getProperty(PagesRedirectHandler.ATTRIBUTE_PAGES_REDIRECT_HANDLER_CLASS); if (handlerClass == null) {
// Path: src/java/com/idega/openid/server/dao/OpenIDServerDAO.java // public interface OpenIDServerDAO extends GenericDao { // // public void createAuthorizedAttribute(String userUUID, String realm, ExchangeAttribute attribute); // // public List<AuthorizedAttribute> getAuthorizedAttributes(String userUUID, String realm); // // public AuthorizedAttribute getAuthorizedAttributes(String userUUID, String realm, ExchangeAttribute attr); // // public void createLogEntry(String userUUID, String realm, String exchangedAttributes); // // public List<ExchangeAttribute> getAllExchangeAttributes(); // // public void createExchangeAttribute(String name, String type); // // public ExchangeAttribute getExchangeAttribute(String name); // // public ExchangeAttribute getExchangeAttribute(String name, String type); // // public void saveAuthorizedAttribute(AuthorizedAttribute attr); // // } // // Path: src/java/com/idega/openid/server/filter/OpenIDPagesRedirectHandler.java // public class OpenIDPagesRedirectHandler implements PagesRedirectHandler { // // @Override // public boolean isForwardOnRootURIRequest(HttpServletRequest request, HttpServletResponse response) { // String serverName = request.getServerName(); // String subDomain = new OpenIDUtil().getSubDomain(serverName); // // if (subDomain == null) { // return true; // } // return false; // } // } // Path: src/java/com/idega/openid/IWBundleStarter.java import org.springframework.beans.factory.annotation.Autowired; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWBundleStartable; import com.idega.openid.server.dao.OpenIDServerDAO; import com.idega.openid.server.filter.OpenIDPagesRedirectHandler; import com.idega.servlet.filter.IWBundleResourceFilter; import com.idega.servlet.filter.util.PagesRedirectHandler; import com.idega.util.expression.ELUtil; package com.idega.openid; public class IWBundleStarter implements IWBundleStartable { @Autowired private OpenIDServerDAO dao; public void start(IWBundle starterBundle) { String handlerClass = starterBundle.getApplication().getSettings().getProperty(PagesRedirectHandler.ATTRIBUTE_PAGES_REDIRECT_HANDLER_CLASS); if (handlerClass == null) {
starterBundle.getApplication().getSettings().setProperty(PagesRedirectHandler.ATTRIBUTE_PAGES_REDIRECT_HANDLER_CLASS, OpenIDPagesRedirectHandler.class.getName());
damianbrunold/jbead
src/ch/jbead/dialog/PreferencesDialog.java
// Path: src/ch/jbead/BeadSymbols.java // public class BeadSymbols { // // public static final String MIDDLE_DOT = "\u00b7"; // public static final String DEFAULT_SYMBOLS = MIDDLE_DOT + "abcdefghijklmnopqrstuvwxyz+-/\\*"; // public static String SYMBOLS = DEFAULT_SYMBOLS; // public static String SAVED_SYMBOLS = DEFAULT_SYMBOLS; // // static { // reloadSymbols(); // } // // public static void restoreDefaults() { // SYMBOLS = DEFAULT_SYMBOLS; // } // // public static void reloadSymbols() { // Settings settings = new Settings(); // settings.setCategory("view"); // SAVED_SYMBOLS = settings.loadString("symbols", DEFAULT_SYMBOLS); // SYMBOLS = SAVED_SYMBOLS; // } // // public static String get(byte index) { // if (index >= SYMBOLS.length()) return " "; // return SYMBOLS.substring(index, index + 1); // } // // } // // Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/Settings.java // public class Settings { // // private static final String BASE = "brunoldsoft/jbead"; // // private Preferences preferences = Preferences.userRoot().node(BASE); // private String category = "general"; // // public Settings() { // category = "general"; // } // // public void setCategory(String category) { // this.category = category; // } // // public String category() { // return category; // } // // public boolean hasSetting(String name) { // return preferences.node(category).get(name, null) != null; // } // // public int loadInt(String name) { // return loadInt(name, 0); // } // // public int loadInt(String name, int defaultvalue) { // return preferences.node(category).getInt(name, defaultvalue); // } // // public long loadLong(String name) { // return loadLong(name, 0); // } // // public long loadLong(String name, long defaultvalue) { // return preferences.node(category).getLong(name, defaultvalue); // } // // public boolean loadBoolean(String name) { // return loadBoolean(name, false); // } // // public boolean loadBoolean(String name, boolean defaultvalue) { // return preferences.node(category).getBoolean(name, defaultvalue); // } // // public String loadString(String name) { // return loadString(name, ""); // } // // public String loadString(String name, String defaultvalue) { // return preferences.node(category).get(name, defaultvalue); // } // // public void saveInt(String name, int value) { // preferences.node(category).putInt(name, value); // } // // public void saveLong(String name, long value) { // preferences.node(category).putLong(name, value); // } // // public void saveBoolean(String name, boolean value) { // preferences.node(category).putBoolean(name, value); // } // // public void saveString(String name, String value) { // preferences.node(category).put(name, value); // } // // public void remove(String name) { // preferences.node(category).remove(name); // } // // public void flush() throws BackingStoreException { // preferences.flush(); // } // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // }
import javax.swing.JTextField; import ch.jbead.BeadSymbols; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.Settings; import ch.jbead.View; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class PreferencesDialog extends JDialog { private static final long serialVersionUID = 1L; private JTextField author; private JTextField organization; private JTextField symbols; private JCheckBox disablestartcheck;
// Path: src/ch/jbead/BeadSymbols.java // public class BeadSymbols { // // public static final String MIDDLE_DOT = "\u00b7"; // public static final String DEFAULT_SYMBOLS = MIDDLE_DOT + "abcdefghijklmnopqrstuvwxyz+-/\\*"; // public static String SYMBOLS = DEFAULT_SYMBOLS; // public static String SAVED_SYMBOLS = DEFAULT_SYMBOLS; // // static { // reloadSymbols(); // } // // public static void restoreDefaults() { // SYMBOLS = DEFAULT_SYMBOLS; // } // // public static void reloadSymbols() { // Settings settings = new Settings(); // settings.setCategory("view"); // SAVED_SYMBOLS = settings.loadString("symbols", DEFAULT_SYMBOLS); // SYMBOLS = SAVED_SYMBOLS; // } // // public static String get(byte index) { // if (index >= SYMBOLS.length()) return " "; // return SYMBOLS.substring(index, index + 1); // } // // } // // Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/Settings.java // public class Settings { // // private static final String BASE = "brunoldsoft/jbead"; // // private Preferences preferences = Preferences.userRoot().node(BASE); // private String category = "general"; // // public Settings() { // category = "general"; // } // // public void setCategory(String category) { // this.category = category; // } // // public String category() { // return category; // } // // public boolean hasSetting(String name) { // return preferences.node(category).get(name, null) != null; // } // // public int loadInt(String name) { // return loadInt(name, 0); // } // // public int loadInt(String name, int defaultvalue) { // return preferences.node(category).getInt(name, defaultvalue); // } // // public long loadLong(String name) { // return loadLong(name, 0); // } // // public long loadLong(String name, long defaultvalue) { // return preferences.node(category).getLong(name, defaultvalue); // } // // public boolean loadBoolean(String name) { // return loadBoolean(name, false); // } // // public boolean loadBoolean(String name, boolean defaultvalue) { // return preferences.node(category).getBoolean(name, defaultvalue); // } // // public String loadString(String name) { // return loadString(name, ""); // } // // public String loadString(String name, String defaultvalue) { // return preferences.node(category).get(name, defaultvalue); // } // // public void saveInt(String name, int value) { // preferences.node(category).putInt(name, value); // } // // public void saveLong(String name, long value) { // preferences.node(category).putLong(name, value); // } // // public void saveBoolean(String name, boolean value) { // preferences.node(category).putBoolean(name, value); // } // // public void saveString(String name, String value) { // preferences.node(category).put(name, value); // } // // public void remove(String name) { // preferences.node(category).remove(name); // } // // public void flush() throws BackingStoreException { // preferences.flush(); // } // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // } // Path: src/ch/jbead/dialog/PreferencesDialog.java import javax.swing.JTextField; import ch.jbead.BeadSymbols; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.Settings; import ch.jbead.View; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class PreferencesDialog extends JDialog { private static final long serialVersionUID = 1L; private JTextField author; private JTextField organization; private JTextField symbols; private JCheckBox disablestartcheck;
public PreferencesDialog(Localization localization, final Model model, final View view) {
damianbrunold/jbead
src/ch/jbead/dialog/PreferencesDialog.java
// Path: src/ch/jbead/BeadSymbols.java // public class BeadSymbols { // // public static final String MIDDLE_DOT = "\u00b7"; // public static final String DEFAULT_SYMBOLS = MIDDLE_DOT + "abcdefghijklmnopqrstuvwxyz+-/\\*"; // public static String SYMBOLS = DEFAULT_SYMBOLS; // public static String SAVED_SYMBOLS = DEFAULT_SYMBOLS; // // static { // reloadSymbols(); // } // // public static void restoreDefaults() { // SYMBOLS = DEFAULT_SYMBOLS; // } // // public static void reloadSymbols() { // Settings settings = new Settings(); // settings.setCategory("view"); // SAVED_SYMBOLS = settings.loadString("symbols", DEFAULT_SYMBOLS); // SYMBOLS = SAVED_SYMBOLS; // } // // public static String get(byte index) { // if (index >= SYMBOLS.length()) return " "; // return SYMBOLS.substring(index, index + 1); // } // // } // // Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/Settings.java // public class Settings { // // private static final String BASE = "brunoldsoft/jbead"; // // private Preferences preferences = Preferences.userRoot().node(BASE); // private String category = "general"; // // public Settings() { // category = "general"; // } // // public void setCategory(String category) { // this.category = category; // } // // public String category() { // return category; // } // // public boolean hasSetting(String name) { // return preferences.node(category).get(name, null) != null; // } // // public int loadInt(String name) { // return loadInt(name, 0); // } // // public int loadInt(String name, int defaultvalue) { // return preferences.node(category).getInt(name, defaultvalue); // } // // public long loadLong(String name) { // return loadLong(name, 0); // } // // public long loadLong(String name, long defaultvalue) { // return preferences.node(category).getLong(name, defaultvalue); // } // // public boolean loadBoolean(String name) { // return loadBoolean(name, false); // } // // public boolean loadBoolean(String name, boolean defaultvalue) { // return preferences.node(category).getBoolean(name, defaultvalue); // } // // public String loadString(String name) { // return loadString(name, ""); // } // // public String loadString(String name, String defaultvalue) { // return preferences.node(category).get(name, defaultvalue); // } // // public void saveInt(String name, int value) { // preferences.node(category).putInt(name, value); // } // // public void saveLong(String name, long value) { // preferences.node(category).putLong(name, value); // } // // public void saveBoolean(String name, boolean value) { // preferences.node(category).putBoolean(name, value); // } // // public void saveString(String name, String value) { // preferences.node(category).put(name, value); // } // // public void remove(String name) { // preferences.node(category).remove(name); // } // // public void flush() throws BackingStoreException { // preferences.flush(); // } // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // }
import javax.swing.JTextField; import ch.jbead.BeadSymbols; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.Settings; import ch.jbead.View; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class PreferencesDialog extends JDialog { private static final long serialVersionUID = 1L; private JTextField author; private JTextField organization; private JTextField symbols; private JCheckBox disablestartcheck;
// Path: src/ch/jbead/BeadSymbols.java // public class BeadSymbols { // // public static final String MIDDLE_DOT = "\u00b7"; // public static final String DEFAULT_SYMBOLS = MIDDLE_DOT + "abcdefghijklmnopqrstuvwxyz+-/\\*"; // public static String SYMBOLS = DEFAULT_SYMBOLS; // public static String SAVED_SYMBOLS = DEFAULT_SYMBOLS; // // static { // reloadSymbols(); // } // // public static void restoreDefaults() { // SYMBOLS = DEFAULT_SYMBOLS; // } // // public static void reloadSymbols() { // Settings settings = new Settings(); // settings.setCategory("view"); // SAVED_SYMBOLS = settings.loadString("symbols", DEFAULT_SYMBOLS); // SYMBOLS = SAVED_SYMBOLS; // } // // public static String get(byte index) { // if (index >= SYMBOLS.length()) return " "; // return SYMBOLS.substring(index, index + 1); // } // // } // // Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/Settings.java // public class Settings { // // private static final String BASE = "brunoldsoft/jbead"; // // private Preferences preferences = Preferences.userRoot().node(BASE); // private String category = "general"; // // public Settings() { // category = "general"; // } // // public void setCategory(String category) { // this.category = category; // } // // public String category() { // return category; // } // // public boolean hasSetting(String name) { // return preferences.node(category).get(name, null) != null; // } // // public int loadInt(String name) { // return loadInt(name, 0); // } // // public int loadInt(String name, int defaultvalue) { // return preferences.node(category).getInt(name, defaultvalue); // } // // public long loadLong(String name) { // return loadLong(name, 0); // } // // public long loadLong(String name, long defaultvalue) { // return preferences.node(category).getLong(name, defaultvalue); // } // // public boolean loadBoolean(String name) { // return loadBoolean(name, false); // } // // public boolean loadBoolean(String name, boolean defaultvalue) { // return preferences.node(category).getBoolean(name, defaultvalue); // } // // public String loadString(String name) { // return loadString(name, ""); // } // // public String loadString(String name, String defaultvalue) { // return preferences.node(category).get(name, defaultvalue); // } // // public void saveInt(String name, int value) { // preferences.node(category).putInt(name, value); // } // // public void saveLong(String name, long value) { // preferences.node(category).putLong(name, value); // } // // public void saveBoolean(String name, boolean value) { // preferences.node(category).putBoolean(name, value); // } // // public void saveString(String name, String value) { // preferences.node(category).put(name, value); // } // // public void remove(String name) { // preferences.node(category).remove(name); // } // // public void flush() throws BackingStoreException { // preferences.flush(); // } // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // } // Path: src/ch/jbead/dialog/PreferencesDialog.java import javax.swing.JTextField; import ch.jbead.BeadSymbols; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.Settings; import ch.jbead.View; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class PreferencesDialog extends JDialog { private static final long serialVersionUID = 1L; private JTextField author; private JTextField organization; private JTextField symbols; private JCheckBox disablestartcheck;
public PreferencesDialog(Localization localization, final Model model, final View view) {
damianbrunold/jbead
src/ch/jbead/print/PartPrinter.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // }
import java.awt.Font; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.util.List; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View; import ch.jbead.util.Convert;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public abstract class PartPrinter { protected Model model;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // } // Path: src/ch/jbead/print/PartPrinter.java import java.awt.Font; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.util.List; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View; import ch.jbead.util.Convert; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public abstract class PartPrinter { protected Model model;
protected View view;
damianbrunold/jbead
src/ch/jbead/print/PartPrinter.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // }
import java.awt.Font; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.util.List; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View; import ch.jbead.util.Convert;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public abstract class PartPrinter { protected Model model; protected View view;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // } // Path: src/ch/jbead/print/PartPrinter.java import java.awt.Font; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.util.List; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View; import ch.jbead.util.Convert; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public abstract class PartPrinter { protected Model model; protected View view;
protected Localization localization;
damianbrunold/jbead
src/ch/jbead/dialog/PatternHeightDialog.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // }
import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import ch.jbead.Localization; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class PatternHeightDialog extends JDialog { private static final long serialVersionUID = 1L; private SpinnerModel heightModel = new SpinnerNumberModel(1000, 5, 10000, 1); private JSpinner patternheight = new JSpinner(heightModel); private boolean isOK = false;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // Path: src/ch/jbead/dialog/PatternHeightDialog.java import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import ch.jbead.Localization; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class PatternHeightDialog extends JDialog { private static final long serialVersionUID = 1L; private SpinnerModel heightModel = new SpinnerNumberModel(1000, 5, 10000, 1); private JSpinner patternheight = new JSpinner(heightModel); private boolean isOK = false;
public PatternHeightDialog(Localization localization) {
damianbrunold/jbead
src/ch/jbead/dialog/ArrangeDialog.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/Selection.java // public class Selection extends Rect { // // private boolean selection; // // private List<SelectionListener> listeners = new ArrayList<SelectionListener>(); // // public Selection() { // super(new Point(0, 0), new Point(0, 0)); // selection = false; // } // // public Selection(Selection sel) { // super(sel.begin, sel.end); // selection = sel.selection; // } // // public void addListener(SelectionListener listener) { // listeners.add(listener); // } // // private void fireSelectionChanged(Selection before, Selection current) { // for (SelectionListener listener : listeners) { // listener.selectionUpdated(before, current); // } // } // // private void fireSelectionDeleted(Selection sel) { // for (SelectionListener listener : listeners) { // listener.selectionDeleted(sel); // } // } // // public void clear() { // if (!selection) return; // fireSelectionDeleted(snapshot()); // selection = false; // } // // public boolean isActive() { // return selection; // } // // public void init(Point origin) { // Selection before = snapshot(); // this.begin = this.end = origin; // selection = false; // fireSelectionChanged(before, snapshot()); // } // // public void update(Point end) { // Selection before = snapshot(); // this.end = end; // selection = !begin.equals(end); // fireSelectionChanged(before, snapshot()); // } // // public Selection snapshot() { // return new Selection(this); // } // // public Point getOrigin() { // return begin; // } // // public Point getDestination() { // return end; // } // // public boolean isNormal() { // return isActive() && begin.getX() != end.getX() && begin.getY() != end.getY(); // } // // public Point getLineDest() { // int x = end.getX(); // int y = end.getY(); // int ax = Math.abs(getDeltaX()); // int ay = Math.abs(getDeltaY()); // if (ax == 0 || ay == 0) return new Point(end); // if (ax > ay) { // x = begin.getX() + ay * getDx(); // } else { // y = begin.getY() + ax * getDy(); // } // return new Point(x, y); // } // // public int getDeltaX() { // return end.getX() - begin.getX(); // } // // public int getDeltaY() { // return end.getY() - begin.getY(); // } // // public int getDx() { // return begin.getX() < end.getX() ? 1 : -1; // } // // public int getDy() { // return begin.getY() < end.getY() ? 1 : -1; // } // // @Override // public String toString() { // return "(" + getBegin() + "-" + getEnd() + ")"; // } // }
import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.Selection; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class ArrangeDialog extends JDialog { private static final long serialVersionUID = 1L; private boolean isOK = false;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/Selection.java // public class Selection extends Rect { // // private boolean selection; // // private List<SelectionListener> listeners = new ArrayList<SelectionListener>(); // // public Selection() { // super(new Point(0, 0), new Point(0, 0)); // selection = false; // } // // public Selection(Selection sel) { // super(sel.begin, sel.end); // selection = sel.selection; // } // // public void addListener(SelectionListener listener) { // listeners.add(listener); // } // // private void fireSelectionChanged(Selection before, Selection current) { // for (SelectionListener listener : listeners) { // listener.selectionUpdated(before, current); // } // } // // private void fireSelectionDeleted(Selection sel) { // for (SelectionListener listener : listeners) { // listener.selectionDeleted(sel); // } // } // // public void clear() { // if (!selection) return; // fireSelectionDeleted(snapshot()); // selection = false; // } // // public boolean isActive() { // return selection; // } // // public void init(Point origin) { // Selection before = snapshot(); // this.begin = this.end = origin; // selection = false; // fireSelectionChanged(before, snapshot()); // } // // public void update(Point end) { // Selection before = snapshot(); // this.end = end; // selection = !begin.equals(end); // fireSelectionChanged(before, snapshot()); // } // // public Selection snapshot() { // return new Selection(this); // } // // public Point getOrigin() { // return begin; // } // // public Point getDestination() { // return end; // } // // public boolean isNormal() { // return isActive() && begin.getX() != end.getX() && begin.getY() != end.getY(); // } // // public Point getLineDest() { // int x = end.getX(); // int y = end.getY(); // int ax = Math.abs(getDeltaX()); // int ay = Math.abs(getDeltaY()); // if (ax == 0 || ay == 0) return new Point(end); // if (ax > ay) { // x = begin.getX() + ay * getDx(); // } else { // y = begin.getY() + ax * getDy(); // } // return new Point(x, y); // } // // public int getDeltaX() { // return end.getX() - begin.getX(); // } // // public int getDeltaY() { // return end.getY() - begin.getY(); // } // // public int getDx() { // return begin.getX() < end.getX() ? 1 : -1; // } // // public int getDy() { // return begin.getY() < end.getY() ? 1 : -1; // } // // @Override // public String toString() { // return "(" + getBegin() + "-" + getEnd() + ")"; // } // } // Path: src/ch/jbead/dialog/ArrangeDialog.java import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.Selection; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class ArrangeDialog extends JDialog { private static final long serialVersionUID = 1L; private boolean isOK = false;
private Selection selection;
damianbrunold/jbead
src/ch/jbead/dialog/ArrangeDialog.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/Selection.java // public class Selection extends Rect { // // private boolean selection; // // private List<SelectionListener> listeners = new ArrayList<SelectionListener>(); // // public Selection() { // super(new Point(0, 0), new Point(0, 0)); // selection = false; // } // // public Selection(Selection sel) { // super(sel.begin, sel.end); // selection = sel.selection; // } // // public void addListener(SelectionListener listener) { // listeners.add(listener); // } // // private void fireSelectionChanged(Selection before, Selection current) { // for (SelectionListener listener : listeners) { // listener.selectionUpdated(before, current); // } // } // // private void fireSelectionDeleted(Selection sel) { // for (SelectionListener listener : listeners) { // listener.selectionDeleted(sel); // } // } // // public void clear() { // if (!selection) return; // fireSelectionDeleted(snapshot()); // selection = false; // } // // public boolean isActive() { // return selection; // } // // public void init(Point origin) { // Selection before = snapshot(); // this.begin = this.end = origin; // selection = false; // fireSelectionChanged(before, snapshot()); // } // // public void update(Point end) { // Selection before = snapshot(); // this.end = end; // selection = !begin.equals(end); // fireSelectionChanged(before, snapshot()); // } // // public Selection snapshot() { // return new Selection(this); // } // // public Point getOrigin() { // return begin; // } // // public Point getDestination() { // return end; // } // // public boolean isNormal() { // return isActive() && begin.getX() != end.getX() && begin.getY() != end.getY(); // } // // public Point getLineDest() { // int x = end.getX(); // int y = end.getY(); // int ax = Math.abs(getDeltaX()); // int ay = Math.abs(getDeltaY()); // if (ax == 0 || ay == 0) return new Point(end); // if (ax > ay) { // x = begin.getX() + ay * getDx(); // } else { // y = begin.getY() + ax * getDy(); // } // return new Point(x, y); // } // // public int getDeltaX() { // return end.getX() - begin.getX(); // } // // public int getDeltaY() { // return end.getY() - begin.getY(); // } // // public int getDx() { // return begin.getX() < end.getX() ? 1 : -1; // } // // public int getDy() { // return begin.getY() < end.getY() ? 1 : -1; // } // // @Override // public String toString() { // return "(" + getBegin() + "-" + getEnd() + ")"; // } // }
import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.Selection; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class ArrangeDialog extends JDialog { private static final long serialVersionUID = 1L; private boolean isOK = false; private Selection selection; private Model model; private SpinnerModel horzModel = new SpinnerNumberModel(5, 0, 100, 1); private SpinnerModel vertModel = new SpinnerNumberModel(5, 0, 100, 1); private SpinnerModel copyModel = new SpinnerNumberModel(1, 0, 100, 1); private JSpinner horz = new JSpinner(horzModel); private JSpinner vert = new JSpinner(vertModel); private JSpinner Copies = new JSpinner(copyModel); private JButton bOK; private JButton bCancel;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/Selection.java // public class Selection extends Rect { // // private boolean selection; // // private List<SelectionListener> listeners = new ArrayList<SelectionListener>(); // // public Selection() { // super(new Point(0, 0), new Point(0, 0)); // selection = false; // } // // public Selection(Selection sel) { // super(sel.begin, sel.end); // selection = sel.selection; // } // // public void addListener(SelectionListener listener) { // listeners.add(listener); // } // // private void fireSelectionChanged(Selection before, Selection current) { // for (SelectionListener listener : listeners) { // listener.selectionUpdated(before, current); // } // } // // private void fireSelectionDeleted(Selection sel) { // for (SelectionListener listener : listeners) { // listener.selectionDeleted(sel); // } // } // // public void clear() { // if (!selection) return; // fireSelectionDeleted(snapshot()); // selection = false; // } // // public boolean isActive() { // return selection; // } // // public void init(Point origin) { // Selection before = snapshot(); // this.begin = this.end = origin; // selection = false; // fireSelectionChanged(before, snapshot()); // } // // public void update(Point end) { // Selection before = snapshot(); // this.end = end; // selection = !begin.equals(end); // fireSelectionChanged(before, snapshot()); // } // // public Selection snapshot() { // return new Selection(this); // } // // public Point getOrigin() { // return begin; // } // // public Point getDestination() { // return end; // } // // public boolean isNormal() { // return isActive() && begin.getX() != end.getX() && begin.getY() != end.getY(); // } // // public Point getLineDest() { // int x = end.getX(); // int y = end.getY(); // int ax = Math.abs(getDeltaX()); // int ay = Math.abs(getDeltaY()); // if (ax == 0 || ay == 0) return new Point(end); // if (ax > ay) { // x = begin.getX() + ay * getDx(); // } else { // y = begin.getY() + ax * getDy(); // } // return new Point(x, y); // } // // public int getDeltaX() { // return end.getX() - begin.getX(); // } // // public int getDeltaY() { // return end.getY() - begin.getY(); // } // // public int getDx() { // return begin.getX() < end.getX() ? 1 : -1; // } // // public int getDy() { // return begin.getY() < end.getY() ? 1 : -1; // } // // @Override // public String toString() { // return "(" + getBegin() + "-" + getEnd() + ")"; // } // } // Path: src/ch/jbead/dialog/ArrangeDialog.java import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.Selection; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class ArrangeDialog extends JDialog { private static final long serialVersionUID = 1L; private boolean isOK = false; private Selection selection; private Model model; private SpinnerModel horzModel = new SpinnerNumberModel(5, 0, 100, 1); private SpinnerModel vertModel = new SpinnerNumberModel(5, 0, 100, 1); private SpinnerModel copyModel = new SpinnerNumberModel(1, 0, 100, 1); private JSpinner horz = new JSpinner(horzModel); private JSpinner vert = new JSpinner(vertModel); private JSpinner Copies = new JSpinner(copyModel); private JButton bOK; private JButton bCancel;
public ArrangeDialog(Localization localization, Selection selection, Model model) {
damianbrunold/jbead
src/ch/jbead/ui/ColorsToolbar.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // }
import javax.swing.JToolBar; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.ui; public class ColorsToolbar extends JToolBar { private static final long serialVersionUID = 1L; private Model model;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // } // Path: src/ch/jbead/ui/ColorsToolbar.java import javax.swing.JToolBar; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.ui; public class ColorsToolbar extends JToolBar { private static final long serialVersionUID = 1L; private Model model;
public ColorsToolbar(Model model, View view, Localization localization) {
damianbrunold/jbead
src/ch/jbead/ui/ColorsToolbar.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // }
import javax.swing.JToolBar; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.ui; public class ColorsToolbar extends JToolBar { private static final long serialVersionUID = 1L; private Model model;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // } // Path: src/ch/jbead/ui/ColorsToolbar.java import javax.swing.JToolBar; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.ui; public class ColorsToolbar extends JToolBar { private static final long serialVersionUID = 1L; private Model model;
public ColorsToolbar(Model model, View view, Localization localization) {
damianbrunold/jbead
src/ch/jbead/print/DesignPrinter.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // }
import ch.jbead.Model; import ch.jbead.View; import java.awt.print.Book; import java.awt.print.PageFormat; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.util.ArrayList; import java.util.List; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.JobName; import javax.swing.JOptionPane; import ch.jbead.Localization;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public class DesignPrinter { private Model model;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // } // Path: src/ch/jbead/print/DesignPrinter.java import ch.jbead.Model; import ch.jbead.View; import java.awt.print.Book; import java.awt.print.PageFormat; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.util.ArrayList; import java.util.List; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.JobName; import javax.swing.JOptionPane; import ch.jbead.Localization; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public class DesignPrinter { private Model model;
private View view;
damianbrunold/jbead
src/ch/jbead/print/DesignPrinter.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // }
import ch.jbead.Model; import ch.jbead.View; import java.awt.print.Book; import java.awt.print.PageFormat; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.util.ArrayList; import java.util.List; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.JobName; import javax.swing.JOptionPane; import ch.jbead.Localization;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public class DesignPrinter { private Model model; private View view;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // } // Path: src/ch/jbead/print/DesignPrinter.java import ch.jbead.Model; import ch.jbead.View; import java.awt.print.Book; import java.awt.print.PageFormat; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.util.ArrayList; import java.util.List; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.JobName; import javax.swing.JOptionPane; import ch.jbead.Localization; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public class DesignPrinter { private Model model; private View view;
private Localization localization;
damianbrunold/jbead
src/ch/jbead/print/GridPrinter.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // }
import java.awt.BasicStroke; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View; import ch.jbead.util.Convert;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public abstract class GridPrinter extends PartPrinter { protected int gx = Convert.mmToPoint(3); protected int gy = gx; protected boolean fullPattern;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // } // Path: src/ch/jbead/print/GridPrinter.java import java.awt.BasicStroke; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View; import ch.jbead.util.Convert; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public abstract class GridPrinter extends PartPrinter { protected int gx = Convert.mmToPoint(3); protected int gy = gx; protected boolean fullPattern;
public GridPrinter(Model model, View view, Localization localization, boolean fullPattern) {
damianbrunold/jbead
src/ch/jbead/print/GridPrinter.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // }
import java.awt.BasicStroke; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View; import ch.jbead.util.Convert;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public abstract class GridPrinter extends PartPrinter { protected int gx = Convert.mmToPoint(3); protected int gy = gx; protected boolean fullPattern;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // } // Path: src/ch/jbead/print/GridPrinter.java import java.awt.BasicStroke; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.View; import ch.jbead.util.Convert; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public abstract class GridPrinter extends PartPrinter { protected int gx = Convert.mmToPoint(3); protected int gy = gx; protected boolean fullPattern;
public GridPrinter(Model model, View view, Localization localization, boolean fullPattern) {
damianbrunold/jbead
src/ch/jbead/fileformat/DbbMemento.java
// Path: src/ch/jbead/BeadSymbols.java // public class BeadSymbols { // // public static final String MIDDLE_DOT = "\u00b7"; // public static final String DEFAULT_SYMBOLS = MIDDLE_DOT + "abcdefghijklmnopqrstuvwxyz+-/\\*"; // public static String SYMBOLS = DEFAULT_SYMBOLS; // public static String SAVED_SYMBOLS = DEFAULT_SYMBOLS; // // static { // reloadSymbols(); // } // // public static void restoreDefaults() { // SYMBOLS = DEFAULT_SYMBOLS; // } // // public static void reloadSymbols() { // Settings settings = new Settings(); // settings.setCategory("view"); // SAVED_SYMBOLS = settings.loadString("symbols", DEFAULT_SYMBOLS); // SYMBOLS = SAVED_SYMBOLS; // } // // public static String get(byte index) { // if (index >= SYMBOLS.length()) return " "; // return SYMBOLS.substring(index, index + 1); // } // // }
import java.awt.Color; import java.io.IOException; import ch.jbead.BeadSymbols;
// draw colors flag not saved // draw symbols flag not saved // symbols string not saved } @Override public void load(JBeadInputStream in) throws IOException { width = in.readInt(); height = (DBB_FIELD_SIZE + width - 1) / width; data = new byte[width * height]; in.read(data, 0, DBB_FIELD_SIZE); colors.clear(); colors.add(in.readBackgroundColor()); for (int i = 1; i < 10; i++) { colors.add(in.readColor()); } colorIndex = readByte(in, "colorIndex"); zoomIndex = readInt(in, "zoomIndex"); shift = readInt(in, "shift"); scroll = readInt(in, "scroll"); draftVisible = in.readBool(); correctedVisible = in.readBool(); simulationVisible = in.readBool(); setDefaults(); } private void setDefaults() { reportVisible = true; drawColors = true; drawSymbols = false;
// Path: src/ch/jbead/BeadSymbols.java // public class BeadSymbols { // // public static final String MIDDLE_DOT = "\u00b7"; // public static final String DEFAULT_SYMBOLS = MIDDLE_DOT + "abcdefghijklmnopqrstuvwxyz+-/\\*"; // public static String SYMBOLS = DEFAULT_SYMBOLS; // public static String SAVED_SYMBOLS = DEFAULT_SYMBOLS; // // static { // reloadSymbols(); // } // // public static void restoreDefaults() { // SYMBOLS = DEFAULT_SYMBOLS; // } // // public static void reloadSymbols() { // Settings settings = new Settings(); // settings.setCategory("view"); // SAVED_SYMBOLS = settings.loadString("symbols", DEFAULT_SYMBOLS); // SYMBOLS = SAVED_SYMBOLS; // } // // public static String get(byte index) { // if (index >= SYMBOLS.length()) return " "; // return SYMBOLS.substring(index, index + 1); // } // // } // Path: src/ch/jbead/fileformat/DbbMemento.java import java.awt.Color; import java.io.IOException; import ch.jbead.BeadSymbols; // draw colors flag not saved // draw symbols flag not saved // symbols string not saved } @Override public void load(JBeadInputStream in) throws IOException { width = in.readInt(); height = (DBB_FIELD_SIZE + width - 1) / width; data = new byte[width * height]; in.read(data, 0, DBB_FIELD_SIZE); colors.clear(); colors.add(in.readBackgroundColor()); for (int i = 1; i < 10; i++) { colors.add(in.readColor()); } colorIndex = readByte(in, "colorIndex"); zoomIndex = readInt(in, "zoomIndex"); shift = readInt(in, "shift"); scroll = readInt(in, "scroll"); draftVisible = in.readBool(); correctedVisible = in.readBool(); simulationVisible = in.readBool(); setDefaults(); } private void setDefaults() { reportVisible = true; drawColors = true; drawSymbols = false;
symbols = BeadSymbols.SAVED_SYMBOLS;
damianbrunold/jbead
src/ch/jbead/print/PrintSettings.java
// Path: src/ch/jbead/Settings.java // public class Settings { // // private static final String BASE = "brunoldsoft/jbead"; // // private Preferences preferences = Preferences.userRoot().node(BASE); // private String category = "general"; // // public Settings() { // category = "general"; // } // // public void setCategory(String category) { // this.category = category; // } // // public String category() { // return category; // } // // public boolean hasSetting(String name) { // return preferences.node(category).get(name, null) != null; // } // // public int loadInt(String name) { // return loadInt(name, 0); // } // // public int loadInt(String name, int defaultvalue) { // return preferences.node(category).getInt(name, defaultvalue); // } // // public long loadLong(String name) { // return loadLong(name, 0); // } // // public long loadLong(String name, long defaultvalue) { // return preferences.node(category).getLong(name, defaultvalue); // } // // public boolean loadBoolean(String name) { // return loadBoolean(name, false); // } // // public boolean loadBoolean(String name, boolean defaultvalue) { // return preferences.node(category).getBoolean(name, defaultvalue); // } // // public String loadString(String name) { // return loadString(name, ""); // } // // public String loadString(String name, String defaultvalue) { // return preferences.node(category).get(name, defaultvalue); // } // // public void saveInt(String name, int value) { // preferences.node(category).putInt(name, value); // } // // public void saveLong(String name, long value) { // preferences.node(category).putLong(name, value); // } // // public void saveBoolean(String name, boolean value) { // preferences.node(category).putBoolean(name, value); // } // // public void saveString(String name, String value) { // preferences.node(category).put(name, value); // } // // public void remove(String name) { // preferences.node(category).remove(name); // } // // public void flush() throws BackingStoreException { // preferences.flush(); // } // // }
import java.awt.print.Paper; import java.awt.print.PrinterJob; import java.util.HashMap; import java.util.Map; import javax.print.PrintService; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.Copies; import javax.print.attribute.standard.MediaSizeName; import javax.print.attribute.standard.OrientationRequested; import ch.jbead.Settings;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public class PrintSettings { private static Map<String, MediaSizeName> mediamap = new HashMap<String, MediaSizeName>(); static { mediamap.put("a0", MediaSizeName.ISO_A0); mediamap.put("a1", MediaSizeName.ISO_A1); mediamap.put("a2", MediaSizeName.ISO_A2); mediamap.put("a3", MediaSizeName.ISO_A3); mediamap.put("a4", MediaSizeName.ISO_A4); mediamap.put("a5", MediaSizeName.ISO_A5); mediamap.put("a6", MediaSizeName.ISO_A6); mediamap.put("a7", MediaSizeName.ISO_A7); mediamap.put("a8", MediaSizeName.ISO_A8); mediamap.put("a9", MediaSizeName.ISO_A9); mediamap.put("a10", MediaSizeName.ISO_A10); mediamap.put("letter", MediaSizeName.NA_LETTER); mediamap.put("legal", MediaSizeName.NA_LEGAL); mediamap.put("executive", MediaSizeName.EXECUTIVE); mediamap.put("ledger", MediaSizeName.LEDGER); mediamap.put("tabloid", MediaSizeName.TABLOID); mediamap.put("invoice", MediaSizeName.INVOICE); mediamap.put("folio", MediaSizeName.FOLIO); mediamap.put("quarto", MediaSizeName.QUARTO); } private PrintService service; private PrintRequestAttributeSet attributes;
// Path: src/ch/jbead/Settings.java // public class Settings { // // private static final String BASE = "brunoldsoft/jbead"; // // private Preferences preferences = Preferences.userRoot().node(BASE); // private String category = "general"; // // public Settings() { // category = "general"; // } // // public void setCategory(String category) { // this.category = category; // } // // public String category() { // return category; // } // // public boolean hasSetting(String name) { // return preferences.node(category).get(name, null) != null; // } // // public int loadInt(String name) { // return loadInt(name, 0); // } // // public int loadInt(String name, int defaultvalue) { // return preferences.node(category).getInt(name, defaultvalue); // } // // public long loadLong(String name) { // return loadLong(name, 0); // } // // public long loadLong(String name, long defaultvalue) { // return preferences.node(category).getLong(name, defaultvalue); // } // // public boolean loadBoolean(String name) { // return loadBoolean(name, false); // } // // public boolean loadBoolean(String name, boolean defaultvalue) { // return preferences.node(category).getBoolean(name, defaultvalue); // } // // public String loadString(String name) { // return loadString(name, ""); // } // // public String loadString(String name, String defaultvalue) { // return preferences.node(category).get(name, defaultvalue); // } // // public void saveInt(String name, int value) { // preferences.node(category).putInt(name, value); // } // // public void saveLong(String name, long value) { // preferences.node(category).putLong(name, value); // } // // public void saveBoolean(String name, boolean value) { // preferences.node(category).putBoolean(name, value); // } // // public void saveString(String name, String value) { // preferences.node(category).put(name, value); // } // // public void remove(String name) { // preferences.node(category).remove(name); // } // // public void flush() throws BackingStoreException { // preferences.flush(); // } // // } // Path: src/ch/jbead/print/PrintSettings.java import java.awt.print.Paper; import java.awt.print.PrinterJob; import java.util.HashMap; import java.util.Map; import javax.print.PrintService; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.Copies; import javax.print.attribute.standard.MediaSizeName; import javax.print.attribute.standard.OrientationRequested; import ch.jbead.Settings; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public class PrintSettings { private static Map<String, MediaSizeName> mediamap = new HashMap<String, MediaSizeName>(); static { mediamap.put("a0", MediaSizeName.ISO_A0); mediamap.put("a1", MediaSizeName.ISO_A1); mediamap.put("a2", MediaSizeName.ISO_A2); mediamap.put("a3", MediaSizeName.ISO_A3); mediamap.put("a4", MediaSizeName.ISO_A4); mediamap.put("a5", MediaSizeName.ISO_A5); mediamap.put("a6", MediaSizeName.ISO_A6); mediamap.put("a7", MediaSizeName.ISO_A7); mediamap.put("a8", MediaSizeName.ISO_A8); mediamap.put("a9", MediaSizeName.ISO_A9); mediamap.put("a10", MediaSizeName.ISO_A10); mediamap.put("letter", MediaSizeName.NA_LETTER); mediamap.put("legal", MediaSizeName.NA_LEGAL); mediamap.put("executive", MediaSizeName.EXECUTIVE); mediamap.put("ledger", MediaSizeName.LEDGER); mediamap.put("tabloid", MediaSizeName.TABLOID); mediamap.put("invoice", MediaSizeName.INVOICE); mediamap.put("folio", MediaSizeName.FOLIO); mediamap.put("quarto", MediaSizeName.QUARTO); } private PrintService service; private PrintRequestAttributeSet attributes;
public PrintSettings(Settings settings) {
damianbrunold/jbead
src/ch/jbead/dialog/TechInfosDialog.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // }
import ch.jbead.Localization; import ch.jbead.fileformat.JBeadMemento; import ch.jbead.version.Version; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JTextArea;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class TechInfosDialog extends JDialog { private static final long serialVersionUID = 1L;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // Path: src/ch/jbead/dialog/TechInfosDialog.java import ch.jbead.Localization; import ch.jbead.fileformat.JBeadMemento; import ch.jbead.version.Version; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JTextArea; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class TechInfosDialog extends JDialog { private static final long serialVersionUID = 1L;
public TechInfosDialog(final Localization localization) {
damianbrunold/jbead
src/ch/jbead/dialog/InfoAboutDialog.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // }
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import ch.jbead.Localization; import ch.jbead.version.Version;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class InfoAboutDialog extends JDialog { private static final long serialVersionUID = 1L;
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // Path: src/ch/jbead/dialog/InfoAboutDialog.java import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import ch.jbead.Localization; import ch.jbead.version.Version; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.dialog; public class InfoAboutDialog extends JDialog { private static final long serialVersionUID = 1L;
public InfoAboutDialog(Localization localization) {
damianbrunold/jbead
src/ch/jbead/print/SimulationPrinter.java
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/Point.java // public class Point { // // private int x; // private int y; // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // public Point(Point pt) { // this.x = pt.x; // this.y = pt.y; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // @Override // public int hashCode() { // return x ^ y; // } // // @Override // public boolean equals(Object obj) { // Point other = (Point) obj; // if (other == null) return false; // return x == other.x && y == other.y; // } // // public Point scrolled(int scroll) { // return new Point(x, y + scroll); // } // // public Point unscrolled(int scroll) { // return new Point(x, y - scroll); // } // // public Point shifted(int shift, int width) { // return new Point((x + shift) % width, y + (x + shift) / width); // } // // public Point nextLeft() { // return new Point(x - 1, y); // } // // public Point nextRight() { // return new Point(x + 1, y); // } // // public Point nextBelow() { // return new Point(x, y - 1); // } // // public Point nextAbove() { // return new Point(x, y + 1); // } // // public Point lastLeft() { // return new Point(0, y); // } // // public Point lastRight(int width) { // return new Point(width - 1, y); // } // // @Override // public String toString() { // return x + "," + y; // } // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // }
import java.awt.Color; import java.awt.Graphics2D; import java.awt.print.PageFormat; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.Point; import ch.jbead.View;
/** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public class SimulationPrinter extends GridPrinter { public SimulationPrinter(Model model, View view, Localization localization, boolean fullPattern) { super(model, view, localization, fullPattern); } @Override protected int getColumnWidth() { return model.getWidth() * gx / 2; } @Override protected int getRows(int height) { int rows = getPrintableRows(height);
// Path: src/ch/jbead/Localization.java // public interface Localization { // // public ResourceBundle getBundle(); // public String getString(String key); // public int getMnemonic(String key); // public KeyStroke getKeyStroke(String key); // // } // // Path: src/ch/jbead/Point.java // public class Point { // // private int x; // private int y; // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // public Point(Point pt) { // this.x = pt.x; // this.y = pt.y; // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // @Override // public int hashCode() { // return x ^ y; // } // // @Override // public boolean equals(Object obj) { // Point other = (Point) obj; // if (other == null) return false; // return x == other.x && y == other.y; // } // // public Point scrolled(int scroll) { // return new Point(x, y + scroll); // } // // public Point unscrolled(int scroll) { // return new Point(x, y - scroll); // } // // public Point shifted(int shift, int width) { // return new Point((x + shift) % width, y + (x + shift) / width); // } // // public Point nextLeft() { // return new Point(x - 1, y); // } // // public Point nextRight() { // return new Point(x + 1, y); // } // // public Point nextBelow() { // return new Point(x, y - 1); // } // // public Point nextAbove() { // return new Point(x, y + 1); // } // // public Point lastLeft() { // return new Point(0, y); // } // // public Point lastRight(int width) { // return new Point(width - 1, y); // } // // @Override // public String toString() { // return x + "," + y; // } // } // // Path: src/ch/jbead/View.java // public interface View { // // public void addListener(ViewListener listener); // // public boolean drawColors(); // public boolean drawSymbols(); // // public boolean isDraftVisible(); // public boolean isCorrectedVisible(); // public boolean isSimulationVisible(); // public boolean isReportVisible(); // // public String getSelectedTool(); // public boolean isDragging(); // public void setDragging(boolean dragging); // public Selection getSelection(); // public void selectColor(byte colorIndex); // // public void refresh(); // } // Path: src/ch/jbead/print/SimulationPrinter.java import java.awt.Color; import java.awt.Graphics2D; import java.awt.print.PageFormat; import ch.jbead.Localization; import ch.jbead.Model; import ch.jbead.Point; import ch.jbead.View; /** jbead - http://www.jbead.ch Copyright (C) 2001-2012 Damian Brunold This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.jbead.print; public class SimulationPrinter extends GridPrinter { public SimulationPrinter(Model model, View view, Localization localization, boolean fullPattern) { super(model, view, localization, fullPattern); } @Override protected int getColumnWidth() { return model.getWidth() * gx / 2; } @Override protected int getRows(int height) { int rows = getPrintableRows(height);
Point pt = model.correct(new Point(model.getWidth() - 1, rows - 1));
blanu/sneakermesh
shared/src/net/blanu/sneakermesh/protocol/GiveCommand.java
// Path: shared/src/net/blanu/sneakermesh/content/Message.java // public abstract class Message implements Comparable<Message> // { // public static final int MSG_TEXT=0; // public static final int MSG_PHOTO=1; // // protected static Random random=new Random(); // protected static File tmp; // // public static Logger logger=null; // // public int type; // public long timestamp; // public int size; // public File file; // public String digest; // // static public void setLogger(Logger l) // { // logger=l; // } // // static public void log(String s) // { // if(logger==null) // { // System.out.println(s); // } // else // { // logger.log(s); // } // } // // public int compareTo(Message m) // { // return new Long(timestamp).compareTo(new Long(m.timestamp)); // } // // public static void setTmp(File f) // { // tmp=f; // } // // public static Message readMessage(DataInputStream is) throws IOException // { // int msgType=is.read(); // log("msgType: "+msgType); // // long ts=is.readLong(); // System.out.println("timestamp: "+ts); // int num=is.readInt(); // System.out.println("num: "+num); // // switch(msgType) // { // case -1: // return null; // case MSG_TEXT: // return new TextMessage(ts, num, is); // case MSG_PHOTO: // return new PhotoMessage(ts, num, is); // default: // System.out.println("Unknown message: "+msgType); // return null; // } // } // // static public Message readMessage(File f) throws IOException // { // long ts=f.lastModified(); // System.out.println("timestamp: "+ts); // int num=(int)f.length(); // // if(f.getAbsolutePath().contains("Pictures")) // { // return new PhotoMessage(ts, num, f); // } // else // { // return new TextMessage(ts, num, f); // } // } // // public Message(int t, long ts, int num, InputStream is) throws IOException // { // type=t; // timestamp=ts; // size=num; // // file=createTempFile(); // FileOutputStream out=new FileOutputStream(file); // digest=Util.pump(is, out, num); // out.close(); // file.setLastModified(timestamp); // } // // static protected File createTempFile() throws IOException // { // if(tmp==null) // { // return File.createTempFile("sneakermesh", "tmp"); // } // else // { // String filename=String.valueOf(new Date().getTime())+"."+String.valueOf(random.nextInt()); // return new File(tmp, filename); // } // } // // public Message(int t, long ts, int num, File f) throws IOException // { // type=t; // timestamp=ts; // size=num; // file=f; // digest=Util.hash(file); // } // // public void save(File destDir) // { // File dest=new File(destDir, digest); // file.renameTo(dest); // dest.setLastModified(timestamp); // file=dest; // } // // public void write(DataOutputStream out) throws IOException // { // out.write(type); // out.writeLong(timestamp); // out.writeInt(size); // writeData(out); // } // // public void writeData(OutputStream out) throws FileNotFoundException // { // InputStream in=new FileInputStream(file); // Util.pump(in, out, size); // } // // public String toString() // { // return "[Message: "+timestamp+"]"; // } // }
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashSet; import java.util.Set; import net.blanu.sneakermesh.content.Message;
package net.blanu.sneakermesh.protocol; public class GiveCommand extends Command { public String digest;
// Path: shared/src/net/blanu/sneakermesh/content/Message.java // public abstract class Message implements Comparable<Message> // { // public static final int MSG_TEXT=0; // public static final int MSG_PHOTO=1; // // protected static Random random=new Random(); // protected static File tmp; // // public static Logger logger=null; // // public int type; // public long timestamp; // public int size; // public File file; // public String digest; // // static public void setLogger(Logger l) // { // logger=l; // } // // static public void log(String s) // { // if(logger==null) // { // System.out.println(s); // } // else // { // logger.log(s); // } // } // // public int compareTo(Message m) // { // return new Long(timestamp).compareTo(new Long(m.timestamp)); // } // // public static void setTmp(File f) // { // tmp=f; // } // // public static Message readMessage(DataInputStream is) throws IOException // { // int msgType=is.read(); // log("msgType: "+msgType); // // long ts=is.readLong(); // System.out.println("timestamp: "+ts); // int num=is.readInt(); // System.out.println("num: "+num); // // switch(msgType) // { // case -1: // return null; // case MSG_TEXT: // return new TextMessage(ts, num, is); // case MSG_PHOTO: // return new PhotoMessage(ts, num, is); // default: // System.out.println("Unknown message: "+msgType); // return null; // } // } // // static public Message readMessage(File f) throws IOException // { // long ts=f.lastModified(); // System.out.println("timestamp: "+ts); // int num=(int)f.length(); // // if(f.getAbsolutePath().contains("Pictures")) // { // return new PhotoMessage(ts, num, f); // } // else // { // return new TextMessage(ts, num, f); // } // } // // public Message(int t, long ts, int num, InputStream is) throws IOException // { // type=t; // timestamp=ts; // size=num; // // file=createTempFile(); // FileOutputStream out=new FileOutputStream(file); // digest=Util.pump(is, out, num); // out.close(); // file.setLastModified(timestamp); // } // // static protected File createTempFile() throws IOException // { // if(tmp==null) // { // return File.createTempFile("sneakermesh", "tmp"); // } // else // { // String filename=String.valueOf(new Date().getTime())+"."+String.valueOf(random.nextInt()); // return new File(tmp, filename); // } // } // // public Message(int t, long ts, int num, File f) throws IOException // { // type=t; // timestamp=ts; // size=num; // file=f; // digest=Util.hash(file); // } // // public void save(File destDir) // { // File dest=new File(destDir, digest); // file.renameTo(dest); // dest.setLastModified(timestamp); // file=dest; // } // // public void write(DataOutputStream out) throws IOException // { // out.write(type); // out.writeLong(timestamp); // out.writeInt(size); // writeData(out); // } // // public void writeData(OutputStream out) throws FileNotFoundException // { // InputStream in=new FileInputStream(file); // Util.pump(in, out, size); // } // // public String toString() // { // return "[Message: "+timestamp+"]"; // } // } // Path: shared/src/net/blanu/sneakermesh/protocol/GiveCommand.java import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashSet; import java.util.Set; import net.blanu.sneakermesh.content.Message; package net.blanu.sneakermesh.protocol; public class GiveCommand extends Command { public String digest;
public Message msg;
blanu/sneakermesh
android/src/net/blanu/sneakermesh/ui/SneakermeshListActivity.java
// Path: android/src/net/blanu/sneakermesh/LANProbeService.java // public class LANProbeService extends Service implements Logger // { // private static final String TAG = "LANProbe"; // static Sneakermesh mesh=null; // static SyncServer probe=null; // static UDPBroadcastTask broadcast=null; // static SyncerTask syncer=null; // // static public String BROADCAST_ACTION; // static Intent intent; // private final IBinder mBinder = new LocalBinder(); // // List<String> lines=new ArrayList<String>(); // // @Override // public void onCreate() { // super.onCreate(); // BROADCAST_ACTION=this.getPackageName()+".log"; // intent = new Intent(BROADCAST_ACTION); // // Message.setLogger(this); // net.blanu.sneakermesh.Util.setLogger(this); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // if(mesh==null) // { // if(checkStorage()) // { // mesh=new AndroidSneakermesh(this); // // Timer timer = new Timer(); // // broadcast=new UDPBroadcastTask(this); // timer.scheduleAtFixedRate(broadcast, 1, 30*1000); // // syncer=new SyncerTask(mesh); // timer.scheduleAtFixedRate(syncer, 1, 30*1000); // // try { // probe=new SyncServer(mesh, UDPUtil.getBroadcastAddress(this)); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // return START_STICKY; // } // // public Sneakermesh getMesh() // { // return mesh; // } // // public class LocalBinder extends Binder { // public LANProbeService getService() { // return LANProbeService.this; // } // } // // @Override // public IBinder onBind(Intent intent) { // return mBinder; // } // // @Override // public void onDestroy() { // super.onDestroy(); // } // // public void forceSync() // { // syncer.run(); // } // // public void forceBroadcast() // { // broadcast.run(); // } // // public void log(String s) // { // Log.e(TAG, s); // // lines.add(s); // if(lines.size()>30) // { // lines.remove(0); // } // // intent.putExtra("logline", net.blanu.sneakermesh.Util.join((String[])lines.toArray(new String[0]), "\n")); // sendBroadcast(intent); // } // // public boolean checkStorage() // { // boolean mExternalStorageAvailable = false; // boolean mExternalStorageWriteable = false; // String state = Environment.getExternalStorageState(); // // if (Environment.MEDIA_MOUNTED.equals(state)) { // // We can read and write the media // mExternalStorageAvailable = mExternalStorageWriteable = true; // } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // // We can only read the media // mExternalStorageAvailable = true; // mExternalStorageWriteable = false; // } else { // // Something else is wrong. It may be one of many other states, but all we need // // to know is we can neither read nor write // mExternalStorageAvailable = mExternalStorageWriteable = false; // } // // return mExternalStorageAvailable && mExternalStorageWriteable; // } // } // // Path: shared/src/net/blanu/sneakermesh/Logger.java // public interface Logger { // public void log(String s); // } // // Path: android/src/net/blanu/sneakermesh/LANProbeService.java // public class LocalBinder extends Binder { // public LANProbeService getService() { // return LANProbeService.this; // } // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import net.blanu.sneakermesh.LANProbeService; import net.blanu.sneakermesh.Logger; import net.blanu.sneakermesh.R; import net.blanu.sneakermesh.LANProbeService.LocalBinder; import net.blanu.sneakermesh.R.id; import net.blanu.sneakermesh.R.menu; import android.app.Activity; import android.app.ListActivity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast;
package net.blanu.sneakermesh.ui; abstract public class SneakermeshListActivity extends ListActivity implements Logger { private static final String TAG="SneakermeshListActivity"; Intent serviceIntent; String REFRESH_ACTION; ArrayAdapter<String> adapter;
// Path: android/src/net/blanu/sneakermesh/LANProbeService.java // public class LANProbeService extends Service implements Logger // { // private static final String TAG = "LANProbe"; // static Sneakermesh mesh=null; // static SyncServer probe=null; // static UDPBroadcastTask broadcast=null; // static SyncerTask syncer=null; // // static public String BROADCAST_ACTION; // static Intent intent; // private final IBinder mBinder = new LocalBinder(); // // List<String> lines=new ArrayList<String>(); // // @Override // public void onCreate() { // super.onCreate(); // BROADCAST_ACTION=this.getPackageName()+".log"; // intent = new Intent(BROADCAST_ACTION); // // Message.setLogger(this); // net.blanu.sneakermesh.Util.setLogger(this); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // if(mesh==null) // { // if(checkStorage()) // { // mesh=new AndroidSneakermesh(this); // // Timer timer = new Timer(); // // broadcast=new UDPBroadcastTask(this); // timer.scheduleAtFixedRate(broadcast, 1, 30*1000); // // syncer=new SyncerTask(mesh); // timer.scheduleAtFixedRate(syncer, 1, 30*1000); // // try { // probe=new SyncServer(mesh, UDPUtil.getBroadcastAddress(this)); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // return START_STICKY; // } // // public Sneakermesh getMesh() // { // return mesh; // } // // public class LocalBinder extends Binder { // public LANProbeService getService() { // return LANProbeService.this; // } // } // // @Override // public IBinder onBind(Intent intent) { // return mBinder; // } // // @Override // public void onDestroy() { // super.onDestroy(); // } // // public void forceSync() // { // syncer.run(); // } // // public void forceBroadcast() // { // broadcast.run(); // } // // public void log(String s) // { // Log.e(TAG, s); // // lines.add(s); // if(lines.size()>30) // { // lines.remove(0); // } // // intent.putExtra("logline", net.blanu.sneakermesh.Util.join((String[])lines.toArray(new String[0]), "\n")); // sendBroadcast(intent); // } // // public boolean checkStorage() // { // boolean mExternalStorageAvailable = false; // boolean mExternalStorageWriteable = false; // String state = Environment.getExternalStorageState(); // // if (Environment.MEDIA_MOUNTED.equals(state)) { // // We can read and write the media // mExternalStorageAvailable = mExternalStorageWriteable = true; // } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // // We can only read the media // mExternalStorageAvailable = true; // mExternalStorageWriteable = false; // } else { // // Something else is wrong. It may be one of many other states, but all we need // // to know is we can neither read nor write // mExternalStorageAvailable = mExternalStorageWriteable = false; // } // // return mExternalStorageAvailable && mExternalStorageWriteable; // } // } // // Path: shared/src/net/blanu/sneakermesh/Logger.java // public interface Logger { // public void log(String s); // } // // Path: android/src/net/blanu/sneakermesh/LANProbeService.java // public class LocalBinder extends Binder { // public LANProbeService getService() { // return LANProbeService.this; // } // } // Path: android/src/net/blanu/sneakermesh/ui/SneakermeshListActivity.java import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import net.blanu.sneakermesh.LANProbeService; import net.blanu.sneakermesh.Logger; import net.blanu.sneakermesh.R; import net.blanu.sneakermesh.LANProbeService.LocalBinder; import net.blanu.sneakermesh.R.id; import net.blanu.sneakermesh.R.menu; import android.app.Activity; import android.app.ListActivity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; package net.blanu.sneakermesh.ui; abstract public class SneakermeshListActivity extends ListActivity implements Logger { private static final String TAG="SneakermeshListActivity"; Intent serviceIntent; String REFRESH_ACTION; ArrayAdapter<String> adapter;
LANProbeService probe;
blanu/sneakermesh
android/src/net/blanu/sneakermesh/ui/SneakermeshActivity.java
// Path: android/src/net/blanu/sneakermesh/LANProbeService.java // public class LANProbeService extends Service implements Logger // { // private static final String TAG = "LANProbe"; // static Sneakermesh mesh=null; // static SyncServer probe=null; // static UDPBroadcastTask broadcast=null; // static SyncerTask syncer=null; // // static public String BROADCAST_ACTION; // static Intent intent; // private final IBinder mBinder = new LocalBinder(); // // List<String> lines=new ArrayList<String>(); // // @Override // public void onCreate() { // super.onCreate(); // BROADCAST_ACTION=this.getPackageName()+".log"; // intent = new Intent(BROADCAST_ACTION); // // Message.setLogger(this); // net.blanu.sneakermesh.Util.setLogger(this); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // if(mesh==null) // { // if(checkStorage()) // { // mesh=new AndroidSneakermesh(this); // // Timer timer = new Timer(); // // broadcast=new UDPBroadcastTask(this); // timer.scheduleAtFixedRate(broadcast, 1, 30*1000); // // syncer=new SyncerTask(mesh); // timer.scheduleAtFixedRate(syncer, 1, 30*1000); // // try { // probe=new SyncServer(mesh, UDPUtil.getBroadcastAddress(this)); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // return START_STICKY; // } // // public Sneakermesh getMesh() // { // return mesh; // } // // public class LocalBinder extends Binder { // public LANProbeService getService() { // return LANProbeService.this; // } // } // // @Override // public IBinder onBind(Intent intent) { // return mBinder; // } // // @Override // public void onDestroy() { // super.onDestroy(); // } // // public void forceSync() // { // syncer.run(); // } // // public void forceBroadcast() // { // broadcast.run(); // } // // public void log(String s) // { // Log.e(TAG, s); // // lines.add(s); // if(lines.size()>30) // { // lines.remove(0); // } // // intent.putExtra("logline", net.blanu.sneakermesh.Util.join((String[])lines.toArray(new String[0]), "\n")); // sendBroadcast(intent); // } // // public boolean checkStorage() // { // boolean mExternalStorageAvailable = false; // boolean mExternalStorageWriteable = false; // String state = Environment.getExternalStorageState(); // // if (Environment.MEDIA_MOUNTED.equals(state)) { // // We can read and write the media // mExternalStorageAvailable = mExternalStorageWriteable = true; // } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // // We can only read the media // mExternalStorageAvailable = true; // mExternalStorageWriteable = false; // } else { // // Something else is wrong. It may be one of many other states, but all we need // // to know is we can neither read nor write // mExternalStorageAvailable = mExternalStorageWriteable = false; // } // // return mExternalStorageAvailable && mExternalStorageWriteable; // } // } // // Path: shared/src/net/blanu/sneakermesh/Logger.java // public interface Logger { // public void log(String s); // } // // Path: android/src/net/blanu/sneakermesh/LANProbeService.java // public class LocalBinder extends Binder { // public LANProbeService getService() { // return LANProbeService.this; // } // }
import net.blanu.sneakermesh.LANProbeService; import net.blanu.sneakermesh.Logger; import net.blanu.sneakermesh.R; import net.blanu.sneakermesh.LANProbeService.LocalBinder; import net.blanu.sneakermesh.R.id; import net.blanu.sneakermesh.R.menu; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView;
package net.blanu.sneakermesh.ui; public class SneakermeshActivity extends Activity implements Logger { private static final String TAG="SneakermeshActivity"; Intent serviceIntent;
// Path: android/src/net/blanu/sneakermesh/LANProbeService.java // public class LANProbeService extends Service implements Logger // { // private static final String TAG = "LANProbe"; // static Sneakermesh mesh=null; // static SyncServer probe=null; // static UDPBroadcastTask broadcast=null; // static SyncerTask syncer=null; // // static public String BROADCAST_ACTION; // static Intent intent; // private final IBinder mBinder = new LocalBinder(); // // List<String> lines=new ArrayList<String>(); // // @Override // public void onCreate() { // super.onCreate(); // BROADCAST_ACTION=this.getPackageName()+".log"; // intent = new Intent(BROADCAST_ACTION); // // Message.setLogger(this); // net.blanu.sneakermesh.Util.setLogger(this); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // if(mesh==null) // { // if(checkStorage()) // { // mesh=new AndroidSneakermesh(this); // // Timer timer = new Timer(); // // broadcast=new UDPBroadcastTask(this); // timer.scheduleAtFixedRate(broadcast, 1, 30*1000); // // syncer=new SyncerTask(mesh); // timer.scheduleAtFixedRate(syncer, 1, 30*1000); // // try { // probe=new SyncServer(mesh, UDPUtil.getBroadcastAddress(this)); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // return START_STICKY; // } // // public Sneakermesh getMesh() // { // return mesh; // } // // public class LocalBinder extends Binder { // public LANProbeService getService() { // return LANProbeService.this; // } // } // // @Override // public IBinder onBind(Intent intent) { // return mBinder; // } // // @Override // public void onDestroy() { // super.onDestroy(); // } // // public void forceSync() // { // syncer.run(); // } // // public void forceBroadcast() // { // broadcast.run(); // } // // public void log(String s) // { // Log.e(TAG, s); // // lines.add(s); // if(lines.size()>30) // { // lines.remove(0); // } // // intent.putExtra("logline", net.blanu.sneakermesh.Util.join((String[])lines.toArray(new String[0]), "\n")); // sendBroadcast(intent); // } // // public boolean checkStorage() // { // boolean mExternalStorageAvailable = false; // boolean mExternalStorageWriteable = false; // String state = Environment.getExternalStorageState(); // // if (Environment.MEDIA_MOUNTED.equals(state)) { // // We can read and write the media // mExternalStorageAvailable = mExternalStorageWriteable = true; // } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // // We can only read the media // mExternalStorageAvailable = true; // mExternalStorageWriteable = false; // } else { // // Something else is wrong. It may be one of many other states, but all we need // // to know is we can neither read nor write // mExternalStorageAvailable = mExternalStorageWriteable = false; // } // // return mExternalStorageAvailable && mExternalStorageWriteable; // } // } // // Path: shared/src/net/blanu/sneakermesh/Logger.java // public interface Logger { // public void log(String s); // } // // Path: android/src/net/blanu/sneakermesh/LANProbeService.java // public class LocalBinder extends Binder { // public LANProbeService getService() { // return LANProbeService.this; // } // } // Path: android/src/net/blanu/sneakermesh/ui/SneakermeshActivity.java import net.blanu.sneakermesh.LANProbeService; import net.blanu.sneakermesh.Logger; import net.blanu.sneakermesh.R; import net.blanu.sneakermesh.LANProbeService.LocalBinder; import net.blanu.sneakermesh.R.id; import net.blanu.sneakermesh.R.menu; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; package net.blanu.sneakermesh.ui; public class SneakermeshActivity extends Activity implements Logger { private static final String TAG="SneakermeshActivity"; Intent serviceIntent;
public LANProbeService probe;
blanu/sneakermesh
laptop/src/net/blanu/sneakermesh/ListMessages.java
// Path: shared/src/net/blanu/sneakermesh/content/Message.java // public abstract class Message implements Comparable<Message> // { // public static final int MSG_TEXT=0; // public static final int MSG_PHOTO=1; // // protected static Random random=new Random(); // protected static File tmp; // // public static Logger logger=null; // // public int type; // public long timestamp; // public int size; // public File file; // public String digest; // // static public void setLogger(Logger l) // { // logger=l; // } // // static public void log(String s) // { // if(logger==null) // { // System.out.println(s); // } // else // { // logger.log(s); // } // } // // public int compareTo(Message m) // { // return new Long(timestamp).compareTo(new Long(m.timestamp)); // } // // public static void setTmp(File f) // { // tmp=f; // } // // public static Message readMessage(DataInputStream is) throws IOException // { // int msgType=is.read(); // log("msgType: "+msgType); // // long ts=is.readLong(); // System.out.println("timestamp: "+ts); // int num=is.readInt(); // System.out.println("num: "+num); // // switch(msgType) // { // case -1: // return null; // case MSG_TEXT: // return new TextMessage(ts, num, is); // case MSG_PHOTO: // return new PhotoMessage(ts, num, is); // default: // System.out.println("Unknown message: "+msgType); // return null; // } // } // // static public Message readMessage(File f) throws IOException // { // long ts=f.lastModified(); // System.out.println("timestamp: "+ts); // int num=(int)f.length(); // // if(f.getAbsolutePath().contains("Pictures")) // { // return new PhotoMessage(ts, num, f); // } // else // { // return new TextMessage(ts, num, f); // } // } // // public Message(int t, long ts, int num, InputStream is) throws IOException // { // type=t; // timestamp=ts; // size=num; // // file=createTempFile(); // FileOutputStream out=new FileOutputStream(file); // digest=Util.pump(is, out, num); // out.close(); // file.setLastModified(timestamp); // } // // static protected File createTempFile() throws IOException // { // if(tmp==null) // { // return File.createTempFile("sneakermesh", "tmp"); // } // else // { // String filename=String.valueOf(new Date().getTime())+"."+String.valueOf(random.nextInt()); // return new File(tmp, filename); // } // } // // public Message(int t, long ts, int num, File f) throws IOException // { // type=t; // timestamp=ts; // size=num; // file=f; // digest=Util.hash(file); // } // // public void save(File destDir) // { // File dest=new File(destDir, digest); // file.renameTo(dest); // dest.setLastModified(timestamp); // file=dest; // } // // public void write(DataOutputStream out) throws IOException // { // out.write(type); // out.writeLong(timestamp); // out.writeInt(size); // writeData(out); // } // // public void writeData(OutputStream out) throws FileNotFoundException // { // InputStream in=new FileInputStream(file); // Util.pump(in, out, size); // } // // public String toString() // { // return "[Message: "+timestamp+"]"; // } // } // // Path: shared/src/net/blanu/sneakermesh/content/TextMessage.java // public class TextMessage extends Message // { // public TextMessage(long ts, int num, InputStream is) throws IOException // { // super(MSG_TEXT, ts, num, is); // } // // public TextMessage(long ts, int num, File f) throws IOException // { // super(MSG_TEXT, ts, num, f); // } // // public TextMessage(long ts, String s) throws IOException // { // super(MSG_TEXT, ts, s.length(), new ByteArrayInputStream(s.getBytes())); // } // // public TextMessage(String s) throws IOException // { // this(new Date().getTime(), s); // } // // public String getText() // { // try // { // FileInputStream in=new FileInputStream(file); // byte[] buff=Util.fillBuffer(in, size); // return new String(buff); // } // catch(Exception e) // { // e.printStackTrace(); // return null; // } // } // // public String toString() // { // return "[Text]"; // } // }
import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Scanner; import net.blanu.sneakermesh.content.Message; import net.blanu.sneakermesh.content.TextMessage;
package net.blanu.sneakermesh; public class ListMessages { public static void main(String[] args) throws IOException { Sneakermesh mesh=new LaptopSneakermesh();
// Path: shared/src/net/blanu/sneakermesh/content/Message.java // public abstract class Message implements Comparable<Message> // { // public static final int MSG_TEXT=0; // public static final int MSG_PHOTO=1; // // protected static Random random=new Random(); // protected static File tmp; // // public static Logger logger=null; // // public int type; // public long timestamp; // public int size; // public File file; // public String digest; // // static public void setLogger(Logger l) // { // logger=l; // } // // static public void log(String s) // { // if(logger==null) // { // System.out.println(s); // } // else // { // logger.log(s); // } // } // // public int compareTo(Message m) // { // return new Long(timestamp).compareTo(new Long(m.timestamp)); // } // // public static void setTmp(File f) // { // tmp=f; // } // // public static Message readMessage(DataInputStream is) throws IOException // { // int msgType=is.read(); // log("msgType: "+msgType); // // long ts=is.readLong(); // System.out.println("timestamp: "+ts); // int num=is.readInt(); // System.out.println("num: "+num); // // switch(msgType) // { // case -1: // return null; // case MSG_TEXT: // return new TextMessage(ts, num, is); // case MSG_PHOTO: // return new PhotoMessage(ts, num, is); // default: // System.out.println("Unknown message: "+msgType); // return null; // } // } // // static public Message readMessage(File f) throws IOException // { // long ts=f.lastModified(); // System.out.println("timestamp: "+ts); // int num=(int)f.length(); // // if(f.getAbsolutePath().contains("Pictures")) // { // return new PhotoMessage(ts, num, f); // } // else // { // return new TextMessage(ts, num, f); // } // } // // public Message(int t, long ts, int num, InputStream is) throws IOException // { // type=t; // timestamp=ts; // size=num; // // file=createTempFile(); // FileOutputStream out=new FileOutputStream(file); // digest=Util.pump(is, out, num); // out.close(); // file.setLastModified(timestamp); // } // // static protected File createTempFile() throws IOException // { // if(tmp==null) // { // return File.createTempFile("sneakermesh", "tmp"); // } // else // { // String filename=String.valueOf(new Date().getTime())+"."+String.valueOf(random.nextInt()); // return new File(tmp, filename); // } // } // // public Message(int t, long ts, int num, File f) throws IOException // { // type=t; // timestamp=ts; // size=num; // file=f; // digest=Util.hash(file); // } // // public void save(File destDir) // { // File dest=new File(destDir, digest); // file.renameTo(dest); // dest.setLastModified(timestamp); // file=dest; // } // // public void write(DataOutputStream out) throws IOException // { // out.write(type); // out.writeLong(timestamp); // out.writeInt(size); // writeData(out); // } // // public void writeData(OutputStream out) throws FileNotFoundException // { // InputStream in=new FileInputStream(file); // Util.pump(in, out, size); // } // // public String toString() // { // return "[Message: "+timestamp+"]"; // } // } // // Path: shared/src/net/blanu/sneakermesh/content/TextMessage.java // public class TextMessage extends Message // { // public TextMessage(long ts, int num, InputStream is) throws IOException // { // super(MSG_TEXT, ts, num, is); // } // // public TextMessage(long ts, int num, File f) throws IOException // { // super(MSG_TEXT, ts, num, f); // } // // public TextMessage(long ts, String s) throws IOException // { // super(MSG_TEXT, ts, s.length(), new ByteArrayInputStream(s.getBytes())); // } // // public TextMessage(String s) throws IOException // { // this(new Date().getTime(), s); // } // // public String getText() // { // try // { // FileInputStream in=new FileInputStream(file); // byte[] buff=Util.fillBuffer(in, size); // return new String(buff); // } // catch(Exception e) // { // e.printStackTrace(); // return null; // } // } // // public String toString() // { // return "[Text]"; // } // } // Path: laptop/src/net/blanu/sneakermesh/ListMessages.java import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Scanner; import net.blanu.sneakermesh.content.Message; import net.blanu.sneakermesh.content.TextMessage; package net.blanu.sneakermesh; public class ListMessages { public static void main(String[] args) throws IOException { Sneakermesh mesh=new LaptopSneakermesh();
List<Message> msgs=mesh.getMessages();
blanu/sneakermesh
laptop/src/net/blanu/sneakermesh/LANProbeService.java
// Path: shared/src/net/blanu/sneakermesh/udp/SyncServer.java // public class SyncServer // { // private static final String TAG = "UDPLANProbe"; // private static final int MAX_PROBES=10; // Sneakermesh mesh; // DatagramSocket socket; // DatagramSocket broadcastSocket; // String data="\0x00"; // // ListenThread listener; // BroadcastListenThread broadcastListener; // // public SyncServer(Sneakermesh sm, InetAddress broadcastAddress) // { // mesh=sm; // // try { // socket = new DatagramSocket(11917); // // broadcastSocket = new DatagramSocket(11916); // broadcastSocket.setBroadcast(true); // } catch (SocketException e) { // e.printStackTrace(); // } // // listener=new ListenThread(); // listener.start(); // // broadcastListener=new BroadcastListenThread(); // broadcastListener.start(); // } // // public void log(String s) // { // mesh.log(s); // } // // private class ListenThread extends Thread // { // public void run() // { // List<String> ips=Util.getLocalIpAddresses(); // // log("running ListenThread"); // while(true) // { // try { // byte[] buf = new byte[1024]; // DatagramPacket packet = new DatagramPacket(buf, buf.length); // log("ready to receive udp packet"); // socket.receive(packet); // log("received udp packet from "+packet.getAddress().toString()); // log("I am "+ips); // // InetAddress peer=packet.getAddress(); // if(!ips.contains(peer.toString())) // Don't connect to self // { // log("real peer!"); // mesh.addPeer(peer); // Command cmd=Command.readCommand(peer.toString(), buf); // mesh.execute(cmd); // } // } catch (Exception e) { // e.printStackTrace(); // return; // } // } // } // } // // private class BroadcastListenThread extends Thread // { // public void run() // { // List<String> ips=Util.getLocalIpAddresses(); // // log("running ListenThread"); // while(true) // { // try { // byte[] buf = new byte[1024]; // DatagramPacket packet = new DatagramPacket(buf, buf.length); // log("ready to receive udp broadcast"); // broadcastSocket.receive(packet); // log("received udp broadcast from "+packet.getAddress().toString()); // // InetAddress peer=packet.getAddress(); // if(!ips.contains(peer.toString())) // Don't connect to self // { // mesh.addPeer(peer); // } // } catch (Exception e) { // e.printStackTrace(); // return; // } // } // } // } // }
import net.blanu.sneakermesh.udp.SyncServer;
package net.blanu.sneakermesh; public class LANProbeService implements Logger { private static final String TAG = "LANProbeService"; Sneakermesh mesh=null; LANProbe probe=null; public LANProbeService() { mesh=new LaptopSneakermesh(); try {
// Path: shared/src/net/blanu/sneakermesh/udp/SyncServer.java // public class SyncServer // { // private static final String TAG = "UDPLANProbe"; // private static final int MAX_PROBES=10; // Sneakermesh mesh; // DatagramSocket socket; // DatagramSocket broadcastSocket; // String data="\0x00"; // // ListenThread listener; // BroadcastListenThread broadcastListener; // // public SyncServer(Sneakermesh sm, InetAddress broadcastAddress) // { // mesh=sm; // // try { // socket = new DatagramSocket(11917); // // broadcastSocket = new DatagramSocket(11916); // broadcastSocket.setBroadcast(true); // } catch (SocketException e) { // e.printStackTrace(); // } // // listener=new ListenThread(); // listener.start(); // // broadcastListener=new BroadcastListenThread(); // broadcastListener.start(); // } // // public void log(String s) // { // mesh.log(s); // } // // private class ListenThread extends Thread // { // public void run() // { // List<String> ips=Util.getLocalIpAddresses(); // // log("running ListenThread"); // while(true) // { // try { // byte[] buf = new byte[1024]; // DatagramPacket packet = new DatagramPacket(buf, buf.length); // log("ready to receive udp packet"); // socket.receive(packet); // log("received udp packet from "+packet.getAddress().toString()); // log("I am "+ips); // // InetAddress peer=packet.getAddress(); // if(!ips.contains(peer.toString())) // Don't connect to self // { // log("real peer!"); // mesh.addPeer(peer); // Command cmd=Command.readCommand(peer.toString(), buf); // mesh.execute(cmd); // } // } catch (Exception e) { // e.printStackTrace(); // return; // } // } // } // } // // private class BroadcastListenThread extends Thread // { // public void run() // { // List<String> ips=Util.getLocalIpAddresses(); // // log("running ListenThread"); // while(true) // { // try { // byte[] buf = new byte[1024]; // DatagramPacket packet = new DatagramPacket(buf, buf.length); // log("ready to receive udp broadcast"); // broadcastSocket.receive(packet); // log("received udp broadcast from "+packet.getAddress().toString()); // // InetAddress peer=packet.getAddress(); // if(!ips.contains(peer.toString())) // Don't connect to self // { // mesh.addPeer(peer); // } // } catch (Exception e) { // e.printStackTrace(); // return; // } // } // } // } // } // Path: laptop/src/net/blanu/sneakermesh/LANProbeService.java import net.blanu.sneakermesh.udp.SyncServer; package net.blanu.sneakermesh; public class LANProbeService implements Logger { private static final String TAG = "LANProbeService"; Sneakermesh mesh=null; LANProbe probe=null; public LANProbeService() { mesh=new LaptopSneakermesh(); try {
SyncServer server=new SyncServer(mesh);
blanu/sneakermesh
laptop/src/net/blanu/sneakermesh/AddMessage.java
// Path: shared/src/net/blanu/sneakermesh/content/TextMessage.java // public class TextMessage extends Message // { // public TextMessage(long ts, int num, InputStream is) throws IOException // { // super(MSG_TEXT, ts, num, is); // } // // public TextMessage(long ts, int num, File f) throws IOException // { // super(MSG_TEXT, ts, num, f); // } // // public TextMessage(long ts, String s) throws IOException // { // super(MSG_TEXT, ts, s.length(), new ByteArrayInputStream(s.getBytes())); // } // // public TextMessage(String s) throws IOException // { // this(new Date().getTime(), s); // } // // public String getText() // { // try // { // FileInputStream in=new FileInputStream(file); // byte[] buff=Util.fillBuffer(in, size); // return new String(buff); // } // catch(Exception e) // { // e.printStackTrace(); // return null; // } // } // // public String toString() // { // return "[Text]"; // } // }
import java.io.IOException; import java.util.Scanner; import net.blanu.sneakermesh.content.TextMessage;
package net.blanu.sneakermesh; public class AddMessage { public static void main(String[] args) throws IOException { System.out.print("Enter message: "); Scanner scanner=new Scanner(System.in); String msg=scanner.nextLine(); Sneakermesh mesh=new LaptopSneakermesh();
// Path: shared/src/net/blanu/sneakermesh/content/TextMessage.java // public class TextMessage extends Message // { // public TextMessage(long ts, int num, InputStream is) throws IOException // { // super(MSG_TEXT, ts, num, is); // } // // public TextMessage(long ts, int num, File f) throws IOException // { // super(MSG_TEXT, ts, num, f); // } // // public TextMessage(long ts, String s) throws IOException // { // super(MSG_TEXT, ts, s.length(), new ByteArrayInputStream(s.getBytes())); // } // // public TextMessage(String s) throws IOException // { // this(new Date().getTime(), s); // } // // public String getText() // { // try // { // FileInputStream in=new FileInputStream(file); // byte[] buff=Util.fillBuffer(in, size); // return new String(buff); // } // catch(Exception e) // { // e.printStackTrace(); // return null; // } // } // // public String toString() // { // return "[Text]"; // } // } // Path: laptop/src/net/blanu/sneakermesh/AddMessage.java import java.io.IOException; import java.util.Scanner; import net.blanu.sneakermesh.content.TextMessage; package net.blanu.sneakermesh; public class AddMessage { public static void main(String[] args) throws IOException { System.out.print("Enter message: "); Scanner scanner=new Scanner(System.in); String msg=scanner.nextLine(); Sneakermesh mesh=new LaptopSneakermesh();
mesh.addMessage(new TextMessage(msg));
lqd-io/liquid-sdk-android
liquid/src/test/java/io/lqd/sdk/LiquidTest.java
// Path: liquid/src/main/java/io/lqd/sdk/model/LQUser.java // public class LQUser extends LQModel { // // private static final long serialVersionUID = 1582937331182018907L; // private static final String[] RESERVED_KEYS = {"unique_id", "identified"}; // // private String mIdentifier; // private boolean mIdentified; // private HashMap<String, Object> mAttributes = new HashMap<String, Object>(); // // public LQUser(String identifier) { // this(identifier, new HashMap<String,Object>()); // } // // public LQUser(String identifier, boolean identified) { // this(identifier, new HashMap<String,Object>(), identified); // } // // public LQUser(String identifier, HashMap<String, Object> attributes) { // this(identifier, attributes, true); // } // // public LQUser(String identifier, HashMap<String, Object> attributes, boolean identified) { // mIdentifier = identifier; // mAttributes = attributes; // this.setIdentified(identified); // attributesCheck(); // // } // // // Attributes // public String getIdentifier() { // return mIdentifier; // } // // public String setIdentifierForPrefs(String identifier){ // mIdentifier = identifier; // return mIdentifier; // } // // public boolean isIdentified() { // return mIdentified; // } // // public void setIdentified(boolean mAutoIdentified) { // this.mIdentified = mAutoIdentified; // } // // @Override // public boolean equals(Object o) { // return (o instanceof LQUser) && ( this.toJSON().toString().equals(((LQUser) o).toJSON().toString())); // } // // public void clearCustomAttributes() { // setAttributes(new HashMap<String, Object>()); // } // // public HashMap<String, Object> getAttributes() { // return new HashMap<String, Object>(mAttributes); // } // // public void setAttributes(HashMap<String, Object> attributes) { // mAttributes = attributes; // attributesCheck(); // } // // public Object setAttribute(String key, Object attribute) { // return mAttributes.put(key, attribute); // } // // public Object attributeForKey(String key) { // return mAttributes.get(key); // } // // // JSON // public JSONObject toJSON() { // JSONObject json = new JSONObject(); // try { // if(mAttributes != null) { // for(String key : mAttributes.keySet()) { // if(mAttributes.get(key) instanceof Date) { // json.put(key, LiquidTools.dateToString((Date) mAttributes.get(key))); // } else { // json.put(key, mAttributes.get(key)); // } // } // } // json.put("unique_id", mIdentifier); // json.put("identified", mIdentified); // return json; // } catch (JSONException e) { // LQLog.error("LQUser toJSON: " + e.getMessage()); // } // return null; // } // // // // public static LQModel fromJSON(JSONObject jsonObject) { // try { // String unique_id = jsonObject.getString("unique_id"); // boolean identified = jsonObject.getBoolean("identified"); // HashMap<String, Object> attrs = attributesFromJSON(jsonObject, RESERVED_KEYS); // return new LQUser(unique_id, attrs, identified); // } catch (JSONException e) { // LQLog.infoVerbose("New user, identifying now..."); // return new LQUser(LQModel.newIdentifier(), false); // } // } // // protected void attributesCheck() { // if(mAttributes == null) { // mAttributes = new HashMap<String, Object>(); // } // } // // @Override // public void save(Context context, String path) { // super.save(context, path + ".user"); // } // // public static LQUser load(Context context, String path) { // return (LQUser) fromJSON(retriveFromFile(context, path)); // } // // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.lang.reflect.Field; import java.util.HashMap; import io.lqd.sdk.model.LQUser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull;
lqd.resetUser(); assertNotEquals("new_id", lqd.getUserIdentifier()); //resets the user id } @Test public void testResetUserAnonymous() { String id = lqd.getUserIdentifier(); lqd.resetUser(); assertEquals(id, lqd.getUserIdentifier()); } @Test public void testnewSessionAfterReset() throws NoSuchFieldException, IllegalAccessException, InterruptedException { Field f = Liquid.class.getDeclaredField("mCurrentSession"); f.setAccessible(true); lqd.softReset(); assertNotNull(f.get(lqd)); } // public void setUserAttributes(final Map<String, Object> attributes) @Test public void testSetAttributes() throws NoSuchFieldException, IllegalAccessException, InterruptedException { HashMap<String, Object> attrs = new HashMap<>(); attrs.put("key", 1); attrs.put("key_2", "value"); lqd.setUserAttributes(attrs); Field f = Liquid.class.getDeclaredField("mCurrentUser"); f.setAccessible(true);
// Path: liquid/src/main/java/io/lqd/sdk/model/LQUser.java // public class LQUser extends LQModel { // // private static final long serialVersionUID = 1582937331182018907L; // private static final String[] RESERVED_KEYS = {"unique_id", "identified"}; // // private String mIdentifier; // private boolean mIdentified; // private HashMap<String, Object> mAttributes = new HashMap<String, Object>(); // // public LQUser(String identifier) { // this(identifier, new HashMap<String,Object>()); // } // // public LQUser(String identifier, boolean identified) { // this(identifier, new HashMap<String,Object>(), identified); // } // // public LQUser(String identifier, HashMap<String, Object> attributes) { // this(identifier, attributes, true); // } // // public LQUser(String identifier, HashMap<String, Object> attributes, boolean identified) { // mIdentifier = identifier; // mAttributes = attributes; // this.setIdentified(identified); // attributesCheck(); // // } // // // Attributes // public String getIdentifier() { // return mIdentifier; // } // // public String setIdentifierForPrefs(String identifier){ // mIdentifier = identifier; // return mIdentifier; // } // // public boolean isIdentified() { // return mIdentified; // } // // public void setIdentified(boolean mAutoIdentified) { // this.mIdentified = mAutoIdentified; // } // // @Override // public boolean equals(Object o) { // return (o instanceof LQUser) && ( this.toJSON().toString().equals(((LQUser) o).toJSON().toString())); // } // // public void clearCustomAttributes() { // setAttributes(new HashMap<String, Object>()); // } // // public HashMap<String, Object> getAttributes() { // return new HashMap<String, Object>(mAttributes); // } // // public void setAttributes(HashMap<String, Object> attributes) { // mAttributes = attributes; // attributesCheck(); // } // // public Object setAttribute(String key, Object attribute) { // return mAttributes.put(key, attribute); // } // // public Object attributeForKey(String key) { // return mAttributes.get(key); // } // // // JSON // public JSONObject toJSON() { // JSONObject json = new JSONObject(); // try { // if(mAttributes != null) { // for(String key : mAttributes.keySet()) { // if(mAttributes.get(key) instanceof Date) { // json.put(key, LiquidTools.dateToString((Date) mAttributes.get(key))); // } else { // json.put(key, mAttributes.get(key)); // } // } // } // json.put("unique_id", mIdentifier); // json.put("identified", mIdentified); // return json; // } catch (JSONException e) { // LQLog.error("LQUser toJSON: " + e.getMessage()); // } // return null; // } // // // // public static LQModel fromJSON(JSONObject jsonObject) { // try { // String unique_id = jsonObject.getString("unique_id"); // boolean identified = jsonObject.getBoolean("identified"); // HashMap<String, Object> attrs = attributesFromJSON(jsonObject, RESERVED_KEYS); // return new LQUser(unique_id, attrs, identified); // } catch (JSONException e) { // LQLog.infoVerbose("New user, identifying now..."); // return new LQUser(LQModel.newIdentifier(), false); // } // } // // protected void attributesCheck() { // if(mAttributes == null) { // mAttributes = new HashMap<String, Object>(); // } // } // // @Override // public void save(Context context, String path) { // super.save(context, path + ".user"); // } // // public static LQUser load(Context context, String path) { // return (LQUser) fromJSON(retriveFromFile(context, path)); // } // // } // Path: liquid/src/test/java/io/lqd/sdk/LiquidTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.lang.reflect.Field; import java.util.HashMap; import io.lqd.sdk.model.LQUser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; lqd.resetUser(); assertNotEquals("new_id", lqd.getUserIdentifier()); //resets the user id } @Test public void testResetUserAnonymous() { String id = lqd.getUserIdentifier(); lqd.resetUser(); assertEquals(id, lqd.getUserIdentifier()); } @Test public void testnewSessionAfterReset() throws NoSuchFieldException, IllegalAccessException, InterruptedException { Field f = Liquid.class.getDeclaredField("mCurrentSession"); f.setAccessible(true); lqd.softReset(); assertNotNull(f.get(lqd)); } // public void setUserAttributes(final Map<String, Object> attributes) @Test public void testSetAttributes() throws NoSuchFieldException, IllegalAccessException, InterruptedException { HashMap<String, Object> attrs = new HashMap<>(); attrs.put("key", 1); attrs.put("key_2", "value"); lqd.setUserAttributes(attrs); Field f = Liquid.class.getDeclaredField("mCurrentUser"); f.setAccessible(true);
LQUser user = ((LQUser) f.get(lqd));
lqd-io/liquid-sdk-android
liquid/src/main/java/io/lqd/sdk/model/LQTarget.java
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // }
import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import io.lqd.sdk.LQLog;
/** * Copyright 2014-present Liquid Data Intelligence S.A. * * 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 io.lqd.sdk.model; public class LQTarget implements Serializable { private static final long serialVersionUID = -8930972810546846549L; private String mId; public LQTarget(String id) { mId = id; } public LQTarget(JSONObject jsonObject){ try { mId = jsonObject.getString("id"); } catch (JSONException e) {
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // } // Path: liquid/src/main/java/io/lqd/sdk/model/LQTarget.java import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import io.lqd.sdk.LQLog; /** * Copyright 2014-present Liquid Data Intelligence S.A. * * 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 io.lqd.sdk.model; public class LQTarget implements Serializable { private static final long serialVersionUID = -8930972810546846549L; private String mId; public LQTarget(String id) { mId = id; } public LQTarget(JSONObject jsonObject){ try { mId = jsonObject.getString("id"); } catch (JSONException e) {
LQLog.error("Parsing LQTarget: " + e.getMessage());
lqd-io/liquid-sdk-android
liquid/src/main/java/io/lqd/sdk/model/InappMessageParser.java
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // }
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import io.lqd.sdk.LQLog;
package io.lqd.sdk.model; public class InappMessageParser { public static ArrayList<LQInAppMessage> parse(JSONArray array) { ArrayList<LQInAppMessage> list = new ArrayList<>(); int length = array.length(); for (int i = 0; i < length; ++i) { try { JSONObject inapp = array.getJSONObject(i); list.add(new LQInAppMessage(inapp)); } catch (JSONException e) {
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // } // Path: liquid/src/main/java/io/lqd/sdk/model/InappMessageParser.java import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import io.lqd.sdk.LQLog; package io.lqd.sdk.model; public class InappMessageParser { public static ArrayList<LQInAppMessage> parse(JSONArray array) { ArrayList<LQInAppMessage> list = new ArrayList<>(); int length = array.length(); for (int i = 0; i < length; ++i) { try { JSONObject inapp = array.getJSONObject(i); list.add(new LQInAppMessage(inapp)); } catch (JSONException e) {
LQLog.error("Error parsing inapp message " + array);
lqd-io/liquid-sdk-android
liquid/src/test/java/io/lqd/sdk/model/LQLogTest.java
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import io.lqd.sdk.LQLog; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail;
package io.lqd.sdk.model; @Config(manifest = "../AndroidManifest.xml") @RunWith(RobolectricTestRunner.class) public class LQLogTest { private int invalid_below = 0; private int invalid_above = 10; @Test public void testBelowinvalidLevelException() { try {
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // } // Path: liquid/src/test/java/io/lqd/sdk/model/LQLogTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import io.lqd.sdk.LQLog; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; package io.lqd.sdk.model; @Config(manifest = "../AndroidManifest.xml") @RunWith(RobolectricTestRunner.class) public class LQLogTest { private int invalid_below = 0; private int invalid_above = 10; @Test public void testBelowinvalidLevelException() { try {
LQLog.setLevel(invalid_below);
lqd-io/liquid-sdk-android
liquid/src/test/java/io/lqd/sdk/model/LQDataPointTest.java
// Path: liquid/src/test/java/io/lqd/sdk/factory/FactoryGirl.java // public class FactoryGirl { // // private static final SecureRandom random = new SecureRandom(); // // // public static LQNetworkRequest createRequest() { // return new LQNetworkRequest(randomString(), "GET", randomString()); // } // // public static LQEvent createEvent() { // return new LQEvent(randomString(), null); // } // // // public static LQDevice createDevice(Context c) { // return new LQDevice(c, Liquid.LIQUID_VERSION); // } // // public static LQDataPoint createDataPoint(Context c) { // return new LQDataPoint(createUser(), createDevice(c), createEvent(), new ArrayList<LQValue>()); // } // // public static LQEvent createEvent(HashMap<String, Object> attrs) { // return new LQEvent(randomString(), attrs); // } // // public static LQUser createUser() { // return new LQUser(randomString()); // } // // // private static String randomString() { // return new BigInteger(130, random).toString(32); // } // // }
import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import io.lqd.sdk.factory.FactoryGirl; import static org.junit.Assert.assertTrue;
package io.lqd.sdk.model; @Config(manifest = "../AndroidManifest.xml") @RunWith(RobolectricTestRunner.class) public class LQDataPointTest { private JSONObject json; @Before public void before() {
// Path: liquid/src/test/java/io/lqd/sdk/factory/FactoryGirl.java // public class FactoryGirl { // // private static final SecureRandom random = new SecureRandom(); // // // public static LQNetworkRequest createRequest() { // return new LQNetworkRequest(randomString(), "GET", randomString()); // } // // public static LQEvent createEvent() { // return new LQEvent(randomString(), null); // } // // // public static LQDevice createDevice(Context c) { // return new LQDevice(c, Liquid.LIQUID_VERSION); // } // // public static LQDataPoint createDataPoint(Context c) { // return new LQDataPoint(createUser(), createDevice(c), createEvent(), new ArrayList<LQValue>()); // } // // public static LQEvent createEvent(HashMap<String, Object> attrs) { // return new LQEvent(randomString(), attrs); // } // // public static LQUser createUser() { // return new LQUser(randomString()); // } // // // private static String randomString() { // return new BigInteger(130, random).toString(32); // } // // } // Path: liquid/src/test/java/io/lqd/sdk/model/LQDataPointTest.java import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import io.lqd.sdk.factory.FactoryGirl; import static org.junit.Assert.assertTrue; package io.lqd.sdk.model; @Config(manifest = "../AndroidManifest.xml") @RunWith(RobolectricTestRunner.class) public class LQDataPointTest { private JSONObject json; @Before public void before() {
json = FactoryGirl.createDataPoint(Robolectric.application).toJSON();
lqd-io/liquid-sdk-android
liquid/src/test/java/io/lqd/sdk/model/LQEventTest.java
// Path: liquid/src/test/java/io/lqd/sdk/factory/FactoryGirl.java // public class FactoryGirl { // // private static final SecureRandom random = new SecureRandom(); // // // public static LQNetworkRequest createRequest() { // return new LQNetworkRequest(randomString(), "GET", randomString()); // } // // public static LQEvent createEvent() { // return new LQEvent(randomString(), null); // } // // // public static LQDevice createDevice(Context c) { // return new LQDevice(c, Liquid.LIQUID_VERSION); // } // // public static LQDataPoint createDataPoint(Context c) { // return new LQDataPoint(createUser(), createDevice(c), createEvent(), new ArrayList<LQValue>()); // } // // public static LQEvent createEvent(HashMap<String, Object> attrs) { // return new LQEvent(randomString(), attrs); // } // // public static LQUser createUser() { // return new LQUser(randomString()); // } // // // private static String randomString() { // return new BigInteger(130, random).toString(32); // } // // }
import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import io.lqd.sdk.LiquidTools; import io.lqd.sdk.factory.FactoryGirl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue;
package io.lqd.sdk.model; @Config(manifest = "../AndroidManifest.xml") @RunWith(RobolectricTestRunner.class) public class LQEventTest { private LQEvent event; private JSONObject json; @Test public void testJSONCreationWithoutAttributes() {
// Path: liquid/src/test/java/io/lqd/sdk/factory/FactoryGirl.java // public class FactoryGirl { // // private static final SecureRandom random = new SecureRandom(); // // // public static LQNetworkRequest createRequest() { // return new LQNetworkRequest(randomString(), "GET", randomString()); // } // // public static LQEvent createEvent() { // return new LQEvent(randomString(), null); // } // // // public static LQDevice createDevice(Context c) { // return new LQDevice(c, Liquid.LIQUID_VERSION); // } // // public static LQDataPoint createDataPoint(Context c) { // return new LQDataPoint(createUser(), createDevice(c), createEvent(), new ArrayList<LQValue>()); // } // // public static LQEvent createEvent(HashMap<String, Object> attrs) { // return new LQEvent(randomString(), attrs); // } // // public static LQUser createUser() { // return new LQUser(randomString()); // } // // // private static String randomString() { // return new BigInteger(130, random).toString(32); // } // // } // Path: liquid/src/test/java/io/lqd/sdk/model/LQEventTest.java import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import io.lqd.sdk.LiquidTools; import io.lqd.sdk.factory.FactoryGirl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; package io.lqd.sdk.model; @Config(manifest = "../AndroidManifest.xml") @RunWith(RobolectricTestRunner.class) public class LQEventTest { private LQEvent event; private JSONObject json; @Test public void testJSONCreationWithoutAttributes() {
event = FactoryGirl.createEvent();
lqd-io/liquid-sdk-android
liquid/src/main/java/io/lqd/sdk/model/LQLiquidPackage.java
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // }
import io.lqd.sdk.LQLog; import android.content.Context; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList;
/** * Copyright 2014-present Liquid Data Intelligence S.A. * * 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 io.lqd.sdk.model; public class LQLiquidPackage implements Serializable{ private static final long serialVersionUID = 2252438865270376L; private static final String LIQUID_PACKAGE_FILENAME = "LiquidPackage"; private ArrayList<LQValue> mValues = new ArrayList<LQValue>(); public LQLiquidPackage() { } public LQLiquidPackage(JSONObject jsonObject) { try { JSONArray valuesJsonArray = jsonObject.getJSONArray("values"); for(int index = 0; index < valuesJsonArray.length(); index ++){ JSONObject valueJson = valuesJsonArray.getJSONObject(index); LQValue v = new LQValue(valueJson); mValues.add(v); } } catch (JSONException e) {
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // } // Path: liquid/src/main/java/io/lqd/sdk/model/LQLiquidPackage.java import io.lqd.sdk.LQLog; import android.content.Context; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; /** * Copyright 2014-present Liquid Data Intelligence S.A. * * 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 io.lqd.sdk.model; public class LQLiquidPackage implements Serializable{ private static final long serialVersionUID = 2252438865270376L; private static final String LIQUID_PACKAGE_FILENAME = "LiquidPackage"; private ArrayList<LQValue> mValues = new ArrayList<LQValue>(); public LQLiquidPackage() { } public LQLiquidPackage(JSONObject jsonObject) { try { JSONArray valuesJsonArray = jsonObject.getJSONArray("values"); for(int index = 0; index < valuesJsonArray.length(); index ++){ JSONObject valueJson = valuesJsonArray.getJSONObject(index); LQValue v = new LQValue(valueJson); mValues.add(v); } } catch (JSONException e) {
LQLog.error("Parsing LQLiquidPackage: " + e.getMessage());
lqd-io/liquid-sdk-android
liquid/src/main/java/io/lqd/sdk/model/LQUser.java
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // }
import android.content.Context; import org.json.JSONException; import org.json.JSONObject; import java.util.Date; import java.util.HashMap; import io.lqd.sdk.LQLog; import io.lqd.sdk.LiquidTools;
public void setAttributes(HashMap<String, Object> attributes) { mAttributes = attributes; attributesCheck(); } public Object setAttribute(String key, Object attribute) { return mAttributes.put(key, attribute); } public Object attributeForKey(String key) { return mAttributes.get(key); } // JSON public JSONObject toJSON() { JSONObject json = new JSONObject(); try { if(mAttributes != null) { for(String key : mAttributes.keySet()) { if(mAttributes.get(key) instanceof Date) { json.put(key, LiquidTools.dateToString((Date) mAttributes.get(key))); } else { json.put(key, mAttributes.get(key)); } } } json.put("unique_id", mIdentifier); json.put("identified", mIdentified); return json; } catch (JSONException e) {
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // } // Path: liquid/src/main/java/io/lqd/sdk/model/LQUser.java import android.content.Context; import org.json.JSONException; import org.json.JSONObject; import java.util.Date; import java.util.HashMap; import io.lqd.sdk.LQLog; import io.lqd.sdk.LiquidTools; public void setAttributes(HashMap<String, Object> attributes) { mAttributes = attributes; attributesCheck(); } public Object setAttribute(String key, Object attribute) { return mAttributes.put(key, attribute); } public Object attributeForKey(String key) { return mAttributes.get(key); } // JSON public JSONObject toJSON() { JSONObject json = new JSONObject(); try { if(mAttributes != null) { for(String key : mAttributes.keySet()) { if(mAttributes.get(key) instanceof Date) { json.put(key, LiquidTools.dateToString((Date) mAttributes.get(key))); } else { json.put(key, mAttributes.get(key)); } } } json.put("unique_id", mIdentifier); json.put("identified", mIdentified); return json; } catch (JSONException e) {
LQLog.error("LQUser toJSON: " + e.getMessage());
lqd-io/liquid-sdk-android
liquid/src/test/java/io/lqd/sdk/model/LQUserTest.java
// Path: liquid/src/test/java/io/lqd/sdk/factory/FactoryGirl.java // public class FactoryGirl { // // private static final SecureRandom random = new SecureRandom(); // // // public static LQNetworkRequest createRequest() { // return new LQNetworkRequest(randomString(), "GET", randomString()); // } // // public static LQEvent createEvent() { // return new LQEvent(randomString(), null); // } // // // public static LQDevice createDevice(Context c) { // return new LQDevice(c, Liquid.LIQUID_VERSION); // } // // public static LQDataPoint createDataPoint(Context c) { // return new LQDataPoint(createUser(), createDevice(c), createEvent(), new ArrayList<LQValue>()); // } // // public static LQEvent createEvent(HashMap<String, Object> attrs) { // return new LQEvent(randomString(), attrs); // } // // public static LQUser createUser() { // return new LQUser(randomString()); // } // // // private static String randomString() { // return new BigInteger(130, random).toString(32); // } // // }
import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.HashMap; import io.lqd.sdk.factory.FactoryGirl; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue;
package io.lqd.sdk.model; @Config(manifest = "../AndroidManifest.xml") @RunWith(RobolectricTestRunner.class) public class LQUserTest { private LQUser user; private HashMap<String, Object> attrs; @Before public void setUp() {
// Path: liquid/src/test/java/io/lqd/sdk/factory/FactoryGirl.java // public class FactoryGirl { // // private static final SecureRandom random = new SecureRandom(); // // // public static LQNetworkRequest createRequest() { // return new LQNetworkRequest(randomString(), "GET", randomString()); // } // // public static LQEvent createEvent() { // return new LQEvent(randomString(), null); // } // // // public static LQDevice createDevice(Context c) { // return new LQDevice(c, Liquid.LIQUID_VERSION); // } // // public static LQDataPoint createDataPoint(Context c) { // return new LQDataPoint(createUser(), createDevice(c), createEvent(), new ArrayList<LQValue>()); // } // // public static LQEvent createEvent(HashMap<String, Object> attrs) { // return new LQEvent(randomString(), attrs); // } // // public static LQUser createUser() { // return new LQUser(randomString()); // } // // // private static String randomString() { // return new BigInteger(130, random).toString(32); // } // // } // Path: liquid/src/test/java/io/lqd/sdk/model/LQUserTest.java import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.HashMap; import io.lqd.sdk.factory.FactoryGirl; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; package io.lqd.sdk.model; @Config(manifest = "../AndroidManifest.xml") @RunWith(RobolectricTestRunner.class) public class LQUserTest { private LQUser user; private HashMap<String, Object> attrs; @Before public void setUp() {
user = FactoryGirl.createUser();
lqd-io/liquid-sdk-android
liquid/src/test/java/io/lqd/sdk/model/LQDeviceTest.java
// Path: liquid/src/test/java/io/lqd/sdk/factory/FactoryGirl.java // public class FactoryGirl { // // private static final SecureRandom random = new SecureRandom(); // // // public static LQNetworkRequest createRequest() { // return new LQNetworkRequest(randomString(), "GET", randomString()); // } // // public static LQEvent createEvent() { // return new LQEvent(randomString(), null); // } // // // public static LQDevice createDevice(Context c) { // return new LQDevice(c, Liquid.LIQUID_VERSION); // } // // public static LQDataPoint createDataPoint(Context c) { // return new LQDataPoint(createUser(), createDevice(c), createEvent(), new ArrayList<LQValue>()); // } // // public static LQEvent createEvent(HashMap<String, Object> attrs) { // return new LQEvent(randomString(), attrs); // } // // public static LQUser createUser() { // return new LQUser(randomString()); // } // // // private static String randomString() { // return new BigInteger(130, random).toString(32); // } // // }
import android.location.Location; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import io.lqd.sdk.factory.FactoryGirl; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
package io.lqd.sdk.model; @Config(manifest = "../AndroidManifest.xml") @RunWith(RobolectricTestRunner.class) public class LQDeviceTest { private LQDevice device; private JSONObject json; @Before public void before() {
// Path: liquid/src/test/java/io/lqd/sdk/factory/FactoryGirl.java // public class FactoryGirl { // // private static final SecureRandom random = new SecureRandom(); // // // public static LQNetworkRequest createRequest() { // return new LQNetworkRequest(randomString(), "GET", randomString()); // } // // public static LQEvent createEvent() { // return new LQEvent(randomString(), null); // } // // // public static LQDevice createDevice(Context c) { // return new LQDevice(c, Liquid.LIQUID_VERSION); // } // // public static LQDataPoint createDataPoint(Context c) { // return new LQDataPoint(createUser(), createDevice(c), createEvent(), new ArrayList<LQValue>()); // } // // public static LQEvent createEvent(HashMap<String, Object> attrs) { // return new LQEvent(randomString(), attrs); // } // // public static LQUser createUser() { // return new LQUser(randomString()); // } // // // private static String randomString() { // return new BigInteger(130, random).toString(32); // } // // } // Path: liquid/src/test/java/io/lqd/sdk/model/LQDeviceTest.java import android.location.Location; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import io.lqd.sdk.factory.FactoryGirl; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; package io.lqd.sdk.model; @Config(manifest = "../AndroidManifest.xml") @RunWith(RobolectricTestRunner.class) public class LQDeviceTest { private LQDevice device; private JSONObject json; @Before public void before() {
device = FactoryGirl.createDevice(Robolectric.application);
lqd-io/liquid-sdk-android
liquid/src/main/java/io/lqd/sdk/model/LQModel.java
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // }
import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import io.lqd.sdk.LQLog; import io.lqd.sdk.LiquidTools; import android.content.Context; import android.content.SharedPreferences; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator;
(attribute instanceof Date)); if(!isValid) { LiquidTools.exceptionOrLog(raiseException, "Value (" + attribute + ") with unsupported type. Supported: (String, Number, Boolean, Date)"); } return isValid; } public static HashMap<String, Object> sanitizeAttributes(Map<String, Object> attributes, boolean raiseException) { if (attributes == null) { return null; } HashMap<String, Object> attrs = new HashMap<String, Object>(); for (String key : attributes.keySet()) { if (LQModel.validKey(key, raiseException) && LQModel.validValue(attributes.get(key), raiseException)) { attrs.put(key, attributes.get(key)); } } return attrs; } public void save(Context context, String path) { String serializedObject = toJSON().toString(); SharedPreferences preferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor prefsEditor = preferences.edit(); String[] split = path.split("\\."); prefsEditor.putString(split[1], serializedObject);
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // } // Path: liquid/src/main/java/io/lqd/sdk/model/LQModel.java import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import io.lqd.sdk.LQLog; import io.lqd.sdk.LiquidTools; import android.content.Context; import android.content.SharedPreferences; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; (attribute instanceof Date)); if(!isValid) { LiquidTools.exceptionOrLog(raiseException, "Value (" + attribute + ") with unsupported type. Supported: (String, Number, Boolean, Date)"); } return isValid; } public static HashMap<String, Object> sanitizeAttributes(Map<String, Object> attributes, boolean raiseException) { if (attributes == null) { return null; } HashMap<String, Object> attrs = new HashMap<String, Object>(); for (String key : attributes.keySet()) { if (LQModel.validKey(key, raiseException) && LQModel.validValue(attributes.get(key), raiseException)) { attrs.put(key, attributes.get(key)); } } return attrs; } public void save(Context context, String path) { String serializedObject = toJSON().toString(); SharedPreferences preferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor prefsEditor = preferences.edit(); String[] split = path.split("\\."); prefsEditor.putString(split[1], serializedObject);
LQLog.infoVerbose("Saving " + split[1] + " to shared prefs");
lqd-io/liquid-sdk-android
liquid/src/main/java/io/lqd/sdk/model/LQEvent.java
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // }
import org.json.JSONException; import org.json.JSONObject; import java.util.Date; import java.util.HashMap; import io.lqd.sdk.LQLog; import io.lqd.sdk.LiquidTools;
public void setName(String name) { if ((name == null) || (name.length() == 0)) { mName = UNNAMED_EVENT; } else { mName = name; } } public String getName() { return mName; } // JSON public JSONObject toJSON() { JSONObject json = new JSONObject(); try { if(mAttributes != null) { for(String key : mAttributes.keySet()){ if(mAttributes.get(key) instanceof Date) { json.put(key, LiquidTools.dateToString((Date) mAttributes.get(key))); } else { json.put(key, mAttributes.get(key)); } } } json.put("name", mName); json.put("date",LiquidTools.dateToString(mDate)); return json; } catch (JSONException e) {
// Path: liquid/src/main/java/io/lqd/sdk/LQLog.java // public class LQLog { // // private static int LOG_LEVEL = 2; // // public static final int PATHS = 7; // public static final int HTTP = 6; // public static final int DATA = 5; // public static final int INFO_VERBOSE = 4; // public static final int INFO = 3; // public static final int WARNING = 2; // public static final int ERROR = 1; // // /** // * Changes the current Log level (Debugging proposes) // * @param level LogLevel // */ // public static void setLevel(int level) { // if( level < 1 || level > 7) // throw new IllegalArgumentException("Log levels are between 1 and 7"); // LOG_LEVEL = level; // } // // /** // * Gets the current log level // * @return the log level // */ // public static int getLevel() { // return LOG_LEVEL; // } // // public static void paths(String message) { // if(LOG_LEVEL >= PATHS) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void http(String message) { // if(LOG_LEVEL >= HTTP) { // Log.d(Liquid.TAG_LIQUID, message); // } // } // // public static void data(String message) { // if(LOG_LEVEL >= DATA) { // Log.v(Liquid.TAG_LIQUID, message); // } // } // // public static void infoVerbose(String message) { // if(LOG_LEVEL >= INFO_VERBOSE) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void warning(String message) { // if(LOG_LEVEL >= WARNING) { // Log.w(Liquid.TAG_LIQUID, message); // } // } // // public static void info(String message) { // if(LOG_LEVEL >= INFO) { // Log.i(Liquid.TAG_LIQUID, message); // } // } // // public static void error(String message) { // if(LOG_LEVEL >= ERROR) { // Log.e(Liquid.TAG_LIQUID, message); // } // } // // } // Path: liquid/src/main/java/io/lqd/sdk/model/LQEvent.java import org.json.JSONException; import org.json.JSONObject; import java.util.Date; import java.util.HashMap; import io.lqd.sdk.LQLog; import io.lqd.sdk.LiquidTools; public void setName(String name) { if ((name == null) || (name.length() == 0)) { mName = UNNAMED_EVENT; } else { mName = name; } } public String getName() { return mName; } // JSON public JSONObject toJSON() { JSONObject json = new JSONObject(); try { if(mAttributes != null) { for(String key : mAttributes.keySet()){ if(mAttributes.get(key) instanceof Date) { json.put(key, LiquidTools.dateToString((Date) mAttributes.get(key))); } else { json.put(key, mAttributes.get(key)); } } } json.put("name", mName); json.put("date",LiquidTools.dateToString(mDate)); return json; } catch (JSONException e) {
LQLog.error("LQEvent toJSON: " + e.getMessage());
lqd-io/liquid-sdk-android
liquid/src/main/java/io/lqd/sdk/visual/ViewHelper.java
// Path: liquid/src/main/java/io/lqd/sdk/visual/AnimatorProxy.java // public static final boolean NEEDS_PROXY = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB; // // Path: liquid/src/main/java/io/lqd/sdk/visual/AnimatorProxy.java // public static AnimatorProxy wrap(View view) { // AnimatorProxy proxy = PROXIES.get(view); // // This checks if the proxy already exists and whether it still is the animation of the given view // if (proxy == null || proxy != view.getAnimation()) { // proxy = new AnimatorProxy(view); // PROXIES.put(view, proxy); // } // return proxy; // }
import android.view.View; import static io.lqd.sdk.visual.AnimatorProxy.NEEDS_PROXY; import static io.lqd.sdk.visual.AnimatorProxy.wrap;
package io.lqd.sdk.visual; public final class ViewHelper { private ViewHelper() {} public static float getAlpha(View view) {
// Path: liquid/src/main/java/io/lqd/sdk/visual/AnimatorProxy.java // public static final boolean NEEDS_PROXY = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB; // // Path: liquid/src/main/java/io/lqd/sdk/visual/AnimatorProxy.java // public static AnimatorProxy wrap(View view) { // AnimatorProxy proxy = PROXIES.get(view); // // This checks if the proxy already exists and whether it still is the animation of the given view // if (proxy == null || proxy != view.getAnimation()) { // proxy = new AnimatorProxy(view); // PROXIES.put(view, proxy); // } // return proxy; // } // Path: liquid/src/main/java/io/lqd/sdk/visual/ViewHelper.java import android.view.View; import static io.lqd.sdk.visual.AnimatorProxy.NEEDS_PROXY; import static io.lqd.sdk.visual.AnimatorProxy.wrap; package io.lqd.sdk.visual; public final class ViewHelper { private ViewHelper() {} public static float getAlpha(View view) {
return NEEDS_PROXY ? wrap(view).getAlpha() : Honeycomb.getAlpha(view);
lqd-io/liquid-sdk-android
liquid/src/main/java/io/lqd/sdk/visual/ViewHelper.java
// Path: liquid/src/main/java/io/lqd/sdk/visual/AnimatorProxy.java // public static final boolean NEEDS_PROXY = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB; // // Path: liquid/src/main/java/io/lqd/sdk/visual/AnimatorProxy.java // public static AnimatorProxy wrap(View view) { // AnimatorProxy proxy = PROXIES.get(view); // // This checks if the proxy already exists and whether it still is the animation of the given view // if (proxy == null || proxy != view.getAnimation()) { // proxy = new AnimatorProxy(view); // PROXIES.put(view, proxy); // } // return proxy; // }
import android.view.View; import static io.lqd.sdk.visual.AnimatorProxy.NEEDS_PROXY; import static io.lqd.sdk.visual.AnimatorProxy.wrap;
package io.lqd.sdk.visual; public final class ViewHelper { private ViewHelper() {} public static float getAlpha(View view) {
// Path: liquid/src/main/java/io/lqd/sdk/visual/AnimatorProxy.java // public static final boolean NEEDS_PROXY = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB; // // Path: liquid/src/main/java/io/lqd/sdk/visual/AnimatorProxy.java // public static AnimatorProxy wrap(View view) { // AnimatorProxy proxy = PROXIES.get(view); // // This checks if the proxy already exists and whether it still is the animation of the given view // if (proxy == null || proxy != view.getAnimation()) { // proxy = new AnimatorProxy(view); // PROXIES.put(view, proxy); // } // return proxy; // } // Path: liquid/src/main/java/io/lqd/sdk/visual/ViewHelper.java import android.view.View; import static io.lqd.sdk.visual.AnimatorProxy.NEEDS_PROXY; import static io.lqd.sdk.visual.AnimatorProxy.wrap; package io.lqd.sdk.visual; public final class ViewHelper { private ViewHelper() {} public static float getAlpha(View view) {
return NEEDS_PROXY ? wrap(view).getAlpha() : Honeycomb.getAlpha(view);
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgDatabase.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // }
import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import java.util.HashMap; import java.util.Map;
package com.matburt.mobileorg.orgdata; public class OrgDatabase extends SQLiteOpenHelper { private static final String DATABASE_NAME = "MobileOrg.db"; private static final int DATABASE_VERSION = 5; private static OrgDatabase mInstance = null; private SQLiteStatement orgdataInsertStatement; private SQLiteStatement addPayloadStatement; private SQLiteStatement addTimestampsStatement; private OrgDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); orgdataInsertStatement = getWritableDatabase() .compileStatement("INSERT INTO " + Tables.ORGDATA+ " ("
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgDatabase.java import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import java.util.HashMap; import java.util.Map; package com.matburt.mobileorg.orgdata; public class OrgDatabase extends SQLiteOpenHelper { private static final String DATABASE_NAME = "MobileOrg.db"; private static final int DATABASE_VERSION = 5; private static OrgDatabase mInstance = null; private SQLiteStatement orgdataInsertStatement; private SQLiteStatement addPayloadStatement; private SQLiteStatement addTimestampsStatement; private OrgDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); orgdataInsertStatement = getWritableDatabase() .compileStatement("INSERT INTO " + Tables.ORGDATA+ " ("
+ OrgData.NAME + ", "
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/util/PreferenceUtils.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/MobileOrgApplication.java // public class MobileOrgApplication extends Application { // // private static MobileOrgApplication instance; // // public static Context getContext() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // instance = this; // // OrgDatabase.startDB(this); // startSynchronizer(); // OrgFileParser.startParser(this); // SyncService.startAlarm(this); // } // // public void startSynchronizer() { // String syncSource = // PreferenceManager // .getDefaultSharedPreferences(getApplicationContext()) // .getString("syncSource", ""); // Context c = getApplicationContext(); // // if (syncSource.equals("webdav")) // Synchronizer.setInstance(new WebDAVSynchronizer(c)); // else if (syncSource.equals("sdcard")) // Synchronizer.setInstance(new SDCardSynchronizer(c)); // else if (syncSource.equals("dropbox")) // Synchronizer.setInstance(new DropboxSynchronizer(c)); // else if (syncSource.equals("ubuntu")) // Synchronizer.setInstance(new UbuntuOneSynchronizer(c)); // else if (syncSource.equals("scp")) // Synchronizer.setInstance(new SSHSynchronizer(c)); // else // Synchronizer.setInstance(new NullSynchronizer(c)); // } // }
import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.preference.PreferenceManager; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.MobileOrgApplication; import java.util.ArrayList; import java.util.HashSet;
package com.matburt.mobileorg.util; public class PreferenceUtils { private static final int DEFAULT_FONTSIZE = 14; public static boolean getCombineBlockAgendas() {
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/MobileOrgApplication.java // public class MobileOrgApplication extends Application { // // private static MobileOrgApplication instance; // // public static Context getContext() { // return instance; // } // // @Override // public void onCreate() { // super.onCreate(); // instance = this; // // OrgDatabase.startDB(this); // startSynchronizer(); // OrgFileParser.startParser(this); // SyncService.startAlarm(this); // } // // public void startSynchronizer() { // String syncSource = // PreferenceManager // .getDefaultSharedPreferences(getApplicationContext()) // .getString("syncSource", ""); // Context c = getApplicationContext(); // // if (syncSource.equals("webdav")) // Synchronizer.setInstance(new WebDAVSynchronizer(c)); // else if (syncSource.equals("sdcard")) // Synchronizer.setInstance(new SDCardSynchronizer(c)); // else if (syncSource.equals("dropbox")) // Synchronizer.setInstance(new DropboxSynchronizer(c)); // else if (syncSource.equals("ubuntu")) // Synchronizer.setInstance(new UbuntuOneSynchronizer(c)); // else if (syncSource.equals("scp")) // Synchronizer.setInstance(new SSHSynchronizer(c)); // else // Synchronizer.setInstance(new NullSynchronizer(c)); // } // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/util/PreferenceUtils.java import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.preference.PreferenceManager; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.MobileOrgApplication; import java.util.ArrayList; import java.util.HashSet; package com.matburt.mobileorg.util; public class PreferenceUtils { private static final int DEFAULT_FONTSIZE = 14; public static boolean getCombineBlockAgendas() {
Context context = MobileOrgApplication.getContext();
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // }
import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List;
package com.matburt.mobileorg.orgdata; public class OrgProviderUtils { /** * * @param context * @return the list of nodes corresponding to a file */ public static List<OrgNode> getFileNodes(Context context){ return OrgProviderUtils.getOrgNodeChildren(-1, context.getContentResolver()); } public static ArrayList<String> getFilenames(ContentResolver resolver) { ArrayList<String> result = new ArrayList<String>();
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; package com.matburt.mobileorg.orgdata; public class OrgProviderUtils { /** * * @param context * @return the list of nodes corresponding to a file */ public static List<OrgNode> getFileNodes(Context context){ return OrgProviderUtils.getOrgNodeChildren(-1, context.getContentResolver()); } public static ArrayList<String> getFilenames(ContentResolver resolver) { ArrayList<String> result = new ArrayList<String>();
Cursor cursor = resolver.query(Files.CONTENT_URI, Files.DEFAULT_COLUMNS,
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // }
import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List;
Cursor cursor = resolver.query(Files.CONTENT_URI, Files.DEFAULT_COLUMNS, null, null, Files.DEFAULT_SORT); if(cursor == null) return result; cursor.moveToFirst(); while (!cursor.isAfterLast()) { OrgFile orgFile = new OrgFile(); try { orgFile.set(cursor); result.add(orgFile); } catch (OrgFileNotFoundException e) {} cursor.moveToNext(); } cursor.close(); return result; } public static String getNonNullString(Cursor cursor, int index){ String result = cursor.getString(index); return result!=null ? result : ""; } public static void addTodos(HashMap<String, Boolean> todos, ContentResolver resolver) { if(todos == null) return; for (String name : todos.keySet()) { ContentValues values = new ContentValues();
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; Cursor cursor = resolver.query(Files.CONTENT_URI, Files.DEFAULT_COLUMNS, null, null, Files.DEFAULT_SORT); if(cursor == null) return result; cursor.moveToFirst(); while (!cursor.isAfterLast()) { OrgFile orgFile = new OrgFile(); try { orgFile.set(cursor); result.add(orgFile); } catch (OrgFileNotFoundException e) {} cursor.moveToNext(); } cursor.close(); return result; } public static String getNonNullString(Cursor cursor, int index){ String result = cursor.getString(index); return result!=null ? result : ""; } public static void addTodos(HashMap<String, Boolean> todos, ContentResolver resolver) { if(todos == null) return; for (String name : todos.keySet()) { ContentValues values = new ContentValues();
values.put(Todos.NAME, name);
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // }
import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List;
public static void addTodos(HashMap<String, Boolean> todos, ContentResolver resolver) { if(todos == null) return; for (String name : todos.keySet()) { ContentValues values = new ContentValues(); values.put(Todos.NAME, name); values.put(Todos.GROUP, 0); if (todos.get(name)) values.put(Todos.ISDONE, 1); try{ resolver.insert(Todos.CONTENT_URI, values); } catch (Exception e){ e.printStackTrace(); } } } public static ArrayList<String> getTodos(ContentResolver resolver) { Cursor cursor = resolver.query(Todos.CONTENT_URI, new String[] { Todos.NAME }, null, null, Todos.ID); if(cursor==null) return new ArrayList<>(); ArrayList<String> todos = cursorToArrayList(cursor); return todos; } public static void setPriorities(ArrayList<String> priorities, ContentResolver resolver) {
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public static void addTodos(HashMap<String, Boolean> todos, ContentResolver resolver) { if(todos == null) return; for (String name : todos.keySet()) { ContentValues values = new ContentValues(); values.put(Todos.NAME, name); values.put(Todos.GROUP, 0); if (todos.get(name)) values.put(Todos.ISDONE, 1); try{ resolver.insert(Todos.CONTENT_URI, values); } catch (Exception e){ e.printStackTrace(); } } } public static ArrayList<String> getTodos(ContentResolver resolver) { Cursor cursor = resolver.query(Todos.CONTENT_URI, new String[] { Todos.NAME }, null, null, Todos.ID); if(cursor==null) return new ArrayList<>(); ArrayList<String> todos = cursorToArrayList(cursor); return todos; } public static void setPriorities(ArrayList<String> priorities, ContentResolver resolver) {
resolver.delete(Priorities.CONTENT_URI, null, null);
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // }
import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List;
public static ArrayList<String> getTodos(ContentResolver resolver) { Cursor cursor = resolver.query(Todos.CONTENT_URI, new String[] { Todos.NAME }, null, null, Todos.ID); if(cursor==null) return new ArrayList<>(); ArrayList<String> todos = cursorToArrayList(cursor); return todos; } public static void setPriorities(ArrayList<String> priorities, ContentResolver resolver) { resolver.delete(Priorities.CONTENT_URI, null, null); for (String priority : priorities) { ContentValues values = new ContentValues(); values.put(Priorities.NAME, priority); resolver.insert(Priorities.CONTENT_URI, values); } } public static ArrayList<String> getPriorities(ContentResolver resolver) { Cursor cursor = resolver.query(Priorities.CONTENT_URI, new String[] { Priorities.NAME }, null, null, Priorities.ID); ArrayList<String> priorities = cursorToArrayList(cursor); cursor.close(); return priorities; } public static void setTags(ArrayList<String> priorities, ContentResolver resolver) {
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public static ArrayList<String> getTodos(ContentResolver resolver) { Cursor cursor = resolver.query(Todos.CONTENT_URI, new String[] { Todos.NAME }, null, null, Todos.ID); if(cursor==null) return new ArrayList<>(); ArrayList<String> todos = cursorToArrayList(cursor); return todos; } public static void setPriorities(ArrayList<String> priorities, ContentResolver resolver) { resolver.delete(Priorities.CONTENT_URI, null, null); for (String priority : priorities) { ContentValues values = new ContentValues(); values.put(Priorities.NAME, priority); resolver.insert(Priorities.CONTENT_URI, values); } } public static ArrayList<String> getPriorities(ContentResolver resolver) { Cursor cursor = resolver.query(Priorities.CONTENT_URI, new String[] { Priorities.NAME }, null, null, Priorities.ID); ArrayList<String> priorities = cursorToArrayList(cursor); cursor.close(); return priorities; } public static void setTags(ArrayList<String> priorities, ContentResolver resolver) {
resolver.delete(Tags.CONTENT_URI, null, null);
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // }
import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List;
if(cursor == null) return list; cursor.moveToFirst(); while (!cursor.isAfterLast()) { list.add(cursor.getString(0)); cursor.moveToNext(); } return list; } public static ArrayList<OrgNode> getOrgNodePathFromTopLevel(long node_id, ContentResolver resolver) { ArrayList<OrgNode> nodes = new ArrayList<OrgNode>(); long currentId = node_id; while(currentId >= 0) { try { OrgNode node = new OrgNode(currentId, resolver); nodes.add(node); currentId = node.parentId; } catch (OrgNodeNotFoundException e) { throw new IllegalStateException("Couldn't build entire path to root from a given node"); } } Collections.reverse(nodes); return nodes; } public static void clearDB(ContentResolver resolver) {
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; if(cursor == null) return list; cursor.moveToFirst(); while (!cursor.isAfterLast()) { list.add(cursor.getString(0)); cursor.moveToNext(); } return list; } public static ArrayList<OrgNode> getOrgNodePathFromTopLevel(long node_id, ContentResolver resolver) { ArrayList<OrgNode> nodes = new ArrayList<OrgNode>(); long currentId = node_id; while(currentId >= 0) { try { OrgNode node = new OrgNode(currentId, resolver); nodes.add(node); currentId = node.parentId; } catch (OrgNodeNotFoundException e) { throw new IllegalStateException("Couldn't build entire path to root from a given node"); } } Collections.reverse(nodes); return nodes; } public static void clearDB(ContentResolver resolver) {
resolver.delete(OrgData.CONTENT_URI, null, null);
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // }
import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List;
while (!cursor.isAfterLast()) { list.add(cursor.getString(0)); cursor.moveToNext(); } return list; } public static ArrayList<OrgNode> getOrgNodePathFromTopLevel(long node_id, ContentResolver resolver) { ArrayList<OrgNode> nodes = new ArrayList<OrgNode>(); long currentId = node_id; while(currentId >= 0) { try { OrgNode node = new OrgNode(currentId, resolver); nodes.add(node); currentId = node.parentId; } catch (OrgNodeNotFoundException e) { throw new IllegalStateException("Couldn't build entire path to root from a given node"); } } Collections.reverse(nodes); return nodes; } public static void clearDB(ContentResolver resolver) { resolver.delete(OrgData.CONTENT_URI, null, null); resolver.delete(Files.CONTENT_URI, null, null);
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Files implements FilesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build(); // // public static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME, // COMMENT, NODE_ID }; // public static final String DEFAULT_SORT = NAME + " ASC"; // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // // public static String getFilename(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildFilenameUri(String filename) { // return CONTENT_URI.buildUpon().appendPath(filename) // .appendPath("filename").build(); // } // // public static Uri buildIdUri(Long fileId) { // return CONTENT_URI.buildUpon().appendPath(fileId.toString()).build(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class OrgData implements OrgDataColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build(); // // public static final Uri CONTENT_URI_TODOS = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // public static final String DEFAULT_SORT = ID + " ASC"; // public static final String NAME_SORT = NAME + " ASC"; // public static final String POSITION_SORT = POSITION + " ASC"; // public static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED, // PARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY}; // // public static String getId(Uri uri) { // return uri.getPathSegments().get(1); // } // // public static Uri buildIdUri(String id) { // return CONTENT_URI.buildUpon().appendPath(id).build(); // } // // public static Uri buildIdUri(Long id) { // return buildIdUri(id.toString()); // } // // public static Uri buildChildrenUri(String parentId) { // return CONTENT_URI.buildUpon().appendPath(parentId).appendPath("children").build(); // } // // public static Uri buildChildrenUri(long node_id) { // return buildChildrenUri(Long.toString(node_id)); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Priorities implements PrioritiesColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Tags implements TagsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build(); // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Todos implements TodosColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build(); // // public static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE}; // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; while (!cursor.isAfterLast()) { list.add(cursor.getString(0)); cursor.moveToNext(); } return list; } public static ArrayList<OrgNode> getOrgNodePathFromTopLevel(long node_id, ContentResolver resolver) { ArrayList<OrgNode> nodes = new ArrayList<OrgNode>(); long currentId = node_id; while(currentId >= 0) { try { OrgNode node = new OrgNode(currentId, resolver); nodes.add(node); currentId = node.parentId; } catch (OrgNodeNotFoundException e) { throw new IllegalStateException("Couldn't build entire path to root from a given node"); } } Collections.reverse(nodes); return nodes; } public static void clearDB(ContentResolver resolver) { resolver.delete(OrgData.CONTENT_URI, null, null); resolver.delete(Files.CONTENT_URI, null, null);
resolver.delete(Timestamps.CONTENT_URI, null, null);
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/gui/wizard/wizards/SDCardWizard.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/gui/wizard/FolderAdapter.java // public class FolderAdapter extends ArrayAdapter<String> { // private int currentChecked = -1; // private DirectoryBrowser<?> directory; // private Button doneButton; // // public FolderAdapter(Context context, int resource, ArrayList<String> list) { // super(context, resource, list); // } // // public void setDirectoryBrowser(DirectoryBrowser<?> d) { // directory = d; // } // // public String getCheckedDirectory() { // if (currentChecked == -1) // return ""; // // (Toast.makeText(context, directory.getAbsolutePath(currentChecked), // // Toast.LENGTH_LONG)).show(); // return directory.getAbsolutePath(currentChecked); // } // // public void setDoneButton(Button b) { // doneButton = b; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // View row = convertView; // TextView folder = null; // CheckBox check = null; // if (row == null) { // LayoutInflater inflater = LayoutInflater.from(getContext()); // row = inflater.inflate(R.layout.folder_adapter_row, parent, false); // folder = (TextView) row.findViewById(R.id.folder); // folder.setOnClickListener(new View.OnClickListener() { // // @Override // public void onClick(View folder) { // int position = (Integer) folder.getTag(); // // FolderAdapter.this.clear(); // directory.browseTo(position); // currentChecked = -1; // FolderAdapter.this.notifyDataSetChanged(); // doneButton.setEnabled(false); // } // }); // check = (CheckBox) row.findViewById(R.id.checkbox); // check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // // public void onCheckedChanged(CompoundButton buttonView, // boolean isChecked) { // // update last checked position // int position = (Integer) buttonView.getTag(); // if (isChecked) // currentChecked = position; // else if (currentChecked == position) // currentChecked = -1; // FolderAdapter.this.notifyDataSetChanged(); // if (isChecked) // doneButton.setEnabled(true); // } // }); // } // folder = (TextView) row.findViewById(R.id.folder); // folder.setText(directory.getDirectoryName(position)); // folder.setTag(Integer.valueOf(position)); // check = (CheckBox) row.findViewById(R.id.checkbox); // // disable the "Up one level" checkbox; otherwise make sure its enabled // if (position == 0 && !directory.isCurrentDirectoryRoot()) // check.setEnabled(false); // else // check.setEnabled(true); // check.setTag(Integer.valueOf(position)); // // set check state. only one can be checked // boolean status = (currentChecked == position) ? true : false; // check.setChecked(status); // return (row); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/gui/wizard/LocalDirectoryBrowser.java // public class LocalDirectoryBrowser extends DirectoryBrowser<File> { // // public LocalDirectoryBrowser(Context context) { // super(context); // // browseTo(File.separator); // } // // @Override // public boolean isCurrentDirectoryRoot() { // return currentDirectory.getParent() == null; // } // // @Override // public void browseTo(int position) { // File newdir = getDir(position); // browseTo(newdir.getAbsolutePath()); // } // // @Override // public void browseTo(String directory) { // currentDirectory = new File(directory); // directoryNames.clear(); // directoryListing.clear(); // if (currentDirectory.getParent() != null) { // directoryNames.add(upOneLevel); // directoryListing.add(currentDirectory.getParentFile()); // } // File[] tmpListing = currentDirectory.listFiles(); // // default list order doesn't seem to be alpha // Arrays.sort(tmpListing); // for (File dir : tmpListing) { // if (dir.isDirectory() && dir.canWrite()) { // directoryNames.add(dir.getName()); // directoryListing.add(dir); // } // } // } // }
import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import android.widget.ListView; import com.matburt.mobileorg.gui.wizard.FolderAdapter; import com.matburt.mobileorg.gui.wizard.LocalDirectoryBrowser; import com.matburt.mobileorg.R;
package com.matburt.mobileorg.gui.wizard.wizards; public class SDCardWizard extends AppCompatActivity { private FolderAdapter directoryAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.wizard_folder_pick_list);
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/gui/wizard/FolderAdapter.java // public class FolderAdapter extends ArrayAdapter<String> { // private int currentChecked = -1; // private DirectoryBrowser<?> directory; // private Button doneButton; // // public FolderAdapter(Context context, int resource, ArrayList<String> list) { // super(context, resource, list); // } // // public void setDirectoryBrowser(DirectoryBrowser<?> d) { // directory = d; // } // // public String getCheckedDirectory() { // if (currentChecked == -1) // return ""; // // (Toast.makeText(context, directory.getAbsolutePath(currentChecked), // // Toast.LENGTH_LONG)).show(); // return directory.getAbsolutePath(currentChecked); // } // // public void setDoneButton(Button b) { // doneButton = b; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // View row = convertView; // TextView folder = null; // CheckBox check = null; // if (row == null) { // LayoutInflater inflater = LayoutInflater.from(getContext()); // row = inflater.inflate(R.layout.folder_adapter_row, parent, false); // folder = (TextView) row.findViewById(R.id.folder); // folder.setOnClickListener(new View.OnClickListener() { // // @Override // public void onClick(View folder) { // int position = (Integer) folder.getTag(); // // FolderAdapter.this.clear(); // directory.browseTo(position); // currentChecked = -1; // FolderAdapter.this.notifyDataSetChanged(); // doneButton.setEnabled(false); // } // }); // check = (CheckBox) row.findViewById(R.id.checkbox); // check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // // public void onCheckedChanged(CompoundButton buttonView, // boolean isChecked) { // // update last checked position // int position = (Integer) buttonView.getTag(); // if (isChecked) // currentChecked = position; // else if (currentChecked == position) // currentChecked = -1; // FolderAdapter.this.notifyDataSetChanged(); // if (isChecked) // doneButton.setEnabled(true); // } // }); // } // folder = (TextView) row.findViewById(R.id.folder); // folder.setText(directory.getDirectoryName(position)); // folder.setTag(Integer.valueOf(position)); // check = (CheckBox) row.findViewById(R.id.checkbox); // // disable the "Up one level" checkbox; otherwise make sure its enabled // if (position == 0 && !directory.isCurrentDirectoryRoot()) // check.setEnabled(false); // else // check.setEnabled(true); // check.setTag(Integer.valueOf(position)); // // set check state. only one can be checked // boolean status = (currentChecked == position) ? true : false; // check.setChecked(status); // return (row); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/gui/wizard/LocalDirectoryBrowser.java // public class LocalDirectoryBrowser extends DirectoryBrowser<File> { // // public LocalDirectoryBrowser(Context context) { // super(context); // // browseTo(File.separator); // } // // @Override // public boolean isCurrentDirectoryRoot() { // return currentDirectory.getParent() == null; // } // // @Override // public void browseTo(int position) { // File newdir = getDir(position); // browseTo(newdir.getAbsolutePath()); // } // // @Override // public void browseTo(String directory) { // currentDirectory = new File(directory); // directoryNames.clear(); // directoryListing.clear(); // if (currentDirectory.getParent() != null) { // directoryNames.add(upOneLevel); // directoryListing.add(currentDirectory.getParentFile()); // } // File[] tmpListing = currentDirectory.listFiles(); // // default list order doesn't seem to be alpha // Arrays.sort(tmpListing); // for (File dir : tmpListing) { // if (dir.isDirectory() && dir.canWrite()) { // directoryNames.add(dir.getName()); // directoryListing.add(dir); // } // } // } // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/gui/wizard/wizards/SDCardWizard.java import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import android.widget.ListView; import com.matburt.mobileorg.gui.wizard.FolderAdapter; import com.matburt.mobileorg.gui.wizard.LocalDirectoryBrowser; import com.matburt.mobileorg.R; package com.matburt.mobileorg.gui.wizard.wizards; public class SDCardWizard extends AppCompatActivity { private FolderAdapter directoryAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.wizard_folder_pick_list);
LocalDirectoryBrowser directory = new LocalDirectoryBrowser(this);
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/gui/wizard/wizards/DropboxWizard.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/gui/wizard/FolderAdapter.java // public class FolderAdapter extends ArrayAdapter<String> { // private int currentChecked = -1; // private DirectoryBrowser<?> directory; // private Button doneButton; // // public FolderAdapter(Context context, int resource, ArrayList<String> list) { // super(context, resource, list); // } // // public void setDirectoryBrowser(DirectoryBrowser<?> d) { // directory = d; // } // // public String getCheckedDirectory() { // if (currentChecked == -1) // return ""; // // (Toast.makeText(context, directory.getAbsolutePath(currentChecked), // // Toast.LENGTH_LONG)).show(); // return directory.getAbsolutePath(currentChecked); // } // // public void setDoneButton(Button b) { // doneButton = b; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // View row = convertView; // TextView folder = null; // CheckBox check = null; // if (row == null) { // LayoutInflater inflater = LayoutInflater.from(getContext()); // row = inflater.inflate(R.layout.folder_adapter_row, parent, false); // folder = (TextView) row.findViewById(R.id.folder); // folder.setOnClickListener(new View.OnClickListener() { // // @Override // public void onClick(View folder) { // int position = (Integer) folder.getTag(); // // FolderAdapter.this.clear(); // directory.browseTo(position); // currentChecked = -1; // FolderAdapter.this.notifyDataSetChanged(); // doneButton.setEnabled(false); // } // }); // check = (CheckBox) row.findViewById(R.id.checkbox); // check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // // public void onCheckedChanged(CompoundButton buttonView, // boolean isChecked) { // // update last checked position // int position = (Integer) buttonView.getTag(); // if (isChecked) // currentChecked = position; // else if (currentChecked == position) // currentChecked = -1; // FolderAdapter.this.notifyDataSetChanged(); // if (isChecked) // doneButton.setEnabled(true); // } // }); // } // folder = (TextView) row.findViewById(R.id.folder); // folder.setText(directory.getDirectoryName(position)); // folder.setTag(Integer.valueOf(position)); // check = (CheckBox) row.findViewById(R.id.checkbox); // // disable the "Up one level" checkbox; otherwise make sure its enabled // if (position == 0 && !directory.isCurrentDirectoryRoot()) // check.setEnabled(false); // else // check.setEnabled(true); // check.setTag(Integer.valueOf(position)); // // set check state. only one can be checked // boolean status = (currentChecked == position) ? true : false; // check.setChecked(status); // return (row); // } // }
import android.os.Bundle; import android.os.StrictMode; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.dropbox.client2.DropboxAPI; import com.dropbox.client2.android.AndroidAuthSession; import com.dropbox.client2.session.AppKeyPair; import com.dropbox.client2.session.Session.AccessType; import com.matburt.mobileorg.gui.wizard.FolderAdapter; import com.matburt.mobileorg.R;
package com.matburt.mobileorg.gui.wizard.wizards; public class DropboxWizard extends AppCompatActivity { private TextView dropboxAccountInfo; private DropboxAPI<AndroidAuthSession> dropboxApi;
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/gui/wizard/FolderAdapter.java // public class FolderAdapter extends ArrayAdapter<String> { // private int currentChecked = -1; // private DirectoryBrowser<?> directory; // private Button doneButton; // // public FolderAdapter(Context context, int resource, ArrayList<String> list) { // super(context, resource, list); // } // // public void setDirectoryBrowser(DirectoryBrowser<?> d) { // directory = d; // } // // public String getCheckedDirectory() { // if (currentChecked == -1) // return ""; // // (Toast.makeText(context, directory.getAbsolutePath(currentChecked), // // Toast.LENGTH_LONG)).show(); // return directory.getAbsolutePath(currentChecked); // } // // public void setDoneButton(Button b) { // doneButton = b; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // View row = convertView; // TextView folder = null; // CheckBox check = null; // if (row == null) { // LayoutInflater inflater = LayoutInflater.from(getContext()); // row = inflater.inflate(R.layout.folder_adapter_row, parent, false); // folder = (TextView) row.findViewById(R.id.folder); // folder.setOnClickListener(new View.OnClickListener() { // // @Override // public void onClick(View folder) { // int position = (Integer) folder.getTag(); // // FolderAdapter.this.clear(); // directory.browseTo(position); // currentChecked = -1; // FolderAdapter.this.notifyDataSetChanged(); // doneButton.setEnabled(false); // } // }); // check = (CheckBox) row.findViewById(R.id.checkbox); // check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // // public void onCheckedChanged(CompoundButton buttonView, // boolean isChecked) { // // update last checked position // int position = (Integer) buttonView.getTag(); // if (isChecked) // currentChecked = position; // else if (currentChecked == position) // currentChecked = -1; // FolderAdapter.this.notifyDataSetChanged(); // if (isChecked) // doneButton.setEnabled(true); // } // }); // } // folder = (TextView) row.findViewById(R.id.folder); // folder.setText(directory.getDirectoryName(position)); // folder.setTag(Integer.valueOf(position)); // check = (CheckBox) row.findViewById(R.id.checkbox); // // disable the "Up one level" checkbox; otherwise make sure its enabled // if (position == 0 && !directory.isCurrentDirectoryRoot()) // check.setEnabled(false); // else // check.setEnabled(true); // check.setTag(Integer.valueOf(position)); // // set check state. only one can be checked // boolean status = (currentChecked == position) ? true : false; // check.setChecked(status); // return (row); // } // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/gui/wizard/wizards/DropboxWizard.java import android.os.Bundle; import android.os.StrictMode; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import com.dropbox.client2.DropboxAPI; import com.dropbox.client2.android.AndroidAuthSession; import com.dropbox.client2.session.AppKeyPair; import com.dropbox.client2.session.Session.AccessType; import com.matburt.mobileorg.gui.wizard.FolderAdapter; import com.matburt.mobileorg.R; package com.matburt.mobileorg.gui.wizard.wizards; public class DropboxWizard extends AppCompatActivity { private TextView dropboxAccountInfo; private DropboxAPI<AndroidAuthSession> dropboxApi;
private FolderAdapter directoryAdapter;
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/plugin/Synchronize.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/services/SyncService.java // public class SyncService extends Service implements // SharedPreferences.OnSharedPreferenceChangeListener { // private static final String ACTION = "action"; // private static final String START_ALARM = "START_ALARM"; // private static final String STOP_ALARM = "STOP_ALARM"; // // private SharedPreferences appSettings; // private MobileOrgApplication appInst; // // private AlarmManager alarmManager; // private PendingIntent alarmIntent; // private boolean alarmScheduled = false; // // private boolean syncRunning; // // public static void stopAlarm(Context context) { // Intent intent = new Intent(context, SyncService.class); // intent.putExtra(ACTION, SyncService.STOP_ALARM); // context.startService(intent); // } // // public static void startAlarm(Context context) { // Intent intent = new Intent(context, SyncService.class); // intent.putExtra(ACTION, SyncService.START_ALARM); // context.startService(intent); // } // // @Override // public void onCreate() { // super.onCreate(); // this.appSettings = PreferenceManager // .getDefaultSharedPreferences(getApplicationContext()); // this.appSettings.registerOnSharedPreferenceChangeListener(this); // this.appInst = (MobileOrgApplication) this.getApplication(); // this.alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // } // // @Override // public void onDestroy() { // unsetAlarm(); // this.appSettings.unregisterOnSharedPreferenceChangeListener(this); // super.onDestroy(); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // if( intent == null ) return 0; // String action = intent.getStringExtra(ACTION); // if (action != null && action.equals(START_ALARM)) // setAlarm(); // else if (action != null && action.equals(STOP_ALARM)) // unsetAlarm(); // else if(!this.syncRunning) { // this.syncRunning = true; // runSynchronizer(); // } // return 0; // } // // // // private void runSynchronizer() { // unsetAlarm(); // final Synchronizer synchronizer = Synchronizer.getInstance(); // // Thread syncThread = new Thread() { // public void run() { // synchronizer.runSynchronizer(); // Synchronizer.getInstance().postSynchronize(); // syncRunning = false; // setAlarm(); // } // }; // // syncThread.start(); // } // // // private void setAlarm() { // boolean doAutoSync = this.appSettings.getBoolean("doAutoSync", false); // if (!this.alarmScheduled && doAutoSync) { // // int interval = Integer.parseInt( // this.appSettings.getString("autoSyncInterval", "1800000"), // 10); // // this.alarmIntent = PendingIntent.getService(appInst, 0, new Intent( // this, SyncService.class), 0); // alarmManager.setRepeating(AlarmManager.RTC, // System.currentTimeMillis() + interval, interval, // alarmIntent); // // this.alarmScheduled = true; // } // } // // private void unsetAlarm() { // if (this.alarmScheduled) { // this.alarmManager.cancel(this.alarmIntent); // this.alarmScheduled = false; // } // } // // private void resetAlarm() { // unsetAlarm(); // setAlarm(); // } // // // @Override // public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, // String key) { // if (key.equals("doAutoSync")) { // if (sharedPreferences.getBoolean("doAutoSync", false) // && !this.alarmScheduled) // setAlarm(); // else if (!sharedPreferences.getBoolean("doAutoSync", false) // && this.alarmScheduled) // unsetAlarm(); // } else if (key.equals("autoSyncInterval")) // resetAlarm(); // } // // @Override // public IBinder onBind(Intent intent) { // return null; // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.matburt.mobileorg.services.SyncService;
package com.matburt.mobileorg.plugin; public final class Synchronize extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) {
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/services/SyncService.java // public class SyncService extends Service implements // SharedPreferences.OnSharedPreferenceChangeListener { // private static final String ACTION = "action"; // private static final String START_ALARM = "START_ALARM"; // private static final String STOP_ALARM = "STOP_ALARM"; // // private SharedPreferences appSettings; // private MobileOrgApplication appInst; // // private AlarmManager alarmManager; // private PendingIntent alarmIntent; // private boolean alarmScheduled = false; // // private boolean syncRunning; // // public static void stopAlarm(Context context) { // Intent intent = new Intent(context, SyncService.class); // intent.putExtra(ACTION, SyncService.STOP_ALARM); // context.startService(intent); // } // // public static void startAlarm(Context context) { // Intent intent = new Intent(context, SyncService.class); // intent.putExtra(ACTION, SyncService.START_ALARM); // context.startService(intent); // } // // @Override // public void onCreate() { // super.onCreate(); // this.appSettings = PreferenceManager // .getDefaultSharedPreferences(getApplicationContext()); // this.appSettings.registerOnSharedPreferenceChangeListener(this); // this.appInst = (MobileOrgApplication) this.getApplication(); // this.alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // } // // @Override // public void onDestroy() { // unsetAlarm(); // this.appSettings.unregisterOnSharedPreferenceChangeListener(this); // super.onDestroy(); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // if( intent == null ) return 0; // String action = intent.getStringExtra(ACTION); // if (action != null && action.equals(START_ALARM)) // setAlarm(); // else if (action != null && action.equals(STOP_ALARM)) // unsetAlarm(); // else if(!this.syncRunning) { // this.syncRunning = true; // runSynchronizer(); // } // return 0; // } // // // // private void runSynchronizer() { // unsetAlarm(); // final Synchronizer synchronizer = Synchronizer.getInstance(); // // Thread syncThread = new Thread() { // public void run() { // synchronizer.runSynchronizer(); // Synchronizer.getInstance().postSynchronize(); // syncRunning = false; // setAlarm(); // } // }; // // syncThread.start(); // } // // // private void setAlarm() { // boolean doAutoSync = this.appSettings.getBoolean("doAutoSync", false); // if (!this.alarmScheduled && doAutoSync) { // // int interval = Integer.parseInt( // this.appSettings.getString("autoSyncInterval", "1800000"), // 10); // // this.alarmIntent = PendingIntent.getService(appInst, 0, new Intent( // this, SyncService.class), 0); // alarmManager.setRepeating(AlarmManager.RTC, // System.currentTimeMillis() + interval, interval, // alarmIntent); // // this.alarmScheduled = true; // } // } // // private void unsetAlarm() { // if (this.alarmScheduled) { // this.alarmManager.cancel(this.alarmIntent); // this.alarmScheduled = false; // } // } // // private void resetAlarm() { // unsetAlarm(); // setAlarm(); // } // // // @Override // public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, // String key) { // if (key.equals("doAutoSync")) { // if (sharedPreferences.getBoolean("doAutoSync", false) // && !this.alarmScheduled) // setAlarm(); // else if (!sharedPreferences.getBoolean("doAutoSync", false) // && this.alarmScheduled) // unsetAlarm(); // } else if (key.equals("autoSyncInterval")) // resetAlarm(); // } // // @Override // public IBinder onBind(Intent intent) { // return null; // } // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/plugin/Synchronize.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.matburt.mobileorg.services.SyncService; package com.matburt.mobileorg.plugin; public final class Synchronize extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) {
context.startService(new Intent(context, SyncService.class));
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgNodeTimeDate.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgDatabase.java // public interface Tables { // String TIMESTAMPS = "timestamps"; // String FILES = "files"; // String PRIORITIES = "priorities"; // String TAGS = "tags"; // String TODOS = "todos"; // String ORGDATA = "orgdata"; // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgDatabase.Tables; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern;
public OrgNodeTimeDate(TYPE type, String line){ this.type = type; parseDate(line); } public OrgNodeTimeDate(TYPE type, int day, int month, int year) { this(type); setDate(day, month, year); } public OrgNodeTimeDate(TYPE type, int day, int month, int year, int startTimeOfDay, int startMinute) { this(type, day, month, year); setTime(startTimeOfDay, startMinute); } public OrgNodeTimeDate(long epochTimeInSec){ setEpochTime(epochTimeInSec, false); } /** * OrgNodeTimeDate ctor from the database * @param type * @param nodeId The OrgNode ID associated with this timestamp */ public OrgNodeTimeDate(TYPE type, long nodeId){ String todoQuery = "SELECT " + OrgContract.formatColumns(
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgDatabase.java // public interface Tables { // String TIMESTAMPS = "timestamps"; // String FILES = "files"; // String PRIORITIES = "priorities"; // String TAGS = "tags"; // String TODOS = "todos"; // String ORGDATA = "orgdata"; // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgNodeTimeDate.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgDatabase.Tables; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; public OrgNodeTimeDate(TYPE type, String line){ this.type = type; parseDate(line); } public OrgNodeTimeDate(TYPE type, int day, int month, int year) { this(type); setDate(day, month, year); } public OrgNodeTimeDate(TYPE type, int day, int month, int year, int startTimeOfDay, int startMinute) { this(type, day, month, year); setTime(startTimeOfDay, startMinute); } public OrgNodeTimeDate(long epochTimeInSec){ setEpochTime(epochTimeInSec, false); } /** * OrgNodeTimeDate ctor from the database * @param type * @param nodeId The OrgNode ID associated with this timestamp */ public OrgNodeTimeDate(TYPE type, long nodeId){ String todoQuery = "SELECT " + OrgContract.formatColumns(
Tables.TIMESTAMPS,
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgNodeTimeDate.java
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgDatabase.java // public interface Tables { // String TIMESTAMPS = "timestamps"; // String FILES = "files"; // String PRIORITIES = "priorities"; // String TAGS = "tags"; // String TODOS = "todos"; // String ORGDATA = "orgdata"; // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgDatabase.Tables; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern;
public OrgNodeTimeDate(TYPE type, String line){ this.type = type; parseDate(line); } public OrgNodeTimeDate(TYPE type, int day, int month, int year) { this(type); setDate(day, month, year); } public OrgNodeTimeDate(TYPE type, int day, int month, int year, int startTimeOfDay, int startMinute) { this(type, day, month, year); setTime(startTimeOfDay, startMinute); } public OrgNodeTimeDate(long epochTimeInSec){ setEpochTime(epochTimeInSec, false); } /** * OrgNodeTimeDate ctor from the database * @param type * @param nodeId The OrgNode ID associated with this timestamp */ public OrgNodeTimeDate(TYPE type, long nodeId){ String todoQuery = "SELECT " + OrgContract.formatColumns( Tables.TIMESTAMPS,
// Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgContract.java // public static class Timestamps implements TimestampsColumns { // public static final Uri CONTENT_URI = // BASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build(); // public static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY}; // // public static Uri buildIdUri(Long id) { // return CONTENT_URI.buildUpon().appendPath(id.toString()).build(); // } // // public static String getId(Uri uri) { // return uri.getLastPathSegment(); // } // } // // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgDatabase.java // public interface Tables { // String TIMESTAMPS = "timestamps"; // String FILES = "files"; // String PRIORITIES = "priorities"; // String TAGS = "tags"; // String TODOS = "todos"; // String ORGDATA = "orgdata"; // } // Path: MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgNodeTimeDate.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgDatabase.Tables; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; public OrgNodeTimeDate(TYPE type, String line){ this.type = type; parseDate(line); } public OrgNodeTimeDate(TYPE type, int day, int month, int year) { this(type); setDate(day, month, year); } public OrgNodeTimeDate(TYPE type, int day, int month, int year, int startTimeOfDay, int startMinute) { this(type, day, month, year); setTime(startTimeOfDay, startMinute); } public OrgNodeTimeDate(long epochTimeInSec){ setEpochTime(epochTimeInSec, false); } /** * OrgNodeTimeDate ctor from the database * @param type * @param nodeId The OrgNode ID associated with this timestamp */ public OrgNodeTimeDate(TYPE type, long nodeId){ String todoQuery = "SELECT " + OrgContract.formatColumns( Tables.TIMESTAMPS,
Timestamps.DEFAULT_COLUMNS ) +
vbauer/caesar
src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractReturnMethodRunner.java
// Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // }
import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.util.Objects;
package com.github.vbauer.caesar.runner.impl.base; /** * {@link AbstractAsyncMethodRunner} * * @author Vladislav Bauer */ public abstract class AbstractReturnMethodRunner extends AbstractAsyncMethodRunner { /** * {@inheritDoc} */ @Override protected Method findSyncMethod( final Class<?> targetClass, final String methodName, final Class<?> returnType, final Class<?>[] parameterTypes ) { final Class<?> returnClass = getReturnClass(returnType); return Objects.equals(returnClass, returnType)
// Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // } // Path: src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractReturnMethodRunner.java import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.util.Objects; package com.github.vbauer.caesar.runner.impl.base; /** * {@link AbstractAsyncMethodRunner} * * @author Vladislav Bauer */ public abstract class AbstractReturnMethodRunner extends AbstractAsyncMethodRunner { /** * {@inheritDoc} */ @Override protected Method findSyncMethod( final Class<?> targetClass, final String methodName, final Class<?> returnType, final Class<?>[] parameterTypes ) { final Class<?> returnClass = getReturnClass(returnType); return Objects.equals(returnClass, returnType)
? ReflectionUtils.findDeclaredMethod(targetClass, methodName, parameterTypes) : null;
vbauer/caesar
src/test/java/com/github/vbauer/caesar/runner/impl/FutureCallbackMethodRunnerTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/FutureCallbackAdapter.java // public class FutureCallbackAdapter<T> implements FutureCallback<T> { // // /** // * {@inheritDoc} // */ // @Override // public void onSuccess(final T result) { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onFailure(final Throwable t) { // // Do nothing. // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.callback.FutureCallbackAdapter; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.google.common.util.concurrent.FutureCallback; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer;
public void onSuccess(final Boolean result) { Assert.fail(); } @Override public void onFailure(final Throwable t) { Assert.assertNotNull(t); } }, false ) ); } @Test public void testWithoutResult() throws Throwable { Assert.assertTrue(check(callback -> getFutureCallbackAsync().empty(callback), notNullResultCallback(), true)); } @Test public void test1ArgumentWithoutResult() throws Throwable { Assert.assertTrue( check(callback -> getFutureCallbackAsync().emptyHello(callback, PARAMETER), notNullResultCallback(), true) ); } @Test public void test1ArgumentWithResult() throws Throwable { Assert.assertTrue( check( callback -> getFutureCallbackAsync().hello(callback, PARAMETER),
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/FutureCallbackAdapter.java // public class FutureCallbackAdapter<T> implements FutureCallback<T> { // // /** // * {@inheritDoc} // */ // @Override // public void onSuccess(final T result) { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onFailure(final Throwable t) { // // Do nothing. // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/runner/impl/FutureCallbackMethodRunnerTest.java import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.callback.FutureCallbackAdapter; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.google.common.util.concurrent.FutureCallback; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; public void onSuccess(final Boolean result) { Assert.fail(); } @Override public void onFailure(final Throwable t) { Assert.assertNotNull(t); } }, false ) ); } @Test public void testWithoutResult() throws Throwable { Assert.assertTrue(check(callback -> getFutureCallbackAsync().empty(callback), notNullResultCallback(), true)); } @Test public void test1ArgumentWithoutResult() throws Throwable { Assert.assertTrue( check(callback -> getFutureCallbackAsync().emptyHello(callback, PARAMETER), notNullResultCallback(), true) ); } @Test public void test1ArgumentWithResult() throws Throwable { Assert.assertTrue( check( callback -> getFutureCallbackAsync().hello(callback, PARAMETER),
new FutureCallbackAdapter<String>() {
vbauer/caesar
src/test/java/com/github/vbauer/caesar/runner/impl/FutureCallbackMethodRunnerTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/FutureCallbackAdapter.java // public class FutureCallbackAdapter<T> implements FutureCallback<T> { // // /** // * {@inheritDoc} // */ // @Override // public void onSuccess(final T result) { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onFailure(final Throwable t) { // // Do nothing. // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.callback.FutureCallbackAdapter; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.google.common.util.concurrent.FutureCallback; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer;
} }, true ) ); } @Test public void test2ArgumentsWithResult() throws Throwable { Assert.assertTrue( check( callback -> getFutureCallbackAsync().hello(callback, PARAMETER, PARAMETER), new FutureCallbackAdapter<String>() { @Override public void onSuccess(final String result) { Assert.assertEquals(getSync().hello(PARAMETER, PARAMETER), result); } }, true ) ); } @Test(expected = UnsupportedOperationException.class) public void testException() throws Throwable { Assert.assertTrue( check(callback -> getFutureCallbackAsync().exception(callback), new FutureCallbackAdapter<Void>(), true) ); }
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/FutureCallbackAdapter.java // public class FutureCallbackAdapter<T> implements FutureCallback<T> { // // /** // * {@inheritDoc} // */ // @Override // public void onSuccess(final T result) { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onFailure(final Throwable t) { // // Do nothing. // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/runner/impl/FutureCallbackMethodRunnerTest.java import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.callback.FutureCallbackAdapter; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.google.common.util.concurrent.FutureCallback; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; } }, true ) ); } @Test public void test2ArgumentsWithResult() throws Throwable { Assert.assertTrue( check( callback -> getFutureCallbackAsync().hello(callback, PARAMETER, PARAMETER), new FutureCallbackAdapter<String>() { @Override public void onSuccess(final String result) { Assert.assertEquals(getSync().hello(PARAMETER, PARAMETER), result); } }, true ) ); } @Test(expected = UnsupportedOperationException.class) public void testException() throws Throwable { Assert.assertTrue( check(callback -> getFutureCallbackAsync().exception(callback), new FutureCallbackAdapter<Void>(), true) ); }
@Test(expected = MissedSyncMethodException.class)
vbauer/caesar
src/test/java/com/github/vbauer/caesar/runner/impl/ObservableMethodRunnerTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.Assert; import org.junit.Test; import rx.Observable; import java.util.concurrent.CancellationException;
public void test1ArgumentWithoutResult() { getSync().emptyHello(PARAMETER); final Observable<Void> observable = getObservableAsync().emptyHello(PARAMETER); Assert.assertNotNull(observable); Assert.assertNull(observable.toBlocking().first()); } @Test public void test1ArgumentWithResult() { Assert.assertEquals( getSync().hello(PARAMETER), getObservableAsync().hello(PARAMETER).toBlocking().first() ); } @Test public void test2ArgumentsWithResult() { Assert.assertEquals( getSync().hello(PARAMETER, PARAMETER), getObservableAsync().hello(PARAMETER, PARAMETER).toBlocking().first() ); } @Test(expected = RuntimeException.class) public void testException() { getObservableAsync().exception().toBlocking().first(); Assert.fail(); }
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/runner/impl/ObservableMethodRunnerTest.java import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.Assert; import org.junit.Test; import rx.Observable; import java.util.concurrent.CancellationException; public void test1ArgumentWithoutResult() { getSync().emptyHello(PARAMETER); final Observable<Void> observable = getObservableAsync().emptyHello(PARAMETER); Assert.assertNotNull(observable); Assert.assertNull(observable.toBlocking().first()); } @Test public void test1ArgumentWithResult() { Assert.assertEquals( getSync().hello(PARAMETER), getObservableAsync().hello(PARAMETER).toBlocking().first() ); } @Test public void test2ArgumentsWithResult() { Assert.assertEquals( getSync().hello(PARAMETER, PARAMETER), getObservableAsync().hello(PARAMETER, PARAMETER).toBlocking().first() ); } @Test(expected = RuntimeException.class) public void testException() { getObservableAsync().exception().toBlocking().first(); Assert.fail(); }
@Test(expected = MissedSyncMethodException.class)
vbauer/caesar
src/main/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunner.java
// Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractCallbackMethodRunner.java // public abstract class AbstractCallbackMethodRunner extends AbstractAsyncMethodRunner { // // /** // * {@inheritDoc} // */ // @Override // public <T> Callable<T> createCall(final Object origin, final Method syncMethod, final Object[] args) { // final Object asyncCallback = args[0]; // final Object[] restArgs = Arrays.copyOfRange(args, 1, args.length); // // return createCall(origin, syncMethod, asyncCallback, restArgs); // } // // /** // * {@inheritDoc} // */ // @Override // protected Method findSyncMethod( // final Class<?> targetClass, final String methodName, // final Class<?> returnType, final Class<?>[] parameterTypes // ) { // if (void.class == returnType && parameterTypes != null && parameterTypes.length > 0) { // final Class<?> lastParam = parameterTypes[0]; // final Class<?> callbackClass = getCallbackClass(); // // if (callbackClass.isAssignableFrom(lastParam)) { // final Class<?>[] restParamTypes = // Arrays.copyOfRange(parameterTypes, 1, parameterTypes.length); // // return ReflectionUtils.findDeclaredMethod(targetClass, methodName, restParamTypes); // } // // } // return null; // } // // // protected abstract <T> Callable<T> createCall( // Object origin, Method syncMethod, Object callback, Object[] args // ); // // protected abstract Class<?> getCallbackClass(); // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/task/AsyncCallbackTask.java // public class AsyncCallbackTask<T> implements Callable<T> { // // private final Object origin; // private final Object[] args; // private final Method syncMethod; // private final AsyncCallback asyncCallback; // // // public AsyncCallbackTask( // final Object origin, final Method syncMethod, final Object[] args, final AsyncCallback asyncCallback // ) { // this.origin = origin; // this.args = args; // this.syncMethod = syncMethod; // this.asyncCallback = asyncCallback; // } // // // @SuppressWarnings("unchecked") // public T call() { // final Object result; // // try { // result = syncMethod.invoke(origin, args); // } catch (final Throwable ex) { // asyncCallback.onFailure(ex.getCause()); // return null; // } // // asyncCallback.onSuccess(result); // // return (T) result; // } // // }
import com.github.vbauer.caesar.callback.AsyncCallback; import com.github.vbauer.caesar.runner.impl.base.AbstractCallbackMethodRunner; import com.github.vbauer.caesar.runner.task.AsyncCallbackTask; import java.lang.reflect.Method; import java.util.concurrent.Callable;
package com.github.vbauer.caesar.runner.impl; /** * @author Vladislav Bauer */ @SuppressWarnings("all") public class AsyncCallbackMethodRunner extends AbstractCallbackMethodRunner { /** * {@inheritDoc} */ @Override protected <T> Callable<T> createCall( final Object origin, final Method syncMethod, final Object callback, final Object[] args ) {
// Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractCallbackMethodRunner.java // public abstract class AbstractCallbackMethodRunner extends AbstractAsyncMethodRunner { // // /** // * {@inheritDoc} // */ // @Override // public <T> Callable<T> createCall(final Object origin, final Method syncMethod, final Object[] args) { // final Object asyncCallback = args[0]; // final Object[] restArgs = Arrays.copyOfRange(args, 1, args.length); // // return createCall(origin, syncMethod, asyncCallback, restArgs); // } // // /** // * {@inheritDoc} // */ // @Override // protected Method findSyncMethod( // final Class<?> targetClass, final String methodName, // final Class<?> returnType, final Class<?>[] parameterTypes // ) { // if (void.class == returnType && parameterTypes != null && parameterTypes.length > 0) { // final Class<?> lastParam = parameterTypes[0]; // final Class<?> callbackClass = getCallbackClass(); // // if (callbackClass.isAssignableFrom(lastParam)) { // final Class<?>[] restParamTypes = // Arrays.copyOfRange(parameterTypes, 1, parameterTypes.length); // // return ReflectionUtils.findDeclaredMethod(targetClass, methodName, restParamTypes); // } // // } // return null; // } // // // protected abstract <T> Callable<T> createCall( // Object origin, Method syncMethod, Object callback, Object[] args // ); // // protected abstract Class<?> getCallbackClass(); // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/task/AsyncCallbackTask.java // public class AsyncCallbackTask<T> implements Callable<T> { // // private final Object origin; // private final Object[] args; // private final Method syncMethod; // private final AsyncCallback asyncCallback; // // // public AsyncCallbackTask( // final Object origin, final Method syncMethod, final Object[] args, final AsyncCallback asyncCallback // ) { // this.origin = origin; // this.args = args; // this.syncMethod = syncMethod; // this.asyncCallback = asyncCallback; // } // // // @SuppressWarnings("unchecked") // public T call() { // final Object result; // // try { // result = syncMethod.invoke(origin, args); // } catch (final Throwable ex) { // asyncCallback.onFailure(ex.getCause()); // return null; // } // // asyncCallback.onSuccess(result); // // return (T) result; // } // // } // Path: src/main/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunner.java import com.github.vbauer.caesar.callback.AsyncCallback; import com.github.vbauer.caesar.runner.impl.base.AbstractCallbackMethodRunner; import com.github.vbauer.caesar.runner.task.AsyncCallbackTask; import java.lang.reflect.Method; import java.util.concurrent.Callable; package com.github.vbauer.caesar.runner.impl; /** * @author Vladislav Bauer */ @SuppressWarnings("all") public class AsyncCallbackMethodRunner extends AbstractCallbackMethodRunner { /** * {@inheritDoc} */ @Override protected <T> Callable<T> createCall( final Object origin, final Method syncMethod, final Object callback, final Object[] args ) {
return new AsyncCallbackTask<T>(origin, syncMethod, args, (AsyncCallback) callback);
vbauer/caesar
src/main/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunner.java
// Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractCallbackMethodRunner.java // public abstract class AbstractCallbackMethodRunner extends AbstractAsyncMethodRunner { // // /** // * {@inheritDoc} // */ // @Override // public <T> Callable<T> createCall(final Object origin, final Method syncMethod, final Object[] args) { // final Object asyncCallback = args[0]; // final Object[] restArgs = Arrays.copyOfRange(args, 1, args.length); // // return createCall(origin, syncMethod, asyncCallback, restArgs); // } // // /** // * {@inheritDoc} // */ // @Override // protected Method findSyncMethod( // final Class<?> targetClass, final String methodName, // final Class<?> returnType, final Class<?>[] parameterTypes // ) { // if (void.class == returnType && parameterTypes != null && parameterTypes.length > 0) { // final Class<?> lastParam = parameterTypes[0]; // final Class<?> callbackClass = getCallbackClass(); // // if (callbackClass.isAssignableFrom(lastParam)) { // final Class<?>[] restParamTypes = // Arrays.copyOfRange(parameterTypes, 1, parameterTypes.length); // // return ReflectionUtils.findDeclaredMethod(targetClass, methodName, restParamTypes); // } // // } // return null; // } // // // protected abstract <T> Callable<T> createCall( // Object origin, Method syncMethod, Object callback, Object[] args // ); // // protected abstract Class<?> getCallbackClass(); // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/task/AsyncCallbackTask.java // public class AsyncCallbackTask<T> implements Callable<T> { // // private final Object origin; // private final Object[] args; // private final Method syncMethod; // private final AsyncCallback asyncCallback; // // // public AsyncCallbackTask( // final Object origin, final Method syncMethod, final Object[] args, final AsyncCallback asyncCallback // ) { // this.origin = origin; // this.args = args; // this.syncMethod = syncMethod; // this.asyncCallback = asyncCallback; // } // // // @SuppressWarnings("unchecked") // public T call() { // final Object result; // // try { // result = syncMethod.invoke(origin, args); // } catch (final Throwable ex) { // asyncCallback.onFailure(ex.getCause()); // return null; // } // // asyncCallback.onSuccess(result); // // return (T) result; // } // // }
import com.github.vbauer.caesar.callback.AsyncCallback; import com.github.vbauer.caesar.runner.impl.base.AbstractCallbackMethodRunner; import com.github.vbauer.caesar.runner.task.AsyncCallbackTask; import java.lang.reflect.Method; import java.util.concurrent.Callable;
package com.github.vbauer.caesar.runner.impl; /** * @author Vladislav Bauer */ @SuppressWarnings("all") public class AsyncCallbackMethodRunner extends AbstractCallbackMethodRunner { /** * {@inheritDoc} */ @Override protected <T> Callable<T> createCall( final Object origin, final Method syncMethod, final Object callback, final Object[] args ) {
// Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractCallbackMethodRunner.java // public abstract class AbstractCallbackMethodRunner extends AbstractAsyncMethodRunner { // // /** // * {@inheritDoc} // */ // @Override // public <T> Callable<T> createCall(final Object origin, final Method syncMethod, final Object[] args) { // final Object asyncCallback = args[0]; // final Object[] restArgs = Arrays.copyOfRange(args, 1, args.length); // // return createCall(origin, syncMethod, asyncCallback, restArgs); // } // // /** // * {@inheritDoc} // */ // @Override // protected Method findSyncMethod( // final Class<?> targetClass, final String methodName, // final Class<?> returnType, final Class<?>[] parameterTypes // ) { // if (void.class == returnType && parameterTypes != null && parameterTypes.length > 0) { // final Class<?> lastParam = parameterTypes[0]; // final Class<?> callbackClass = getCallbackClass(); // // if (callbackClass.isAssignableFrom(lastParam)) { // final Class<?>[] restParamTypes = // Arrays.copyOfRange(parameterTypes, 1, parameterTypes.length); // // return ReflectionUtils.findDeclaredMethod(targetClass, methodName, restParamTypes); // } // // } // return null; // } // // // protected abstract <T> Callable<T> createCall( // Object origin, Method syncMethod, Object callback, Object[] args // ); // // protected abstract Class<?> getCallbackClass(); // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/task/AsyncCallbackTask.java // public class AsyncCallbackTask<T> implements Callable<T> { // // private final Object origin; // private final Object[] args; // private final Method syncMethod; // private final AsyncCallback asyncCallback; // // // public AsyncCallbackTask( // final Object origin, final Method syncMethod, final Object[] args, final AsyncCallback asyncCallback // ) { // this.origin = origin; // this.args = args; // this.syncMethod = syncMethod; // this.asyncCallback = asyncCallback; // } // // // @SuppressWarnings("unchecked") // public T call() { // final Object result; // // try { // result = syncMethod.invoke(origin, args); // } catch (final Throwable ex) { // asyncCallback.onFailure(ex.getCause()); // return null; // } // // asyncCallback.onSuccess(result); // // return (T) result; // } // // } // Path: src/main/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunner.java import com.github.vbauer.caesar.callback.AsyncCallback; import com.github.vbauer.caesar.runner.impl.base.AbstractCallbackMethodRunner; import com.github.vbauer.caesar.runner.task.AsyncCallbackTask; import java.lang.reflect.Method; import java.util.concurrent.Callable; package com.github.vbauer.caesar.runner.impl; /** * @author Vladislav Bauer */ @SuppressWarnings("all") public class AsyncCallbackMethodRunner extends AbstractCallbackMethodRunner { /** * {@inheritDoc} */ @Override protected <T> Callable<T> createCall( final Object origin, final Method syncMethod, final Object callback, final Object[] args ) {
return new AsyncCallbackTask<T>(origin, syncMethod, args, (AsyncCallback) callback);
vbauer/caesar
src/test/java/com/github/vbauer/caesar/util/ReflectionUtilsTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunnerFactory.java // public final class AsyncMethodRunnerFactory { // // public static final String PACKAGE_NAME = "com.github.vbauer.caesar.runner.impl"; // // /** // * Immutable list with class names of method runners. // * // * IMPORTANT: // * This classes must be listed in the right order: from more-specific to less-specific classes. // */ // public static final List<String> CLASS_NAMES = Collections.unmodifiableList( // Arrays.asList( // "ObservableMethodRunner", // "ListenableFutureMethodRunner", // "FutureCallbackMethodRunner", // "FutureMethodRunner", // "AsyncCallbackMethodRunner", // "SyncMethodRunner" // ) // ); // // // private AsyncMethodRunnerFactory() { // throw new UnsupportedOperationException(); // } // // // public static Collection<AsyncMethodRunner> createMethodRunners() { // final Collection<String> classNames = // ReflectionUtils.classNames(PACKAGE_NAME, CLASS_NAMES); // // return ReflectionUtils.createObjects(classNames); // } // // }
import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.runner.AsyncMethodRunnerFactory; import com.google.common.collect.Lists; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.List;
package com.github.vbauer.caesar.util; /** * @author Vladislav Bauer */ public class ReflectionUtilsTest extends BasicTest { private static final String CLASS_OBJECT = "java.lang.Object"; private static final String CLASS_STRING = "java.lang.String"; @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(ReflectionUtils.class)); } @Test public void testCreateObject() { Assert.assertEquals( Object.class, ReflectionUtils.getClassSafe(ReflectionUtils.createObject(CLASS_OBJECT)) ); Assert.assertArrayEquals((Object[]) null, ReflectionUtils.createObject(null)); } @Test public void testCreateObjects() { final List<Object> objects = Lists.newArrayList( ReflectionUtils.createObjects( Arrays.asList(CLASS_OBJECT, CLASS_STRING) ) ); Assert.assertEquals(Object.class, objects.get(0).getClass()); Assert.assertEquals(String.class, objects.get(1).getClass()); Assert.assertEquals(2, objects.size()); } @Test public void testClassNames() {
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunnerFactory.java // public final class AsyncMethodRunnerFactory { // // public static final String PACKAGE_NAME = "com.github.vbauer.caesar.runner.impl"; // // /** // * Immutable list with class names of method runners. // * // * IMPORTANT: // * This classes must be listed in the right order: from more-specific to less-specific classes. // */ // public static final List<String> CLASS_NAMES = Collections.unmodifiableList( // Arrays.asList( // "ObservableMethodRunner", // "ListenableFutureMethodRunner", // "FutureCallbackMethodRunner", // "FutureMethodRunner", // "AsyncCallbackMethodRunner", // "SyncMethodRunner" // ) // ); // // // private AsyncMethodRunnerFactory() { // throw new UnsupportedOperationException(); // } // // // public static Collection<AsyncMethodRunner> createMethodRunners() { // final Collection<String> classNames = // ReflectionUtils.classNames(PACKAGE_NAME, CLASS_NAMES); // // return ReflectionUtils.createObjects(classNames); // } // // } // Path: src/test/java/com/github/vbauer/caesar/util/ReflectionUtilsTest.java import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.runner.AsyncMethodRunnerFactory; import com.google.common.collect.Lists; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.List; package com.github.vbauer.caesar.util; /** * @author Vladislav Bauer */ public class ReflectionUtilsTest extends BasicTest { private static final String CLASS_OBJECT = "java.lang.Object"; private static final String CLASS_STRING = "java.lang.String"; @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(ReflectionUtils.class)); } @Test public void testCreateObject() { Assert.assertEquals( Object.class, ReflectionUtils.getClassSafe(ReflectionUtils.createObject(CLASS_OBJECT)) ); Assert.assertArrayEquals((Object[]) null, ReflectionUtils.createObject(null)); } @Test public void testCreateObjects() { final List<Object> objects = Lists.newArrayList( ReflectionUtils.createObjects( Arrays.asList(CLASS_OBJECT, CLASS_STRING) ) ); Assert.assertEquals(Object.class, objects.get(0).getClass()); Assert.assertEquals(String.class, objects.get(1).getClass()); Assert.assertEquals(2, objects.size()); } @Test public void testClassNames() {
final String packageName = AsyncMethodRunnerFactory.PACKAGE_NAME;
vbauer/caesar
src/test/java/com/github/vbauer/caesar/runner/impl/FutureMethodRunnerTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future;
final Future<Void> future = getFutureAsync().empty(); Assert.assertNotNull(future); Assert.assertNull(future.get()); } @Test public void test1ArgumentWithoutResult() throws Throwable { getSync().emptyHello(PARAMETER); final Future<Void> future = getFutureAsync().emptyHello(PARAMETER); Assert.assertNotNull(future); Assert.assertNull(future.get()); } @Test public void test1ArgumentWithResult() throws Throwable { Assert.assertEquals(getSync().hello(PARAMETER), getFutureAsync().hello(PARAMETER).get()); } @Test public void test2ArgumentsWithResult() throws Throwable { Assert.assertEquals(getSync().hello(PARAMETER, PARAMETER), getFutureAsync().hello(PARAMETER, PARAMETER).get()); } @Test(expected = ExecutionException.class) public void testException() throws Throwable { getFutureAsync().exception().get(); Assert.fail(); }
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/runner/impl/FutureMethodRunnerTest.java import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; final Future<Void> future = getFutureAsync().empty(); Assert.assertNotNull(future); Assert.assertNull(future.get()); } @Test public void test1ArgumentWithoutResult() throws Throwable { getSync().emptyHello(PARAMETER); final Future<Void> future = getFutureAsync().emptyHello(PARAMETER); Assert.assertNotNull(future); Assert.assertNull(future.get()); } @Test public void test1ArgumentWithResult() throws Throwable { Assert.assertEquals(getSync().hello(PARAMETER), getFutureAsync().hello(PARAMETER).get()); } @Test public void test2ArgumentsWithResult() throws Throwable { Assert.assertEquals(getSync().hello(PARAMETER, PARAMETER), getFutureAsync().hello(PARAMETER, PARAMETER).get()); } @Test(expected = ExecutionException.class) public void testException() throws Throwable { getFutureAsync().exception().get(); Assert.fail(); }
@Test(expected = MissedSyncMethodException.class)
vbauer/caesar
src/main/java/com/github/vbauer/caesar/runner/task/AsyncCallbackTask.java
// Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // }
import com.github.vbauer.caesar.callback.AsyncCallback; import java.lang.reflect.Method; import java.util.concurrent.Callable;
package com.github.vbauer.caesar.runner.task; /** * @author Vladislav Bauer * @param <T> result type */ public class AsyncCallbackTask<T> implements Callable<T> { private final Object origin; private final Object[] args; private final Method syncMethod;
// Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // } // Path: src/main/java/com/github/vbauer/caesar/runner/task/AsyncCallbackTask.java import com.github.vbauer.caesar.callback.AsyncCallback; import java.lang.reflect.Method; import java.util.concurrent.Callable; package com.github.vbauer.caesar.runner.task; /** * @author Vladislav Bauer * @param <T> result type */ public class AsyncCallbackTask<T> implements Callable<T> { private final Object origin; private final Object[] args; private final Method syncMethod;
private final AsyncCallback asyncCallback;
vbauer/caesar
src/test/java/com/github/vbauer/caesar/annotation/TimeoutAnnotationTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/UnsupportedTimeoutException.java // @SuppressWarnings("serial") // public class UnsupportedTimeoutException extends AbstractCaesarException { // // private final Executor executor; // // // public UnsupportedTimeoutException(final Executor executor) { // this.executor = executor; // } // // // public Executor getExecutor() { // return executor; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "%s does not support timeouts. Use %s.", // getExecutor(), ScheduledExecutorService.class // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java // public final class AsyncProxyCreator { // // private AsyncProxyCreator() { // throw new UnsupportedOperationException(); // } // // // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor // ) { // return create(bean, asyncInterface, executor, true); // } // // @SuppressWarnings("unchecked") // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate // ) { // final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); // final Class<?> beanClass = bean.getClass(); // final ClassLoader classLoader = beanClass.getClassLoader(); // final Class<?>[] interfaces = { // asyncInterface, // }; // // final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); // return validate ? validate(proxy, handler) : proxy; // } // // // private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { // final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); // final Method[] methods = targetClass.getDeclaredMethods(); // // for (final Method method : methods) { // final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method); // if (runner == null) { // throw new MissedSyncMethodException(method); // } // } // // return proxy; // } // // }
import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.exception.UnsupportedTimeoutException; import com.github.vbauer.caesar.proxy.AsyncProxyCreator; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.github.vbauer.caesar.annotation; /** * @author Vladislav Bauer */ public class TimeoutAnnotationTest extends BasicTest { @Test public void testGoodExecutorService() throws Exception { final ExecutorService executor = Executors.newScheduledThreadPool(1); try {
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/UnsupportedTimeoutException.java // @SuppressWarnings("serial") // public class UnsupportedTimeoutException extends AbstractCaesarException { // // private final Executor executor; // // // public UnsupportedTimeoutException(final Executor executor) { // this.executor = executor; // } // // // public Executor getExecutor() { // return executor; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "%s does not support timeouts. Use %s.", // getExecutor(), ScheduledExecutorService.class // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java // public final class AsyncProxyCreator { // // private AsyncProxyCreator() { // throw new UnsupportedOperationException(); // } // // // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor // ) { // return create(bean, asyncInterface, executor, true); // } // // @SuppressWarnings("unchecked") // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate // ) { // final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); // final Class<?> beanClass = bean.getClass(); // final ClassLoader classLoader = beanClass.getClassLoader(); // final Class<?>[] interfaces = { // asyncInterface, // }; // // final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); // return validate ? validate(proxy, handler) : proxy; // } // // // private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { // final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); // final Method[] methods = targetClass.getDeclaredMethods(); // // for (final Method method : methods) { // final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method); // if (runner == null) { // throw new MissedSyncMethodException(method); // } // } // // return proxy; // } // // } // Path: src/test/java/com/github/vbauer/caesar/annotation/TimeoutAnnotationTest.java import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.exception.UnsupportedTimeoutException; import com.github.vbauer.caesar.proxy.AsyncProxyCreator; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package com.github.vbauer.caesar.annotation; /** * @author Vladislav Bauer */ public class TimeoutAnnotationTest extends BasicTest { @Test public void testGoodExecutorService() throws Exception { final ExecutorService executor = Executors.newScheduledThreadPool(1); try {
final SimpleAsync proxy = createProxy(executor);
vbauer/caesar
src/test/java/com/github/vbauer/caesar/annotation/TimeoutAnnotationTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/UnsupportedTimeoutException.java // @SuppressWarnings("serial") // public class UnsupportedTimeoutException extends AbstractCaesarException { // // private final Executor executor; // // // public UnsupportedTimeoutException(final Executor executor) { // this.executor = executor; // } // // // public Executor getExecutor() { // return executor; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "%s does not support timeouts. Use %s.", // getExecutor(), ScheduledExecutorService.class // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java // public final class AsyncProxyCreator { // // private AsyncProxyCreator() { // throw new UnsupportedOperationException(); // } // // // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor // ) { // return create(bean, asyncInterface, executor, true); // } // // @SuppressWarnings("unchecked") // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate // ) { // final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); // final Class<?> beanClass = bean.getClass(); // final ClassLoader classLoader = beanClass.getClassLoader(); // final Class<?>[] interfaces = { // asyncInterface, // }; // // final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); // return validate ? validate(proxy, handler) : proxy; // } // // // private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { // final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); // final Method[] methods = targetClass.getDeclaredMethods(); // // for (final Method method : methods) { // final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method); // if (runner == null) { // throw new MissedSyncMethodException(method); // } // } // // return proxy; // } // // }
import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.exception.UnsupportedTimeoutException; import com.github.vbauer.caesar.proxy.AsyncProxyCreator; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.github.vbauer.caesar.annotation; /** * @author Vladislav Bauer */ public class TimeoutAnnotationTest extends BasicTest { @Test public void testGoodExecutorService() throws Exception { final ExecutorService executor = Executors.newScheduledThreadPool(1); try { final SimpleAsync proxy = createProxy(executor);
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/UnsupportedTimeoutException.java // @SuppressWarnings("serial") // public class UnsupportedTimeoutException extends AbstractCaesarException { // // private final Executor executor; // // // public UnsupportedTimeoutException(final Executor executor) { // this.executor = executor; // } // // // public Executor getExecutor() { // return executor; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "%s does not support timeouts. Use %s.", // getExecutor(), ScheduledExecutorService.class // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java // public final class AsyncProxyCreator { // // private AsyncProxyCreator() { // throw new UnsupportedOperationException(); // } // // // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor // ) { // return create(bean, asyncInterface, executor, true); // } // // @SuppressWarnings("unchecked") // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate // ) { // final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); // final Class<?> beanClass = bean.getClass(); // final ClassLoader classLoader = beanClass.getClassLoader(); // final Class<?>[] interfaces = { // asyncInterface, // }; // // final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); // return validate ? validate(proxy, handler) : proxy; // } // // // private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { // final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); // final Method[] methods = targetClass.getDeclaredMethods(); // // for (final Method method : methods) { // final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method); // if (runner == null) { // throw new MissedSyncMethodException(method); // } // } // // return proxy; // } // // } // Path: src/test/java/com/github/vbauer/caesar/annotation/TimeoutAnnotationTest.java import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.exception.UnsupportedTimeoutException; import com.github.vbauer.caesar.proxy.AsyncProxyCreator; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package com.github.vbauer.caesar.annotation; /** * @author Vladislav Bauer */ public class TimeoutAnnotationTest extends BasicTest { @Test public void testGoodExecutorService() throws Exception { final ExecutorService executor = Executors.newScheduledThreadPool(1); try { final SimpleAsync proxy = createProxy(executor);
Assert.assertEquals(SimpleSync.TIMEOUT_VALUE, proxy.timeout().get());
vbauer/caesar
src/test/java/com/github/vbauer/caesar/annotation/TimeoutAnnotationTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/UnsupportedTimeoutException.java // @SuppressWarnings("serial") // public class UnsupportedTimeoutException extends AbstractCaesarException { // // private final Executor executor; // // // public UnsupportedTimeoutException(final Executor executor) { // this.executor = executor; // } // // // public Executor getExecutor() { // return executor; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "%s does not support timeouts. Use %s.", // getExecutor(), ScheduledExecutorService.class // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java // public final class AsyncProxyCreator { // // private AsyncProxyCreator() { // throw new UnsupportedOperationException(); // } // // // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor // ) { // return create(bean, asyncInterface, executor, true); // } // // @SuppressWarnings("unchecked") // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate // ) { // final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); // final Class<?> beanClass = bean.getClass(); // final ClassLoader classLoader = beanClass.getClassLoader(); // final Class<?>[] interfaces = { // asyncInterface, // }; // // final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); // return validate ? validate(proxy, handler) : proxy; // } // // // private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { // final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); // final Method[] methods = targetClass.getDeclaredMethods(); // // for (final Method method : methods) { // final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method); // if (runner == null) { // throw new MissedSyncMethodException(method); // } // } // // return proxy; // } // // }
import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.exception.UnsupportedTimeoutException; import com.github.vbauer.caesar.proxy.AsyncProxyCreator; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.github.vbauer.caesar.annotation; /** * @author Vladislav Bauer */ public class TimeoutAnnotationTest extends BasicTest { @Test public void testGoodExecutorService() throws Exception { final ExecutorService executor = Executors.newScheduledThreadPool(1); try { final SimpleAsync proxy = createProxy(executor); Assert.assertEquals(SimpleSync.TIMEOUT_VALUE, proxy.timeout().get()); } finally { executor.shutdown(); } }
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/UnsupportedTimeoutException.java // @SuppressWarnings("serial") // public class UnsupportedTimeoutException extends AbstractCaesarException { // // private final Executor executor; // // // public UnsupportedTimeoutException(final Executor executor) { // this.executor = executor; // } // // // public Executor getExecutor() { // return executor; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "%s does not support timeouts. Use %s.", // getExecutor(), ScheduledExecutorService.class // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java // public final class AsyncProxyCreator { // // private AsyncProxyCreator() { // throw new UnsupportedOperationException(); // } // // // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor // ) { // return create(bean, asyncInterface, executor, true); // } // // @SuppressWarnings("unchecked") // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate // ) { // final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); // final Class<?> beanClass = bean.getClass(); // final ClassLoader classLoader = beanClass.getClassLoader(); // final Class<?>[] interfaces = { // asyncInterface, // }; // // final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); // return validate ? validate(proxy, handler) : proxy; // } // // // private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { // final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); // final Method[] methods = targetClass.getDeclaredMethods(); // // for (final Method method : methods) { // final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method); // if (runner == null) { // throw new MissedSyncMethodException(method); // } // } // // return proxy; // } // // } // Path: src/test/java/com/github/vbauer/caesar/annotation/TimeoutAnnotationTest.java import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.exception.UnsupportedTimeoutException; import com.github.vbauer.caesar.proxy.AsyncProxyCreator; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package com.github.vbauer.caesar.annotation; /** * @author Vladislav Bauer */ public class TimeoutAnnotationTest extends BasicTest { @Test public void testGoodExecutorService() throws Exception { final ExecutorService executor = Executors.newScheduledThreadPool(1); try { final SimpleAsync proxy = createProxy(executor); Assert.assertEquals(SimpleSync.TIMEOUT_VALUE, proxy.timeout().get()); } finally { executor.shutdown(); } }
@Test(expected = UnsupportedTimeoutException.class)