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
wangchongjie/multi-engine
src/test/java/com/baidu/unbiz/multiengine/codec/CodecTest.java
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/JsonCodec.java // public class JsonCodec implements MsgCodec { // /** // * 对象匹配映射 // */ // private final ObjectMapper mapper; // // public JsonCodec() { // mapper = new ObjectMapper(); // // ignoring unknown properties makes us more robust to changes in the schema // mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // // This will allow including type information all non-final types. This allows correct // // serialization/deserialization of generic collections, for example List<MyType>. // mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); // } // // @Override // public byte[] encode(Object object) throws CodecException { // try { // return mapper.writeValueAsBytes(object); // } catch (Exception e) { // throw new CodecException(e); // } // } // // @Override // public <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException { // try { // return mapper.readValue(bytes, clazz); // } catch (Exception e) { // throw new CodecException(e); // } // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/ProtostuffCodec.java // public class ProtostuffCodec implements MsgCodec { // // /** // * 设置编码规则 // */ // static { // System.setProperty("protostuff.runtime.collection_schema_on_repeated_fields", "true"); // System.setProperty("protostuff.runtime.morph_collection_interfaces", "true"); // System.setProperty("protostuff.runtime.morph_map_interfaces", "true"); // } // // /** // * 缓冲区 // */ // private ThreadLocal<LinkedBuffer> linkedBuffer = new ThreadLocal<LinkedBuffer>() { // @Override // protected LinkedBuffer initialValue() { // return LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); // } // }; // // @Override // public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException { // Schema<T> schema = RuntimeSchema.getSchema(clazz); // // T content = ReflectionUtil.newInstance(clazz); // ProtobufIOUtil.mergeFrom(data, content, schema); // return content; // } // // @Override // public <T> byte[] encode(T object) throws CodecException { // try { // @SuppressWarnings("unchecked") // com.dyuproject.protostuff.Schema<T> schema = // (com.dyuproject.protostuff.Schema<T>) RuntimeSchema.getSchema(object.getClass()); // byte[] protostuff = ProtobufIOUtil.toByteArray(object, schema, linkedBuffer.get()); // return protostuff; // } finally { // linkedBuffer.get().clear(); // } // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/dto/Signal.java // public class Signal<T> { // // protected long seqId; // protected T message; // protected SignalType type = SignalType.TASK_COMMOND; // // public Signal() { // } // // public Signal(T message) { // this.message = message; // } // // public T getMessage() { // return message; // } // // public void setMessage(T message) { // this.message = message; // } // // public long getSeqId() { // return seqId; // } // // public void setSeqId(long seqId) { // this.seqId = seqId; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public SignalType getType() { // return type; // } // // public void setType(SignalType type) { // this.type = type; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java // public class DeviceViewItem { // // private static final long serialVersionUID = 6132709579470894604L; // // private int planId; // // private String planName; // // private Integer deviceId; // // private String deviceName ; // // // getter and setter // public int getPlanId() { // return planId; // } // // public void setPlanId(int planId) { // this.planId = planId; // } // // public Integer getDeviceId() { // return deviceId; // } // // public void setDeviceId(Integer deviceId) { // this.deviceId = deviceId; // } // // public String getPlanName() { // return planName; // } // // public void setPlanName(String planName) { // this.planName = planName; // } // // public String getDeviceName() { // return deviceName; // } // // public void setDeviceName(String deviceName) { // this.deviceName = deviceName; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // }
import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.baidu.unbiz.multiengine.codec.common.JsonCodec; import com.baidu.unbiz.multiengine.codec.common.ProtostuffCodec; import com.baidu.unbiz.multiengine.transport.dto.Signal; import com.baidu.unbiz.multiengine.vo.DeviceViewItem;
package com.baidu.unbiz.multiengine.codec; /** * Created by wangchongjie on 16/4/5. */ public class CodecTest { @Test public void testProtostuffCodec() { MsgCodec codec = new ProtostuffCodec(); List<DeviceViewItem> dataList = mockList();
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/JsonCodec.java // public class JsonCodec implements MsgCodec { // /** // * 对象匹配映射 // */ // private final ObjectMapper mapper; // // public JsonCodec() { // mapper = new ObjectMapper(); // // ignoring unknown properties makes us more robust to changes in the schema // mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // // This will allow including type information all non-final types. This allows correct // // serialization/deserialization of generic collections, for example List<MyType>. // mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); // } // // @Override // public byte[] encode(Object object) throws CodecException { // try { // return mapper.writeValueAsBytes(object); // } catch (Exception e) { // throw new CodecException(e); // } // } // // @Override // public <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException { // try { // return mapper.readValue(bytes, clazz); // } catch (Exception e) { // throw new CodecException(e); // } // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/ProtostuffCodec.java // public class ProtostuffCodec implements MsgCodec { // // /** // * 设置编码规则 // */ // static { // System.setProperty("protostuff.runtime.collection_schema_on_repeated_fields", "true"); // System.setProperty("protostuff.runtime.morph_collection_interfaces", "true"); // System.setProperty("protostuff.runtime.morph_map_interfaces", "true"); // } // // /** // * 缓冲区 // */ // private ThreadLocal<LinkedBuffer> linkedBuffer = new ThreadLocal<LinkedBuffer>() { // @Override // protected LinkedBuffer initialValue() { // return LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); // } // }; // // @Override // public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException { // Schema<T> schema = RuntimeSchema.getSchema(clazz); // // T content = ReflectionUtil.newInstance(clazz); // ProtobufIOUtil.mergeFrom(data, content, schema); // return content; // } // // @Override // public <T> byte[] encode(T object) throws CodecException { // try { // @SuppressWarnings("unchecked") // com.dyuproject.protostuff.Schema<T> schema = // (com.dyuproject.protostuff.Schema<T>) RuntimeSchema.getSchema(object.getClass()); // byte[] protostuff = ProtobufIOUtil.toByteArray(object, schema, linkedBuffer.get()); // return protostuff; // } finally { // linkedBuffer.get().clear(); // } // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/dto/Signal.java // public class Signal<T> { // // protected long seqId; // protected T message; // protected SignalType type = SignalType.TASK_COMMOND; // // public Signal() { // } // // public Signal(T message) { // this.message = message; // } // // public T getMessage() { // return message; // } // // public void setMessage(T message) { // this.message = message; // } // // public long getSeqId() { // return seqId; // } // // public void setSeqId(long seqId) { // this.seqId = seqId; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public SignalType getType() { // return type; // } // // public void setType(SignalType type) { // this.type = type; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java // public class DeviceViewItem { // // private static final long serialVersionUID = 6132709579470894604L; // // private int planId; // // private String planName; // // private Integer deviceId; // // private String deviceName ; // // // getter and setter // public int getPlanId() { // return planId; // } // // public void setPlanId(int planId) { // this.planId = planId; // } // // public Integer getDeviceId() { // return deviceId; // } // // public void setDeviceId(Integer deviceId) { // this.deviceId = deviceId; // } // // public String getPlanName() { // return planName; // } // // public void setPlanName(String planName) { // this.planName = planName; // } // // public String getDeviceName() { // return deviceName; // } // // public void setDeviceName(String deviceName) { // this.deviceName = deviceName; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // } // Path: src/test/java/com/baidu/unbiz/multiengine/codec/CodecTest.java import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.baidu.unbiz.multiengine.codec.common.JsonCodec; import com.baidu.unbiz.multiengine.codec.common.ProtostuffCodec; import com.baidu.unbiz.multiengine.transport.dto.Signal; import com.baidu.unbiz.multiengine.vo.DeviceViewItem; package com.baidu.unbiz.multiengine.codec; /** * Created by wangchongjie on 16/4/5. */ public class CodecTest { @Test public void testProtostuffCodec() { MsgCodec codec = new ProtostuffCodec(); List<DeviceViewItem> dataList = mockList();
Signal params = new Signal(dataList);
wangchongjie/multi-engine
src/main/java/com/baidu/unbiz/multiengine/codec/common/ProtobufCodec.java
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java // public interface MsgCodec { // /** // * 反序列化 // * // * @param clazz 反序列化后的类定义 // * @param bytes 字节码 // * @return 反序列化后的对象 // * @throws CodecException // */ // <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException; // // /** // * 序列化 // * // * @param object 待序列化的对象 // * @return 字节码 // * @throws CodecException // */ // <T> byte[] encode(T object) throws CodecException; // } // // Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java // public class CodecException extends RuntimeException { // // /** // * serialVersionUID // */ // private static final long serialVersionUID = 5196421433506179782L; // // /** // * Creates a new instance of CodecException. // */ // public CodecException() { // super(); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // * @param arg1 // */ // public CodecException(String arg0, Throwable arg1) { // super(arg0, arg1); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(String arg0) { // super(arg0); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(Throwable arg0) { // super(arg0); // } // // }
import java.lang.reflect.Method; import java.util.concurrent.Callable; import com.baidu.unbiz.devlib.cache.AtomicComputeCache; import com.baidu.unbiz.multiengine.codec.MsgCodec; import com.baidu.unbiz.multiengine.exception.CodecException; import com.google.protobuf.GeneratedMessage;
package com.baidu.unbiz.multiengine.codec.common; /** * ClassName: ProtobufCodec <br/> * Function: protobuf序列化器,利用反射缓存<tt>method</tt>来进行调用 * */ public class ProtobufCodec implements MsgCodec { /** * Protobuf生成原生Java代码中的方法解码方法名称 */ private static final String METHOD_NAME_PARSEFROM = "parseFrom"; /** * Protobuf生成原生Java代码中的方法编码方法名称 */ private static final String METHOD_NAME_TOBYTE = "toByteArray"; /** * 方法缓存,用于Protobuf生成原生Java代码中的某些编解码方法。 缓存的方法包括: */ private static final AtomicComputeCache<String, Method> PROTOBUF_METHOD_CACHE = new AtomicComputeCache<String, Method>(); @Override
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java // public interface MsgCodec { // /** // * 反序列化 // * // * @param clazz 反序列化后的类定义 // * @param bytes 字节码 // * @return 反序列化后的对象 // * @throws CodecException // */ // <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException; // // /** // * 序列化 // * // * @param object 待序列化的对象 // * @return 字节码 // * @throws CodecException // */ // <T> byte[] encode(T object) throws CodecException; // } // // Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java // public class CodecException extends RuntimeException { // // /** // * serialVersionUID // */ // private static final long serialVersionUID = 5196421433506179782L; // // /** // * Creates a new instance of CodecException. // */ // public CodecException() { // super(); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // * @param arg1 // */ // public CodecException(String arg0, Throwable arg1) { // super(arg0, arg1); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(String arg0) { // super(arg0); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(Throwable arg0) { // super(arg0); // } // // } // Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/ProtobufCodec.java import java.lang.reflect.Method; import java.util.concurrent.Callable; import com.baidu.unbiz.devlib.cache.AtomicComputeCache; import com.baidu.unbiz.multiengine.codec.MsgCodec; import com.baidu.unbiz.multiengine.exception.CodecException; import com.google.protobuf.GeneratedMessage; package com.baidu.unbiz.multiengine.codec.common; /** * ClassName: ProtobufCodec <br/> * Function: protobuf序列化器,利用反射缓存<tt>method</tt>来进行调用 * */ public class ProtobufCodec implements MsgCodec { /** * Protobuf生成原生Java代码中的方法解码方法名称 */ private static final String METHOD_NAME_PARSEFROM = "parseFrom"; /** * Protobuf生成原生Java代码中的方法编码方法名称 */ private static final String METHOD_NAME_TOBYTE = "toByteArray"; /** * 方法缓存,用于Protobuf生成原生Java代码中的某些编解码方法。 缓存的方法包括: */ private static final AtomicComputeCache<String, Method> PROTOBUF_METHOD_CACHE = new AtomicComputeCache<String, Method>(); @Override
public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException {
wangchongjie/multi-engine
src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClientFactory.java
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/HostConf.java // public class HostConf { // // private String host = System.getProperty("host", "127.0.0.1"); // private int port = Integer.parseInt(System.getProperty("port", "8007")); // private boolean ssl = System.getProperty("ssl") != null; // // public HostConf() { // try { // InetAddress addr = InetAddress.getLocalHost(); // host = addr.getHostAddress(); // } catch (UnknownHostException e) { // // do nothing // } // } // // public HostConf(String host, int port) { // this(); // this.host = host; // this.port = port; // } // // @Override // public boolean equals(Object obj) { // if (!(obj instanceof HostConf)) { // return false; // } // HostConf other = (HostConf) obj; // return this.host.equals(other.getHost()) && this.port == other.getPort() && this.ssl == other.isSsl(); // } // // @Override // public int hashCode() { // return this.host.hashCode() + this.host.hashCode(); // } // // public static List<HostConf> resolveHost(String hosts) { // List<HostConf> hostConfs = new ArrayList<HostConf>(); // if (StringUtils.isEmpty(hosts)) { // return hostConfs; // } // String[] hostStrs = hosts.split(";"); // for (String host : hostStrs) { // String ip = host.replaceAll(":.*", ""); // String port = host.replaceAll(".*:", ""); // hostConfs.add(new HostConf(ip, Integer.parseInt(port))); // } // return hostConfs; // } // // public static List<HostConf> resolvePort(String ports) { // // List<HostConf> hostConfs = new ArrayList<HostConf>(); // if (StringUtils.isEmpty(ports)) { // return hostConfs; // } // String[] ps = ports.split(";"); // for (String port : ps) { // HostConf hostConf = new HostConf(); // hostConf.setPort(Integer.parseInt(port)); // hostConfs.add(hostConf); // } // return hostConfs; // } // // public String info() { // StringBuilder sb = new StringBuilder(); // sb.append(this.getHost()).append(":").append(this.getPort()); // return sb.toString(); // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public boolean isSsl() { // return ssl; // } // // public void setSsl(boolean ssl) { // this.ssl = ssl; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/DefaultSessionIdProvider.java // public class DefaultSessionIdProvider implements SessionIdProvider, Cloneable { // private String prefix; // private volatile String currentSessionId; // // /** // * 无参数构造方法 // */ // public DefaultSessionIdProvider() { // } // // /** // * 构造方法 // * // * @param prefix sessionid前缀 // */ // public DefaultSessionIdProvider(String prefix) { // this.prefix = prefix; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // // // @Override // public String getSessionId(boolean refresh) { // if (refresh) { // currentSessionId = genSessionId(); // } // return currentSessionId; // } // // /** // * 生成uuid session // * // * @return session // */ // private String genSessionId() { // if (prefix == null) { // return UUID.randomUUID().toString(); // } else { // return prefix + "_" + UUID.randomUUID().toString(); // } // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/SequenceIdGen.java // public class SequenceIdGen { // private AtomicLong counter = new AtomicLong(0); // // public long genId() { // long v = counter.incrementAndGet(); // if (v < 0) { // v &= Long.MAX_VALUE; // } // if (v == 0) { // return genId(); // } // return v; // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/SessionIdProvider.java // public interface SessionIdProvider { // /** // * 获取sessionid // * // * @param refresh 是否刷新新session id // * @return session id // */ // String getSessionId(boolean refresh); // // }
import com.baidu.unbiz.multiengine.endpoint.HostConf; import com.baidu.unbiz.multiengine.transport.DefaultSessionIdProvider; import com.baidu.unbiz.multiengine.transport.SequenceIdGen; import com.baidu.unbiz.multiengine.transport.SessionIdProvider;
package com.baidu.unbiz.multiengine.transport.client; /** * Created by wangchongjie on 16/4/11. */ public class TaskClientFactory { private static SessionIdProvider idProvider = new DefaultSessionIdProvider("TaskClient");
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/HostConf.java // public class HostConf { // // private String host = System.getProperty("host", "127.0.0.1"); // private int port = Integer.parseInt(System.getProperty("port", "8007")); // private boolean ssl = System.getProperty("ssl") != null; // // public HostConf() { // try { // InetAddress addr = InetAddress.getLocalHost(); // host = addr.getHostAddress(); // } catch (UnknownHostException e) { // // do nothing // } // } // // public HostConf(String host, int port) { // this(); // this.host = host; // this.port = port; // } // // @Override // public boolean equals(Object obj) { // if (!(obj instanceof HostConf)) { // return false; // } // HostConf other = (HostConf) obj; // return this.host.equals(other.getHost()) && this.port == other.getPort() && this.ssl == other.isSsl(); // } // // @Override // public int hashCode() { // return this.host.hashCode() + this.host.hashCode(); // } // // public static List<HostConf> resolveHost(String hosts) { // List<HostConf> hostConfs = new ArrayList<HostConf>(); // if (StringUtils.isEmpty(hosts)) { // return hostConfs; // } // String[] hostStrs = hosts.split(";"); // for (String host : hostStrs) { // String ip = host.replaceAll(":.*", ""); // String port = host.replaceAll(".*:", ""); // hostConfs.add(new HostConf(ip, Integer.parseInt(port))); // } // return hostConfs; // } // // public static List<HostConf> resolvePort(String ports) { // // List<HostConf> hostConfs = new ArrayList<HostConf>(); // if (StringUtils.isEmpty(ports)) { // return hostConfs; // } // String[] ps = ports.split(";"); // for (String port : ps) { // HostConf hostConf = new HostConf(); // hostConf.setPort(Integer.parseInt(port)); // hostConfs.add(hostConf); // } // return hostConfs; // } // // public String info() { // StringBuilder sb = new StringBuilder(); // sb.append(this.getHost()).append(":").append(this.getPort()); // return sb.toString(); // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public boolean isSsl() { // return ssl; // } // // public void setSsl(boolean ssl) { // this.ssl = ssl; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/DefaultSessionIdProvider.java // public class DefaultSessionIdProvider implements SessionIdProvider, Cloneable { // private String prefix; // private volatile String currentSessionId; // // /** // * 无参数构造方法 // */ // public DefaultSessionIdProvider() { // } // // /** // * 构造方法 // * // * @param prefix sessionid前缀 // */ // public DefaultSessionIdProvider(String prefix) { // this.prefix = prefix; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // // // @Override // public String getSessionId(boolean refresh) { // if (refresh) { // currentSessionId = genSessionId(); // } // return currentSessionId; // } // // /** // * 生成uuid session // * // * @return session // */ // private String genSessionId() { // if (prefix == null) { // return UUID.randomUUID().toString(); // } else { // return prefix + "_" + UUID.randomUUID().toString(); // } // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/SequenceIdGen.java // public class SequenceIdGen { // private AtomicLong counter = new AtomicLong(0); // // public long genId() { // long v = counter.incrementAndGet(); // if (v < 0) { // v &= Long.MAX_VALUE; // } // if (v == 0) { // return genId(); // } // return v; // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/SessionIdProvider.java // public interface SessionIdProvider { // /** // * 获取sessionid // * // * @param refresh 是否刷新新session id // * @return session id // */ // String getSessionId(boolean refresh); // // } // Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClientFactory.java import com.baidu.unbiz.multiengine.endpoint.HostConf; import com.baidu.unbiz.multiengine.transport.DefaultSessionIdProvider; import com.baidu.unbiz.multiengine.transport.SequenceIdGen; import com.baidu.unbiz.multiengine.transport.SessionIdProvider; package com.baidu.unbiz.multiengine.transport.client; /** * Created by wangchongjie on 16/4/11. */ public class TaskClientFactory { private static SessionIdProvider idProvider = new DefaultSessionIdProvider("TaskClient");
public static TaskClient createTaskClient(HostConf hostConf) {
wangchongjie/multi-engine
src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClientFactory.java
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/HostConf.java // public class HostConf { // // private String host = System.getProperty("host", "127.0.0.1"); // private int port = Integer.parseInt(System.getProperty("port", "8007")); // private boolean ssl = System.getProperty("ssl") != null; // // public HostConf() { // try { // InetAddress addr = InetAddress.getLocalHost(); // host = addr.getHostAddress(); // } catch (UnknownHostException e) { // // do nothing // } // } // // public HostConf(String host, int port) { // this(); // this.host = host; // this.port = port; // } // // @Override // public boolean equals(Object obj) { // if (!(obj instanceof HostConf)) { // return false; // } // HostConf other = (HostConf) obj; // return this.host.equals(other.getHost()) && this.port == other.getPort() && this.ssl == other.isSsl(); // } // // @Override // public int hashCode() { // return this.host.hashCode() + this.host.hashCode(); // } // // public static List<HostConf> resolveHost(String hosts) { // List<HostConf> hostConfs = new ArrayList<HostConf>(); // if (StringUtils.isEmpty(hosts)) { // return hostConfs; // } // String[] hostStrs = hosts.split(";"); // for (String host : hostStrs) { // String ip = host.replaceAll(":.*", ""); // String port = host.replaceAll(".*:", ""); // hostConfs.add(new HostConf(ip, Integer.parseInt(port))); // } // return hostConfs; // } // // public static List<HostConf> resolvePort(String ports) { // // List<HostConf> hostConfs = new ArrayList<HostConf>(); // if (StringUtils.isEmpty(ports)) { // return hostConfs; // } // String[] ps = ports.split(";"); // for (String port : ps) { // HostConf hostConf = new HostConf(); // hostConf.setPort(Integer.parseInt(port)); // hostConfs.add(hostConf); // } // return hostConfs; // } // // public String info() { // StringBuilder sb = new StringBuilder(); // sb.append(this.getHost()).append(":").append(this.getPort()); // return sb.toString(); // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public boolean isSsl() { // return ssl; // } // // public void setSsl(boolean ssl) { // this.ssl = ssl; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/DefaultSessionIdProvider.java // public class DefaultSessionIdProvider implements SessionIdProvider, Cloneable { // private String prefix; // private volatile String currentSessionId; // // /** // * 无参数构造方法 // */ // public DefaultSessionIdProvider() { // } // // /** // * 构造方法 // * // * @param prefix sessionid前缀 // */ // public DefaultSessionIdProvider(String prefix) { // this.prefix = prefix; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // // // @Override // public String getSessionId(boolean refresh) { // if (refresh) { // currentSessionId = genSessionId(); // } // return currentSessionId; // } // // /** // * 生成uuid session // * // * @return session // */ // private String genSessionId() { // if (prefix == null) { // return UUID.randomUUID().toString(); // } else { // return prefix + "_" + UUID.randomUUID().toString(); // } // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/SequenceIdGen.java // public class SequenceIdGen { // private AtomicLong counter = new AtomicLong(0); // // public long genId() { // long v = counter.incrementAndGet(); // if (v < 0) { // v &= Long.MAX_VALUE; // } // if (v == 0) { // return genId(); // } // return v; // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/SessionIdProvider.java // public interface SessionIdProvider { // /** // * 获取sessionid // * // * @param refresh 是否刷新新session id // * @return session id // */ // String getSessionId(boolean refresh); // // }
import com.baidu.unbiz.multiengine.endpoint.HostConf; import com.baidu.unbiz.multiengine.transport.DefaultSessionIdProvider; import com.baidu.unbiz.multiengine.transport.SequenceIdGen; import com.baidu.unbiz.multiengine.transport.SessionIdProvider;
package com.baidu.unbiz.multiengine.transport.client; /** * Created by wangchongjie on 16/4/11. */ public class TaskClientFactory { private static SessionIdProvider idProvider = new DefaultSessionIdProvider("TaskClient"); public static TaskClient createTaskClient(HostConf hostConf) { TaskClient taskClient = new TaskClient(hostConf);
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/HostConf.java // public class HostConf { // // private String host = System.getProperty("host", "127.0.0.1"); // private int port = Integer.parseInt(System.getProperty("port", "8007")); // private boolean ssl = System.getProperty("ssl") != null; // // public HostConf() { // try { // InetAddress addr = InetAddress.getLocalHost(); // host = addr.getHostAddress(); // } catch (UnknownHostException e) { // // do nothing // } // } // // public HostConf(String host, int port) { // this(); // this.host = host; // this.port = port; // } // // @Override // public boolean equals(Object obj) { // if (!(obj instanceof HostConf)) { // return false; // } // HostConf other = (HostConf) obj; // return this.host.equals(other.getHost()) && this.port == other.getPort() && this.ssl == other.isSsl(); // } // // @Override // public int hashCode() { // return this.host.hashCode() + this.host.hashCode(); // } // // public static List<HostConf> resolveHost(String hosts) { // List<HostConf> hostConfs = new ArrayList<HostConf>(); // if (StringUtils.isEmpty(hosts)) { // return hostConfs; // } // String[] hostStrs = hosts.split(";"); // for (String host : hostStrs) { // String ip = host.replaceAll(":.*", ""); // String port = host.replaceAll(".*:", ""); // hostConfs.add(new HostConf(ip, Integer.parseInt(port))); // } // return hostConfs; // } // // public static List<HostConf> resolvePort(String ports) { // // List<HostConf> hostConfs = new ArrayList<HostConf>(); // if (StringUtils.isEmpty(ports)) { // return hostConfs; // } // String[] ps = ports.split(";"); // for (String port : ps) { // HostConf hostConf = new HostConf(); // hostConf.setPort(Integer.parseInt(port)); // hostConfs.add(hostConf); // } // return hostConfs; // } // // public String info() { // StringBuilder sb = new StringBuilder(); // sb.append(this.getHost()).append(":").append(this.getPort()); // return sb.toString(); // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public boolean isSsl() { // return ssl; // } // // public void setSsl(boolean ssl) { // this.ssl = ssl; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/DefaultSessionIdProvider.java // public class DefaultSessionIdProvider implements SessionIdProvider, Cloneable { // private String prefix; // private volatile String currentSessionId; // // /** // * 无参数构造方法 // */ // public DefaultSessionIdProvider() { // } // // /** // * 构造方法 // * // * @param prefix sessionid前缀 // */ // public DefaultSessionIdProvider(String prefix) { // this.prefix = prefix; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // // // @Override // public String getSessionId(boolean refresh) { // if (refresh) { // currentSessionId = genSessionId(); // } // return currentSessionId; // } // // /** // * 生成uuid session // * // * @return session // */ // private String genSessionId() { // if (prefix == null) { // return UUID.randomUUID().toString(); // } else { // return prefix + "_" + UUID.randomUUID().toString(); // } // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/SequenceIdGen.java // public class SequenceIdGen { // private AtomicLong counter = new AtomicLong(0); // // public long genId() { // long v = counter.incrementAndGet(); // if (v < 0) { // v &= Long.MAX_VALUE; // } // if (v == 0) { // return genId(); // } // return v; // } // // } // // Path: src/main/java/com/baidu/unbiz/multiengine/transport/SessionIdProvider.java // public interface SessionIdProvider { // /** // * 获取sessionid // * // * @param refresh 是否刷新新session id // * @return session id // */ // String getSessionId(boolean refresh); // // } // Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClientFactory.java import com.baidu.unbiz.multiengine.endpoint.HostConf; import com.baidu.unbiz.multiengine.transport.DefaultSessionIdProvider; import com.baidu.unbiz.multiengine.transport.SequenceIdGen; import com.baidu.unbiz.multiengine.transport.SessionIdProvider; package com.baidu.unbiz.multiengine.transport.client; /** * Created by wangchongjie on 16/4/11. */ public class TaskClientFactory { private static SessionIdProvider idProvider = new DefaultSessionIdProvider("TaskClient"); public static TaskClient createTaskClient(HostConf hostConf) { TaskClient taskClient = new TaskClient(hostConf);
taskClient.setIdGen(new SequenceIdGen());
wangchongjie/multi-engine
src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer2.java
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java // public class DefaultEndpointSupervisor implements EndpointSupervisor { // private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class); // // private static List<TaskServer> taskServers; // private GossipSupport gossipSupport; // private HeartbeatSupport heartbeatSupport; // // private String exportPort; // private String serverHost; // // public DefaultEndpointSupervisor() { // taskServers = new CopyOnWriteArrayList<TaskServer>(); // gossipSupport = new GossipSupport(); // heartbeatSupport = new HeartbeatSupport() { // @Override // public void tryRestartEndpoint(TaskClient taskClient) { // doTryRestartEndpoint(taskClient); // } // }; // } // // public static List<HostConf> getTaskHostConf() { // List<HostConf> hostConfs = new ArrayList<HostConf>(); // // fixme // // for(TaskServer taskServer : taskServers){ // // hostConfs.internalAdd(taskServer.getHostConf()); // // } // hostConfs.addAll(EndpointPool.getTaskHostConf()); // return hostConfs; // } // // public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) { // List<HostConf> hostConfs = getTaskHostConf(); // otherHost.removeAll(hostConfs); // EndpointPool.add(otherHost); // return hostConfs; // } // // /** // * default: heartbeat and gossip // */ // @Override // public void init() { // List<HostConf> exportHosts = HostConf.resolvePort(exportPort); // for (HostConf hostConf : exportHosts) { // TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf); // taskServer.start(); // taskServers.add(taskServer); // } // List<HostConf> clientHost = HostConf.resolveHost(this.serverHost); // EndpointPool.init(clientHost); // // heartbeatSupport.scheduleHeartbeat(); // gossipSupport.scheduleGossip(); // } // // @Override // public void stop() { // EndpointPool.stop(); // if (CollectionUtils.isEmpty(taskServers)) { // return; // } // for (TaskServer taskServer : taskServers) { // taskServer.stop(); // } // // heartbeatSupport.shutdownScheduler(); // gossipSupport.shutdownScheduler(); // } // // protected void doTryRestartEndpoint(TaskClient taskClient) { // try { // taskClient.restart(); // } catch (Exception e) { // // do nothing // } // } // // public String getServerHost() { // return serverHost; // } // // public void setServerHost(String serverHost) { // this.serverHost = serverHost; // } // // public String getExportPort() { // return exportPort; // } // // public void setExportPort(String exportPort) { // this.exportPort = exportPort; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java // public class TestUtils { // public static final long VERY_LONG_TIME = 2000 * 1000; // // public static void dumySleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) { // // do nothing // } // } // }
import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor; import com.baidu.unbiz.multiengine.utils.TestUtils;
package com.baidu.unbiz.multiengine.demo.test; /** * Created by wangchongjie on 16/4/18. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "/applicationContext-test2.xml") public class TestMultiProcessServer2 {
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java // public class DefaultEndpointSupervisor implements EndpointSupervisor { // private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class); // // private static List<TaskServer> taskServers; // private GossipSupport gossipSupport; // private HeartbeatSupport heartbeatSupport; // // private String exportPort; // private String serverHost; // // public DefaultEndpointSupervisor() { // taskServers = new CopyOnWriteArrayList<TaskServer>(); // gossipSupport = new GossipSupport(); // heartbeatSupport = new HeartbeatSupport() { // @Override // public void tryRestartEndpoint(TaskClient taskClient) { // doTryRestartEndpoint(taskClient); // } // }; // } // // public static List<HostConf> getTaskHostConf() { // List<HostConf> hostConfs = new ArrayList<HostConf>(); // // fixme // // for(TaskServer taskServer : taskServers){ // // hostConfs.internalAdd(taskServer.getHostConf()); // // } // hostConfs.addAll(EndpointPool.getTaskHostConf()); // return hostConfs; // } // // public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) { // List<HostConf> hostConfs = getTaskHostConf(); // otherHost.removeAll(hostConfs); // EndpointPool.add(otherHost); // return hostConfs; // } // // /** // * default: heartbeat and gossip // */ // @Override // public void init() { // List<HostConf> exportHosts = HostConf.resolvePort(exportPort); // for (HostConf hostConf : exportHosts) { // TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf); // taskServer.start(); // taskServers.add(taskServer); // } // List<HostConf> clientHost = HostConf.resolveHost(this.serverHost); // EndpointPool.init(clientHost); // // heartbeatSupport.scheduleHeartbeat(); // gossipSupport.scheduleGossip(); // } // // @Override // public void stop() { // EndpointPool.stop(); // if (CollectionUtils.isEmpty(taskServers)) { // return; // } // for (TaskServer taskServer : taskServers) { // taskServer.stop(); // } // // heartbeatSupport.shutdownScheduler(); // gossipSupport.shutdownScheduler(); // } // // protected void doTryRestartEndpoint(TaskClient taskClient) { // try { // taskClient.restart(); // } catch (Exception e) { // // do nothing // } // } // // public String getServerHost() { // return serverHost; // } // // public void setServerHost(String serverHost) { // this.serverHost = serverHost; // } // // public String getExportPort() { // return exportPort; // } // // public void setExportPort(String exportPort) { // this.exportPort = exportPort; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java // public class TestUtils { // public static final long VERY_LONG_TIME = 2000 * 1000; // // public static void dumySleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) { // // do nothing // } // } // } // Path: src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer2.java import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor; import com.baidu.unbiz.multiengine.utils.TestUtils; package com.baidu.unbiz.multiengine.demo.test; /** * Created by wangchongjie on 16/4/18. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "/applicationContext-test2.xml") public class TestMultiProcessServer2 {
private DefaultEndpointSupervisor supervisor = new DefaultEndpointSupervisor();
wangchongjie/multi-engine
src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer2.java
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java // public class DefaultEndpointSupervisor implements EndpointSupervisor { // private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class); // // private static List<TaskServer> taskServers; // private GossipSupport gossipSupport; // private HeartbeatSupport heartbeatSupport; // // private String exportPort; // private String serverHost; // // public DefaultEndpointSupervisor() { // taskServers = new CopyOnWriteArrayList<TaskServer>(); // gossipSupport = new GossipSupport(); // heartbeatSupport = new HeartbeatSupport() { // @Override // public void tryRestartEndpoint(TaskClient taskClient) { // doTryRestartEndpoint(taskClient); // } // }; // } // // public static List<HostConf> getTaskHostConf() { // List<HostConf> hostConfs = new ArrayList<HostConf>(); // // fixme // // for(TaskServer taskServer : taskServers){ // // hostConfs.internalAdd(taskServer.getHostConf()); // // } // hostConfs.addAll(EndpointPool.getTaskHostConf()); // return hostConfs; // } // // public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) { // List<HostConf> hostConfs = getTaskHostConf(); // otherHost.removeAll(hostConfs); // EndpointPool.add(otherHost); // return hostConfs; // } // // /** // * default: heartbeat and gossip // */ // @Override // public void init() { // List<HostConf> exportHosts = HostConf.resolvePort(exportPort); // for (HostConf hostConf : exportHosts) { // TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf); // taskServer.start(); // taskServers.add(taskServer); // } // List<HostConf> clientHost = HostConf.resolveHost(this.serverHost); // EndpointPool.init(clientHost); // // heartbeatSupport.scheduleHeartbeat(); // gossipSupport.scheduleGossip(); // } // // @Override // public void stop() { // EndpointPool.stop(); // if (CollectionUtils.isEmpty(taskServers)) { // return; // } // for (TaskServer taskServer : taskServers) { // taskServer.stop(); // } // // heartbeatSupport.shutdownScheduler(); // gossipSupport.shutdownScheduler(); // } // // protected void doTryRestartEndpoint(TaskClient taskClient) { // try { // taskClient.restart(); // } catch (Exception e) { // // do nothing // } // } // // public String getServerHost() { // return serverHost; // } // // public void setServerHost(String serverHost) { // this.serverHost = serverHost; // } // // public String getExportPort() { // return exportPort; // } // // public void setExportPort(String exportPort) { // this.exportPort = exportPort; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java // public class TestUtils { // public static final long VERY_LONG_TIME = 2000 * 1000; // // public static void dumySleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) { // // do nothing // } // } // }
import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor; import com.baidu.unbiz.multiengine.utils.TestUtils;
package com.baidu.unbiz.multiengine.demo.test; /** * Created by wangchongjie on 16/4/18. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "/applicationContext-test2.xml") public class TestMultiProcessServer2 { private DefaultEndpointSupervisor supervisor = new DefaultEndpointSupervisor(); @Before public void init() { supervisor.setExportPort("8802"); supervisor.setServerHost("127.0.0.1:8801;127.0.0.1:8802"); supervisor.init(); } @After public void clean() { supervisor.stop(); } /** * 测试分布式并行执行task */ @Test public void runServer() {
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java // public class DefaultEndpointSupervisor implements EndpointSupervisor { // private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class); // // private static List<TaskServer> taskServers; // private GossipSupport gossipSupport; // private HeartbeatSupport heartbeatSupport; // // private String exportPort; // private String serverHost; // // public DefaultEndpointSupervisor() { // taskServers = new CopyOnWriteArrayList<TaskServer>(); // gossipSupport = new GossipSupport(); // heartbeatSupport = new HeartbeatSupport() { // @Override // public void tryRestartEndpoint(TaskClient taskClient) { // doTryRestartEndpoint(taskClient); // } // }; // } // // public static List<HostConf> getTaskHostConf() { // List<HostConf> hostConfs = new ArrayList<HostConf>(); // // fixme // // for(TaskServer taskServer : taskServers){ // // hostConfs.internalAdd(taskServer.getHostConf()); // // } // hostConfs.addAll(EndpointPool.getTaskHostConf()); // return hostConfs; // } // // public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) { // List<HostConf> hostConfs = getTaskHostConf(); // otherHost.removeAll(hostConfs); // EndpointPool.add(otherHost); // return hostConfs; // } // // /** // * default: heartbeat and gossip // */ // @Override // public void init() { // List<HostConf> exportHosts = HostConf.resolvePort(exportPort); // for (HostConf hostConf : exportHosts) { // TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf); // taskServer.start(); // taskServers.add(taskServer); // } // List<HostConf> clientHost = HostConf.resolveHost(this.serverHost); // EndpointPool.init(clientHost); // // heartbeatSupport.scheduleHeartbeat(); // gossipSupport.scheduleGossip(); // } // // @Override // public void stop() { // EndpointPool.stop(); // if (CollectionUtils.isEmpty(taskServers)) { // return; // } // for (TaskServer taskServer : taskServers) { // taskServer.stop(); // } // // heartbeatSupport.shutdownScheduler(); // gossipSupport.shutdownScheduler(); // } // // protected void doTryRestartEndpoint(TaskClient taskClient) { // try { // taskClient.restart(); // } catch (Exception e) { // // do nothing // } // } // // public String getServerHost() { // return serverHost; // } // // public void setServerHost(String serverHost) { // this.serverHost = serverHost; // } // // public String getExportPort() { // return exportPort; // } // // public void setExportPort(String exportPort) { // this.exportPort = exportPort; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java // public class TestUtils { // public static final long VERY_LONG_TIME = 2000 * 1000; // // public static void dumySleep(long time) { // try { // Thread.sleep(time); // } catch (InterruptedException e) { // // do nothing // } // } // } // Path: src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer2.java import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor; import com.baidu.unbiz.multiengine.utils.TestUtils; package com.baidu.unbiz.multiengine.demo.test; /** * Created by wangchongjie on 16/4/18. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "/applicationContext-test2.xml") public class TestMultiProcessServer2 { private DefaultEndpointSupervisor supervisor = new DefaultEndpointSupervisor(); @Before public void init() { supervisor.setExportPort("8802"); supervisor.setServerHost("127.0.0.1:8801;127.0.0.1:8802"); supervisor.init(); } @After public void clean() { supervisor.stop(); } /** * 测试分布式并行执行task */ @Test public void runServer() {
TestUtils.dumySleep(TestUtils.VERY_LONG_TIME);
wangchongjie/multi-engine
src/main/java/com/baidu/unbiz/multiengine/codec/common/ProtostuffCodec.java
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java // public interface MsgCodec { // /** // * 反序列化 // * // * @param clazz 反序列化后的类定义 // * @param bytes 字节码 // * @return 反序列化后的对象 // * @throws CodecException // */ // <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException; // // /** // * 序列化 // * // * @param object 待序列化的对象 // * @return 字节码 // * @throws CodecException // */ // <T> byte[] encode(T object) throws CodecException; // } // // Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java // public class CodecException extends RuntimeException { // // /** // * serialVersionUID // */ // private static final long serialVersionUID = 5196421433506179782L; // // /** // * Creates a new instance of CodecException. // */ // public CodecException() { // super(); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // * @param arg1 // */ // public CodecException(String arg0, Throwable arg1) { // super(arg0, arg1); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(String arg0) { // super(arg0); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(Throwable arg0) { // super(arg0); // } // // }
import com.baidu.unbiz.devlib.reflection.ReflectionUtil; import com.baidu.unbiz.multiengine.codec.MsgCodec; import com.baidu.unbiz.multiengine.exception.CodecException; import com.dyuproject.protostuff.LinkedBuffer; import com.dyuproject.protostuff.ProtobufIOUtil; import com.dyuproject.protostuff.Schema; import com.dyuproject.protostuff.runtime.RuntimeSchema;
package com.baidu.unbiz.multiengine.codec.common; /** * ClassName: ProtobufCodec <br/> * Function: protobuf序列化器,利用反射缓存<tt>method</tt>来进行调用 */ public class ProtostuffCodec implements MsgCodec { /** * 设置编码规则 */ static { System.setProperty("protostuff.runtime.collection_schema_on_repeated_fields", "true"); System.setProperty("protostuff.runtime.morph_collection_interfaces", "true"); System.setProperty("protostuff.runtime.morph_map_interfaces", "true"); } /** * 缓冲区 */ private ThreadLocal<LinkedBuffer> linkedBuffer = new ThreadLocal<LinkedBuffer>() { @Override protected LinkedBuffer initialValue() { return LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); } }; @Override
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java // public interface MsgCodec { // /** // * 反序列化 // * // * @param clazz 反序列化后的类定义 // * @param bytes 字节码 // * @return 反序列化后的对象 // * @throws CodecException // */ // <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException; // // /** // * 序列化 // * // * @param object 待序列化的对象 // * @return 字节码 // * @throws CodecException // */ // <T> byte[] encode(T object) throws CodecException; // } // // Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java // public class CodecException extends RuntimeException { // // /** // * serialVersionUID // */ // private static final long serialVersionUID = 5196421433506179782L; // // /** // * Creates a new instance of CodecException. // */ // public CodecException() { // super(); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // * @param arg1 // */ // public CodecException(String arg0, Throwable arg1) { // super(arg0, arg1); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(String arg0) { // super(arg0); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(Throwable arg0) { // super(arg0); // } // // } // Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/ProtostuffCodec.java import com.baidu.unbiz.devlib.reflection.ReflectionUtil; import com.baidu.unbiz.multiengine.codec.MsgCodec; import com.baidu.unbiz.multiengine.exception.CodecException; import com.dyuproject.protostuff.LinkedBuffer; import com.dyuproject.protostuff.ProtobufIOUtil; import com.dyuproject.protostuff.Schema; import com.dyuproject.protostuff.runtime.RuntimeSchema; package com.baidu.unbiz.multiengine.codec.common; /** * ClassName: ProtobufCodec <br/> * Function: protobuf序列化器,利用反射缓存<tt>method</tt>来进行调用 */ public class ProtostuffCodec implements MsgCodec { /** * 设置编码规则 */ static { System.setProperty("protostuff.runtime.collection_schema_on_repeated_fields", "true"); System.setProperty("protostuff.runtime.morph_collection_interfaces", "true"); System.setProperty("protostuff.runtime.morph_map_interfaces", "true"); } /** * 缓冲区 */ private ThreadLocal<LinkedBuffer> linkedBuffer = new ThreadLocal<LinkedBuffer>() { @Override protected LinkedBuffer initialValue() { return LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); } }; @Override
public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException {
wangchongjie/multi-engine
src/main/java/com/baidu/unbiz/multiengine/codec/common/JsonCodec.java
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java // public interface MsgCodec { // /** // * 反序列化 // * // * @param clazz 反序列化后的类定义 // * @param bytes 字节码 // * @return 反序列化后的对象 // * @throws CodecException // */ // <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException; // // /** // * 序列化 // * // * @param object 待序列化的对象 // * @return 字节码 // * @throws CodecException // */ // <T> byte[] encode(T object) throws CodecException; // } // // Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java // public class CodecException extends RuntimeException { // // /** // * serialVersionUID // */ // private static final long serialVersionUID = 5196421433506179782L; // // /** // * Creates a new instance of CodecException. // */ // public CodecException() { // super(); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // * @param arg1 // */ // public CodecException(String arg0, Throwable arg1) { // super(arg0, arg1); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(String arg0) { // super(arg0); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(Throwable arg0) { // super(arg0); // } // // }
import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import com.baidu.unbiz.multiengine.codec.MsgCodec; import com.baidu.unbiz.multiengine.exception.CodecException;
package com.baidu.unbiz.multiengine.codec.common; /** * JSON格式的消息编解码 */ public class JsonCodec implements MsgCodec { /** * 对象匹配映射 */ private final ObjectMapper mapper; public JsonCodec() { mapper = new ObjectMapper(); // ignoring unknown properties makes us more robust to changes in the schema mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // This will allow including type information all non-final types. This allows correct // serialization/deserialization of generic collections, for example List<MyType>. mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); } @Override
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java // public interface MsgCodec { // /** // * 反序列化 // * // * @param clazz 反序列化后的类定义 // * @param bytes 字节码 // * @return 反序列化后的对象 // * @throws CodecException // */ // <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException; // // /** // * 序列化 // * // * @param object 待序列化的对象 // * @return 字节码 // * @throws CodecException // */ // <T> byte[] encode(T object) throws CodecException; // } // // Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java // public class CodecException extends RuntimeException { // // /** // * serialVersionUID // */ // private static final long serialVersionUID = 5196421433506179782L; // // /** // * Creates a new instance of CodecException. // */ // public CodecException() { // super(); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // * @param arg1 // */ // public CodecException(String arg0, Throwable arg1) { // super(arg0, arg1); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(String arg0) { // super(arg0); // } // // /** // * Creates a new instance of CodecException. // * // * @param arg0 // */ // public CodecException(Throwable arg0) { // super(arg0); // } // // } // Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/JsonCodec.java import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import com.baidu.unbiz.multiengine.codec.MsgCodec; import com.baidu.unbiz.multiengine.exception.CodecException; package com.baidu.unbiz.multiengine.codec.common; /** * JSON格式的消息编解码 */ public class JsonCodec implements MsgCodec { /** * 对象匹配映射 */ private final ObjectMapper mapper; public JsonCodec() { mapper = new ObjectMapper(); // ignoring unknown properties makes us more robust to changes in the schema mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // This will allow including type information all non-final types. This allows correct // serialization/deserialization of generic collections, for example List<MyType>. mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); } @Override
public byte[] encode(Object object) throws CodecException {
wangchongjie/multi-engine
src/test/java/com/baidu/unbiz/multiengine/service/DevicePlanStatServiceImpl.java
// Path: src/test/java/com/baidu/unbiz/multiengine/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // private static final long serialVersionUID = -7375423850222016116L; // // public BusinessException(String msg) { // super(msg); // } // // public BusinessException(Throwable cause) { // super(cause); // } // // public BusinessException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java // public class DeviceRequest { // // private List<Integer> deviceIds; // // public List<Integer> getDeviceIds() { // return deviceIds; // } // // public void setDeviceIds(List<Integer> deviceIds) { // this.deviceIds = deviceIds; // } // // public static DeviceRequest build(QueryParam target) { // DeviceRequest req = new DeviceRequest(); // // req.copyProperties(target); // return req; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java // public class DeviceViewItem { // // private static final long serialVersionUID = 6132709579470894604L; // // private int planId; // // private String planName; // // private Integer deviceId; // // private String deviceName ; // // // getter and setter // public int getPlanId() { // return planId; // } // // public void setPlanId(int planId) { // this.planId = planId; // } // // public Integer getDeviceId() { // return deviceId; // } // // public void setDeviceId(Integer deviceId) { // this.deviceId = deviceId; // } // // public String getPlanName() { // return planName; // } // // public void setPlanName(String planName) { // this.planName = planName; // } // // public String getDeviceName() { // return deviceName; // } // // public void setDeviceName(String deviceName) { // this.deviceName = deviceName; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // }
import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.baidu.unbiz.multiengine.exception.BusinessException; import com.baidu.unbiz.multiengine.vo.DeviceRequest; import com.baidu.unbiz.multiengine.vo.DeviceViewItem; import com.baidu.unbiz.multitask.annotation.TaskBean; import com.baidu.unbiz.multitask.annotation.TaskService;
package com.baidu.unbiz.multiengine.service; /** * 该类会被并行组件监测到,并将其方法包装成可并行执行的Fetcher */ @TaskService public class DevicePlanStatServiceImpl implements DevicePlanStatService { private static final Log LOG = LogFactory.getLog(DevicePlanStatServiceImpl.class); /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("deviceStatFetcher")
// Path: src/test/java/com/baidu/unbiz/multiengine/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // private static final long serialVersionUID = -7375423850222016116L; // // public BusinessException(String msg) { // super(msg); // } // // public BusinessException(Throwable cause) { // super(cause); // } // // public BusinessException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java // public class DeviceRequest { // // private List<Integer> deviceIds; // // public List<Integer> getDeviceIds() { // return deviceIds; // } // // public void setDeviceIds(List<Integer> deviceIds) { // this.deviceIds = deviceIds; // } // // public static DeviceRequest build(QueryParam target) { // DeviceRequest req = new DeviceRequest(); // // req.copyProperties(target); // return req; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java // public class DeviceViewItem { // // private static final long serialVersionUID = 6132709579470894604L; // // private int planId; // // private String planName; // // private Integer deviceId; // // private String deviceName ; // // // getter and setter // public int getPlanId() { // return planId; // } // // public void setPlanId(int planId) { // this.planId = planId; // } // // public Integer getDeviceId() { // return deviceId; // } // // public void setDeviceId(Integer deviceId) { // this.deviceId = deviceId; // } // // public String getPlanName() { // return planName; // } // // public void setPlanName(String planName) { // this.planName = planName; // } // // public String getDeviceName() { // return deviceName; // } // // public void setDeviceName(String deviceName) { // this.deviceName = deviceName; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // } // Path: src/test/java/com/baidu/unbiz/multiengine/service/DevicePlanStatServiceImpl.java import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.baidu.unbiz.multiengine.exception.BusinessException; import com.baidu.unbiz.multiengine.vo.DeviceRequest; import com.baidu.unbiz.multiengine.vo.DeviceViewItem; import com.baidu.unbiz.multitask.annotation.TaskBean; import com.baidu.unbiz.multitask.annotation.TaskService; package com.baidu.unbiz.multiengine.service; /** * 该类会被并行组件监测到,并将其方法包装成可并行执行的Fetcher */ @TaskService public class DevicePlanStatServiceImpl implements DevicePlanStatService { private static final Log LOG = LogFactory.getLog(DevicePlanStatServiceImpl.class); /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("deviceStatFetcher")
public List<DeviceViewItem> queryPlanDeviceData(DeviceRequest req) {
wangchongjie/multi-engine
src/test/java/com/baidu/unbiz/multiengine/service/DevicePlanStatServiceImpl.java
// Path: src/test/java/com/baidu/unbiz/multiengine/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // private static final long serialVersionUID = -7375423850222016116L; // // public BusinessException(String msg) { // super(msg); // } // // public BusinessException(Throwable cause) { // super(cause); // } // // public BusinessException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java // public class DeviceRequest { // // private List<Integer> deviceIds; // // public List<Integer> getDeviceIds() { // return deviceIds; // } // // public void setDeviceIds(List<Integer> deviceIds) { // this.deviceIds = deviceIds; // } // // public static DeviceRequest build(QueryParam target) { // DeviceRequest req = new DeviceRequest(); // // req.copyProperties(target); // return req; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java // public class DeviceViewItem { // // private static final long serialVersionUID = 6132709579470894604L; // // private int planId; // // private String planName; // // private Integer deviceId; // // private String deviceName ; // // // getter and setter // public int getPlanId() { // return planId; // } // // public void setPlanId(int planId) { // this.planId = planId; // } // // public Integer getDeviceId() { // return deviceId; // } // // public void setDeviceId(Integer deviceId) { // this.deviceId = deviceId; // } // // public String getPlanName() { // return planName; // } // // public void setPlanName(String planName) { // this.planName = planName; // } // // public String getDeviceName() { // return deviceName; // } // // public void setDeviceName(String deviceName) { // this.deviceName = deviceName; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // }
import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.baidu.unbiz.multiengine.exception.BusinessException; import com.baidu.unbiz.multiengine.vo.DeviceRequest; import com.baidu.unbiz.multiengine.vo.DeviceViewItem; import com.baidu.unbiz.multitask.annotation.TaskBean; import com.baidu.unbiz.multitask.annotation.TaskService;
package com.baidu.unbiz.multiengine.service; /** * 该类会被并行组件监测到,并将其方法包装成可并行执行的Fetcher */ @TaskService public class DevicePlanStatServiceImpl implements DevicePlanStatService { private static final Log LOG = LogFactory.getLog(DevicePlanStatServiceImpl.class); /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("deviceStatFetcher")
// Path: src/test/java/com/baidu/unbiz/multiengine/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // private static final long serialVersionUID = -7375423850222016116L; // // public BusinessException(String msg) { // super(msg); // } // // public BusinessException(Throwable cause) { // super(cause); // } // // public BusinessException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java // public class DeviceRequest { // // private List<Integer> deviceIds; // // public List<Integer> getDeviceIds() { // return deviceIds; // } // // public void setDeviceIds(List<Integer> deviceIds) { // this.deviceIds = deviceIds; // } // // public static DeviceRequest build(QueryParam target) { // DeviceRequest req = new DeviceRequest(); // // req.copyProperties(target); // return req; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java // public class DeviceViewItem { // // private static final long serialVersionUID = 6132709579470894604L; // // private int planId; // // private String planName; // // private Integer deviceId; // // private String deviceName ; // // // getter and setter // public int getPlanId() { // return planId; // } // // public void setPlanId(int planId) { // this.planId = planId; // } // // public Integer getDeviceId() { // return deviceId; // } // // public void setDeviceId(Integer deviceId) { // this.deviceId = deviceId; // } // // public String getPlanName() { // return planName; // } // // public void setPlanName(String planName) { // this.planName = planName; // } // // public String getDeviceName() { // return deviceName; // } // // public void setDeviceName(String deviceName) { // this.deviceName = deviceName; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // } // Path: src/test/java/com/baidu/unbiz/multiengine/service/DevicePlanStatServiceImpl.java import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.baidu.unbiz.multiengine.exception.BusinessException; import com.baidu.unbiz.multiengine.vo.DeviceRequest; import com.baidu.unbiz.multiengine.vo.DeviceViewItem; import com.baidu.unbiz.multitask.annotation.TaskBean; import com.baidu.unbiz.multitask.annotation.TaskService; package com.baidu.unbiz.multiengine.service; /** * 该类会被并行组件监测到,并将其方法包装成可并行执行的Fetcher */ @TaskService public class DevicePlanStatServiceImpl implements DevicePlanStatService { private static final Log LOG = LogFactory.getLog(DevicePlanStatServiceImpl.class); /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("deviceStatFetcher")
public List<DeviceViewItem> queryPlanDeviceData(DeviceRequest req) {
wangchongjie/multi-engine
src/test/java/com/baidu/unbiz/multiengine/service/DevicePlanStatServiceImpl.java
// Path: src/test/java/com/baidu/unbiz/multiengine/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // private static final long serialVersionUID = -7375423850222016116L; // // public BusinessException(String msg) { // super(msg); // } // // public BusinessException(Throwable cause) { // super(cause); // } // // public BusinessException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java // public class DeviceRequest { // // private List<Integer> deviceIds; // // public List<Integer> getDeviceIds() { // return deviceIds; // } // // public void setDeviceIds(List<Integer> deviceIds) { // this.deviceIds = deviceIds; // } // // public static DeviceRequest build(QueryParam target) { // DeviceRequest req = new DeviceRequest(); // // req.copyProperties(target); // return req; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java // public class DeviceViewItem { // // private static final long serialVersionUID = 6132709579470894604L; // // private int planId; // // private String planName; // // private Integer deviceId; // // private String deviceName ; // // // getter and setter // public int getPlanId() { // return planId; // } // // public void setPlanId(int planId) { // this.planId = planId; // } // // public Integer getDeviceId() { // return deviceId; // } // // public void setDeviceId(Integer deviceId) { // this.deviceId = deviceId; // } // // public String getPlanName() { // return planName; // } // // public void setPlanName(String planName) { // this.planName = planName; // } // // public String getDeviceName() { // return deviceName; // } // // public void setDeviceName(String deviceName) { // this.deviceName = deviceName; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // }
import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.baidu.unbiz.multiengine.exception.BusinessException; import com.baidu.unbiz.multiengine.vo.DeviceRequest; import com.baidu.unbiz.multiengine.vo.DeviceViewItem; import com.baidu.unbiz.multitask.annotation.TaskBean; import com.baidu.unbiz.multitask.annotation.TaskService;
package com.baidu.unbiz.multiengine.service; /** * 该类会被并行组件监测到,并将其方法包装成可并行执行的Fetcher */ @TaskService public class DevicePlanStatServiceImpl implements DevicePlanStatService { private static final Log LOG = LogFactory.getLog(DevicePlanStatServiceImpl.class); /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("deviceStatFetcher") public List<DeviceViewItem> queryPlanDeviceData(DeviceRequest req) { this.checkParam(req); // Test ThreadLocal LOG.debug("ThreadLocal" + MyThreadLocal.get()); return this.mockList1(); } /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("deviceBigDataStatFetcher") public List<DeviceViewItem> queryPlanDeviceDataWithBigData(DeviceRequest req) { this.checkParam(req); return this.mockList3(); } /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("deviceUvFetcher") public List<DeviceViewItem> queryPlanDeviceUvData(DeviceRequest req) { this.checkParam(req); return this.mockList2(); } /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("doSthVerySlowFetcher") public List<DeviceViewItem> queryPlanDeviceDataWithBadNetwork(DeviceRequest req) { try { Thread.sleep(900000L); } catch (InterruptedException e) { // do nothing, just for test } return this.mockList1(); } /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("doSthFailWithExceptionFetcher") public List<DeviceViewItem> queryPlanDeviceDataWithBusinessException(DeviceRequest req) {
// Path: src/test/java/com/baidu/unbiz/multiengine/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // private static final long serialVersionUID = -7375423850222016116L; // // public BusinessException(String msg) { // super(msg); // } // // public BusinessException(Throwable cause) { // super(cause); // } // // public BusinessException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java // public class DeviceRequest { // // private List<Integer> deviceIds; // // public List<Integer> getDeviceIds() { // return deviceIds; // } // // public void setDeviceIds(List<Integer> deviceIds) { // this.deviceIds = deviceIds; // } // // public static DeviceRequest build(QueryParam target) { // DeviceRequest req = new DeviceRequest(); // // req.copyProperties(target); // return req; // } // } // // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java // public class DeviceViewItem { // // private static final long serialVersionUID = 6132709579470894604L; // // private int planId; // // private String planName; // // private Integer deviceId; // // private String deviceName ; // // // getter and setter // public int getPlanId() { // return planId; // } // // public void setPlanId(int planId) { // this.planId = planId; // } // // public Integer getDeviceId() { // return deviceId; // } // // public void setDeviceId(Integer deviceId) { // this.deviceId = deviceId; // } // // public String getPlanName() { // return planName; // } // // public void setPlanName(String planName) { // this.planName = planName; // } // // public String getDeviceName() { // return deviceName; // } // // public void setDeviceName(String deviceName) { // this.deviceName = deviceName; // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // } // Path: src/test/java/com/baidu/unbiz/multiengine/service/DevicePlanStatServiceImpl.java import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.baidu.unbiz.multiengine.exception.BusinessException; import com.baidu.unbiz.multiengine.vo.DeviceRequest; import com.baidu.unbiz.multiengine.vo.DeviceViewItem; import com.baidu.unbiz.multitask.annotation.TaskBean; import com.baidu.unbiz.multitask.annotation.TaskService; package com.baidu.unbiz.multiengine.service; /** * 该类会被并行组件监测到,并将其方法包装成可并行执行的Fetcher */ @TaskService public class DevicePlanStatServiceImpl implements DevicePlanStatService { private static final Log LOG = LogFactory.getLog(DevicePlanStatServiceImpl.class); /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("deviceStatFetcher") public List<DeviceViewItem> queryPlanDeviceData(DeviceRequest req) { this.checkParam(req); // Test ThreadLocal LOG.debug("ThreadLocal" + MyThreadLocal.get()); return this.mockList1(); } /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("deviceBigDataStatFetcher") public List<DeviceViewItem> queryPlanDeviceDataWithBigData(DeviceRequest req) { this.checkParam(req); return this.mockList3(); } /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("deviceUvFetcher") public List<DeviceViewItem> queryPlanDeviceUvData(DeviceRequest req) { this.checkParam(req); return this.mockList2(); } /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("doSthVerySlowFetcher") public List<DeviceViewItem> queryPlanDeviceDataWithBadNetwork(DeviceRequest req) { try { Thread.sleep(900000L); } catch (InterruptedException e) { // do nothing, just for test } return this.mockList1(); } /** * 并行组件会将该方法包装成一个可并行执行的Fetcher */ @TaskBean("doSthFailWithExceptionFetcher") public List<DeviceViewItem> queryPlanDeviceDataWithBusinessException(DeviceRequest req) {
throw new BusinessException("Some business com.baidu.unbiz.multiengine.vo.exception, just for test!");
lsjwzh/FastTextView
app/src/main/java/com/wechat/testdemo/MainActivity.java
// Path: app/src/main/java/com/lsjwzh/test/FpsCalculator.java // public class FpsCalculator { // // private final static String TAG = "FpsCalculator"; // // private long mFrameIntervalNanos; // // private boolean mRunning = false; // // private static FpsCalculator instance; // // private AtomicInteger atom = new AtomicInteger(0); // private Thread syncCheckThread = null; // // static { // instance = new FpsCalculator(); // } // // public static FpsCalculator instance() { // return instance; // } // // private int totalFps; // private int fpsCalculateCount; // private boolean isCalculatingFPS; // // // calculate the average fps // // public void startCalculate() { // totalFps = 0; // fpsCalculateCount = 0; // isCalculatingFPS = true; // } // // public int stopGetAvgFPS() { // isCalculatingFPS = false; // int avgFPS = totalFps / fpsCalculateCount; // totalFps = 0; // fpsCalculateCount = 0; // return avgFPS; // } // // private void syncCheckThread(){ // if(!mRunning){ // return; // } // int val = atom.getAndSet(0); // if (isCalculatingFPS) { // totalFps += val; // fpsCalculateCount++; // } // android.util.Log.i(TAG, "FPS: " + val); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // private FrameCallback frameCallback = new FrameCallback() { // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // @Override // public void doFrame(long frameTimeNanos) { // // if (!mRunning) { // return; // } // // Choreographer.getInstance().postFrameCallback(frameCallback); // // atom.incrementAndGet(); // }}; // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public void start() { // Log.d(TAG, "start vsync detect"); // if (mRunning) { // return; // } // // mRunning = true; // // syncCheckThread = new Thread(new Runnable() { // @Override // public void run() { // for (;;) { // if (!mRunning) { // break; // } // syncCheckThread(); // } // } // }); // syncCheckThread.start(); // // Choreographer chor = Choreographer.getInstance(); // Field field; // try { // field = chor.getClass().getDeclaredField("mFrameIntervalNanos"); // field.setAccessible(true); // mFrameIntervalNanos = field.getLong(chor); // Log.d(TAG, "mFrameIntervalNanos " + mFrameIntervalNanos); // } catch (Exception e) { // Log.e(TAG, "error: " + e.getMessage()); // } // chor.postFrameCallback(frameCallback); // // } // // public void stop() { // mRunning = false; // if (syncCheckThread != null) { // try { // syncCheckThread.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // // Path: app/src/main/java/com/lsjwzh/test/GhostThread.java // public class GhostThread { // private static final String TAG = "GhostThread"; // // private static boolean isStart = false; // // private static Thread[] threads = new Thread[0]; // // private static Random random = new Random(); // private static Runnable runnable = new Runnable() { // @Override // public void run() { // for (; ;) { // if (!isStart) { // break; // } // double c = Math.PI * Math.PI * Math.PI * random.nextFloat(); // // Log.e("test", "v:" + c); // } // } // }; // // public static void start() { // if (isStart) { // return; // } // isStart = true; // for (int i = 0; i < threads.length; i++) { // Thread thread = new Thread(runnable); // thread.setPriority(Thread.NORM_PRIORITY); // thread.start(); // threads[i] = thread; // } // } // // public static void stop() { // isStart = false; // for (Thread thread : threads) { // try { // thread.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // }
import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.FragmentActivity; import android.view.View; import android.view.Menu; import android.view.MenuItem; import com.lsjwzh.test.FpsCalculator; import com.lsjwzh.test.GhostThread;
package com.wechat.testdemo; public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getSupportFragmentManager().popBackStackImmediate(); } }); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment, new MainActivityFragment()) .commit(); // GhostThread.start();
// Path: app/src/main/java/com/lsjwzh/test/FpsCalculator.java // public class FpsCalculator { // // private final static String TAG = "FpsCalculator"; // // private long mFrameIntervalNanos; // // private boolean mRunning = false; // // private static FpsCalculator instance; // // private AtomicInteger atom = new AtomicInteger(0); // private Thread syncCheckThread = null; // // static { // instance = new FpsCalculator(); // } // // public static FpsCalculator instance() { // return instance; // } // // private int totalFps; // private int fpsCalculateCount; // private boolean isCalculatingFPS; // // // calculate the average fps // // public void startCalculate() { // totalFps = 0; // fpsCalculateCount = 0; // isCalculatingFPS = true; // } // // public int stopGetAvgFPS() { // isCalculatingFPS = false; // int avgFPS = totalFps / fpsCalculateCount; // totalFps = 0; // fpsCalculateCount = 0; // return avgFPS; // } // // private void syncCheckThread(){ // if(!mRunning){ // return; // } // int val = atom.getAndSet(0); // if (isCalculatingFPS) { // totalFps += val; // fpsCalculateCount++; // } // android.util.Log.i(TAG, "FPS: " + val); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // private FrameCallback frameCallback = new FrameCallback() { // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // @Override // public void doFrame(long frameTimeNanos) { // // if (!mRunning) { // return; // } // // Choreographer.getInstance().postFrameCallback(frameCallback); // // atom.incrementAndGet(); // }}; // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public void start() { // Log.d(TAG, "start vsync detect"); // if (mRunning) { // return; // } // // mRunning = true; // // syncCheckThread = new Thread(new Runnable() { // @Override // public void run() { // for (;;) { // if (!mRunning) { // break; // } // syncCheckThread(); // } // } // }); // syncCheckThread.start(); // // Choreographer chor = Choreographer.getInstance(); // Field field; // try { // field = chor.getClass().getDeclaredField("mFrameIntervalNanos"); // field.setAccessible(true); // mFrameIntervalNanos = field.getLong(chor); // Log.d(TAG, "mFrameIntervalNanos " + mFrameIntervalNanos); // } catch (Exception e) { // Log.e(TAG, "error: " + e.getMessage()); // } // chor.postFrameCallback(frameCallback); // // } // // public void stop() { // mRunning = false; // if (syncCheckThread != null) { // try { // syncCheckThread.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // // Path: app/src/main/java/com/lsjwzh/test/GhostThread.java // public class GhostThread { // private static final String TAG = "GhostThread"; // // private static boolean isStart = false; // // private static Thread[] threads = new Thread[0]; // // private static Random random = new Random(); // private static Runnable runnable = new Runnable() { // @Override // public void run() { // for (; ;) { // if (!isStart) { // break; // } // double c = Math.PI * Math.PI * Math.PI * random.nextFloat(); // // Log.e("test", "v:" + c); // } // } // }; // // public static void start() { // if (isStart) { // return; // } // isStart = true; // for (int i = 0; i < threads.length; i++) { // Thread thread = new Thread(runnable); // thread.setPriority(Thread.NORM_PRIORITY); // thread.start(); // threads[i] = thread; // } // } // // public static void stop() { // isStart = false; // for (Thread thread : threads) { // try { // thread.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // Path: app/src/main/java/com/wechat/testdemo/MainActivity.java import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.FragmentActivity; import android.view.View; import android.view.Menu; import android.view.MenuItem; import com.lsjwzh.test.FpsCalculator; import com.lsjwzh.test.GhostThread; package com.wechat.testdemo; public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getSupportFragmentManager().popBackStackImmediate(); } }); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment, new MainActivityFragment()) .commit(); // GhostThread.start();
FpsCalculator.instance().start();
lsjwzh/FastTextView
app/src/main/java/com/wechat/testdemo/MainActivity.java
// Path: app/src/main/java/com/lsjwzh/test/FpsCalculator.java // public class FpsCalculator { // // private final static String TAG = "FpsCalculator"; // // private long mFrameIntervalNanos; // // private boolean mRunning = false; // // private static FpsCalculator instance; // // private AtomicInteger atom = new AtomicInteger(0); // private Thread syncCheckThread = null; // // static { // instance = new FpsCalculator(); // } // // public static FpsCalculator instance() { // return instance; // } // // private int totalFps; // private int fpsCalculateCount; // private boolean isCalculatingFPS; // // // calculate the average fps // // public void startCalculate() { // totalFps = 0; // fpsCalculateCount = 0; // isCalculatingFPS = true; // } // // public int stopGetAvgFPS() { // isCalculatingFPS = false; // int avgFPS = totalFps / fpsCalculateCount; // totalFps = 0; // fpsCalculateCount = 0; // return avgFPS; // } // // private void syncCheckThread(){ // if(!mRunning){ // return; // } // int val = atom.getAndSet(0); // if (isCalculatingFPS) { // totalFps += val; // fpsCalculateCount++; // } // android.util.Log.i(TAG, "FPS: " + val); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // private FrameCallback frameCallback = new FrameCallback() { // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // @Override // public void doFrame(long frameTimeNanos) { // // if (!mRunning) { // return; // } // // Choreographer.getInstance().postFrameCallback(frameCallback); // // atom.incrementAndGet(); // }}; // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public void start() { // Log.d(TAG, "start vsync detect"); // if (mRunning) { // return; // } // // mRunning = true; // // syncCheckThread = new Thread(new Runnable() { // @Override // public void run() { // for (;;) { // if (!mRunning) { // break; // } // syncCheckThread(); // } // } // }); // syncCheckThread.start(); // // Choreographer chor = Choreographer.getInstance(); // Field field; // try { // field = chor.getClass().getDeclaredField("mFrameIntervalNanos"); // field.setAccessible(true); // mFrameIntervalNanos = field.getLong(chor); // Log.d(TAG, "mFrameIntervalNanos " + mFrameIntervalNanos); // } catch (Exception e) { // Log.e(TAG, "error: " + e.getMessage()); // } // chor.postFrameCallback(frameCallback); // // } // // public void stop() { // mRunning = false; // if (syncCheckThread != null) { // try { // syncCheckThread.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // // Path: app/src/main/java/com/lsjwzh/test/GhostThread.java // public class GhostThread { // private static final String TAG = "GhostThread"; // // private static boolean isStart = false; // // private static Thread[] threads = new Thread[0]; // // private static Random random = new Random(); // private static Runnable runnable = new Runnable() { // @Override // public void run() { // for (; ;) { // if (!isStart) { // break; // } // double c = Math.PI * Math.PI * Math.PI * random.nextFloat(); // // Log.e("test", "v:" + c); // } // } // }; // // public static void start() { // if (isStart) { // return; // } // isStart = true; // for (int i = 0; i < threads.length; i++) { // Thread thread = new Thread(runnable); // thread.setPriority(Thread.NORM_PRIORITY); // thread.start(); // threads[i] = thread; // } // } // // public static void stop() { // isStart = false; // for (Thread thread : threads) { // try { // thread.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // }
import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.FragmentActivity; import android.view.View; import android.view.Menu; import android.view.MenuItem; import com.lsjwzh.test.FpsCalculator; import com.lsjwzh.test.GhostThread;
public void onBackPressed() { super.onBackPressed(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onDestroy() { super.onDestroy(); FpsCalculator.instance().stop();
// Path: app/src/main/java/com/lsjwzh/test/FpsCalculator.java // public class FpsCalculator { // // private final static String TAG = "FpsCalculator"; // // private long mFrameIntervalNanos; // // private boolean mRunning = false; // // private static FpsCalculator instance; // // private AtomicInteger atom = new AtomicInteger(0); // private Thread syncCheckThread = null; // // static { // instance = new FpsCalculator(); // } // // public static FpsCalculator instance() { // return instance; // } // // private int totalFps; // private int fpsCalculateCount; // private boolean isCalculatingFPS; // // // calculate the average fps // // public void startCalculate() { // totalFps = 0; // fpsCalculateCount = 0; // isCalculatingFPS = true; // } // // public int stopGetAvgFPS() { // isCalculatingFPS = false; // int avgFPS = totalFps / fpsCalculateCount; // totalFps = 0; // fpsCalculateCount = 0; // return avgFPS; // } // // private void syncCheckThread(){ // if(!mRunning){ // return; // } // int val = atom.getAndSet(0); // if (isCalculatingFPS) { // totalFps += val; // fpsCalculateCount++; // } // android.util.Log.i(TAG, "FPS: " + val); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // private FrameCallback frameCallback = new FrameCallback() { // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // @Override // public void doFrame(long frameTimeNanos) { // // if (!mRunning) { // return; // } // // Choreographer.getInstance().postFrameCallback(frameCallback); // // atom.incrementAndGet(); // }}; // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN) // public void start() { // Log.d(TAG, "start vsync detect"); // if (mRunning) { // return; // } // // mRunning = true; // // syncCheckThread = new Thread(new Runnable() { // @Override // public void run() { // for (;;) { // if (!mRunning) { // break; // } // syncCheckThread(); // } // } // }); // syncCheckThread.start(); // // Choreographer chor = Choreographer.getInstance(); // Field field; // try { // field = chor.getClass().getDeclaredField("mFrameIntervalNanos"); // field.setAccessible(true); // mFrameIntervalNanos = field.getLong(chor); // Log.d(TAG, "mFrameIntervalNanos " + mFrameIntervalNanos); // } catch (Exception e) { // Log.e(TAG, "error: " + e.getMessage()); // } // chor.postFrameCallback(frameCallback); // // } // // public void stop() { // mRunning = false; // if (syncCheckThread != null) { // try { // syncCheckThread.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // // Path: app/src/main/java/com/lsjwzh/test/GhostThread.java // public class GhostThread { // private static final String TAG = "GhostThread"; // // private static boolean isStart = false; // // private static Thread[] threads = new Thread[0]; // // private static Random random = new Random(); // private static Runnable runnable = new Runnable() { // @Override // public void run() { // for (; ;) { // if (!isStart) { // break; // } // double c = Math.PI * Math.PI * Math.PI * random.nextFloat(); // // Log.e("test", "v:" + c); // } // } // }; // // public static void start() { // if (isStart) { // return; // } // isStart = true; // for (int i = 0; i < threads.length; i++) { // Thread thread = new Thread(runnable); // thread.setPriority(Thread.NORM_PRIORITY); // thread.start(); // threads[i] = thread; // } // } // // public static void stop() { // isStart = false; // for (Thread thread : threads) { // try { // thread.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // Path: app/src/main/java/com/wechat/testdemo/MainActivity.java import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.FragmentActivity; import android.view.View; import android.view.Menu; import android.view.MenuItem; import com.lsjwzh.test.FpsCalculator; import com.lsjwzh.test.GhostThread; public void onBackPressed() { super.onBackPressed(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onDestroy() { super.onDestroy(); FpsCalculator.instance().stop();
GhostThread.stop();
lsjwzh/FastTextView
app/src/main/java/com/wechat/testdemo/TestListAdapter.java
// Path: app/src/main/java/com/lsjwzh/test/Util.java // public class Util { // // public static final int TEST_LIST_ITEM_COUNT = 500; // // public static final int TEXT_SIZE_DP = 25; // // public static final int AUTO_SCROLL_INTERVAL = 1; // // public static final int AUTO_SCROLL_STEP = 10; // // public static float fromDPtoPix(Context context, int dp) { // return context.getResources().getDisplayMetrics().density * dp; // } // // public static int getScreenWidth(Context context) { // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // // Point size = new Point(); // windowManager.getDefaultDisplay().getSize(size); // // return size.x; // } // }
import android.content.Context; import android.os.SystemClock; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.lsjwzh.test.Util;
package com.wechat.testdemo; public abstract class TestListAdapter extends BaseAdapter { protected Context context; public long bindCost = 0; public TestListAdapter(Context context) { this.context = context; } @Override public int getCount() {
// Path: app/src/main/java/com/lsjwzh/test/Util.java // public class Util { // // public static final int TEST_LIST_ITEM_COUNT = 500; // // public static final int TEXT_SIZE_DP = 25; // // public static final int AUTO_SCROLL_INTERVAL = 1; // // public static final int AUTO_SCROLL_STEP = 10; // // public static float fromDPtoPix(Context context, int dp) { // return context.getResources().getDisplayMetrics().density * dp; // } // // public static int getScreenWidth(Context context) { // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // // Point size = new Point(); // windowManager.getDefaultDisplay().getSize(size); // // return size.x; // } // } // Path: app/src/main/java/com/wechat/testdemo/TestListAdapter.java import android.content.Context; import android.os.SystemClock; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.lsjwzh.test.Util; package com.wechat.testdemo; public abstract class TestListAdapter extends BaseAdapter { protected Context context; public long bindCost = 0; public TestListAdapter(Context context) { this.context = context; } @Override public int getCount() {
return Util.TEST_LIST_ITEM_COUNT;
vinli/android-net
android-net/src/test/java/li/vin/net/DistancesIntegrationTests.java
// Path: android-net/src/main/java/li/vin/net/DistanceList.java // @AutoParcel // public static abstract class Distance implements Parcelable{ // /*package*/ static final Type WRAPPED_TYPE = new TypeToken<Wrapped<Distance>>() { }.getType(); // // /*package*/ static final void registerGson(GsonBuilder gb) { // gb.registerTypeAdapter(Distance.class, AutoParcelAdapter.create(AutoParcel_DistanceList_Distance.class)); // gb.registerTypeAdapter(WRAPPED_TYPE, Wrapped.Adapter.create(Distance.class)); // } // // public abstract Double confidenceMin(); // public abstract Double confidenceMax(); // public abstract Double value(); // public abstract String lastOdometerDate(); // // public static Observable<Distance> bestDistanceWithVehicleId(@NonNull String vehicleId) { // return bestDistanceWithVehicleId(vehicleId, null); // } // // public static Observable<Distance> bestDistanceWithVehicleId(@NonNull String vehicleId, // @Nullable DistanceUnit unit) { // return Vinli.curApp() // .distances() // .bestDistance(vehicleId, (unit == null) ? null : unit.getDistanceUnitStr()) // .map(Wrapped.<Distance>pluckItem()); // } // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import li.vin.net.DistanceList.Distance; import rx.Observer; import rx.Subscriber; import static junit.framework.Assert.assertTrue;
@Override public void onError(Throwable e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); assertTrue(false); } @Override public void onNext(Void aVoid) { } }); } }); DistanceList.distancesWithVehicleId(TestHelper.getVehicleId(), (Long) null, null, null).toBlocking().subscribe(new Subscriber<DistanceList>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); assertTrue(false); } @Override public void onNext(DistanceList distanceList) { assertTrue(distanceList.distances().size() > 0);
// Path: android-net/src/main/java/li/vin/net/DistanceList.java // @AutoParcel // public static abstract class Distance implements Parcelable{ // /*package*/ static final Type WRAPPED_TYPE = new TypeToken<Wrapped<Distance>>() { }.getType(); // // /*package*/ static final void registerGson(GsonBuilder gb) { // gb.registerTypeAdapter(Distance.class, AutoParcelAdapter.create(AutoParcel_DistanceList_Distance.class)); // gb.registerTypeAdapter(WRAPPED_TYPE, Wrapped.Adapter.create(Distance.class)); // } // // public abstract Double confidenceMin(); // public abstract Double confidenceMax(); // public abstract Double value(); // public abstract String lastOdometerDate(); // // public static Observable<Distance> bestDistanceWithVehicleId(@NonNull String vehicleId) { // return bestDistanceWithVehicleId(vehicleId, null); // } // // public static Observable<Distance> bestDistanceWithVehicleId(@NonNull String vehicleId, // @Nullable DistanceUnit unit) { // return Vinli.curApp() // .distances() // .bestDistance(vehicleId, (unit == null) ? null : unit.getDistanceUnitStr()) // .map(Wrapped.<Distance>pluckItem()); // } // } // Path: android-net/src/test/java/li/vin/net/DistancesIntegrationTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import li.vin.net.DistanceList.Distance; import rx.Observer; import rx.Subscriber; import static junit.framework.Assert.assertTrue; @Override public void onError(Throwable e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); assertTrue(false); } @Override public void onNext(Void aVoid) { } }); } }); DistanceList.distancesWithVehicleId(TestHelper.getVehicleId(), (Long) null, null, null).toBlocking().subscribe(new Subscriber<DistanceList>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); assertTrue(false); } @Override public void onNext(DistanceList distanceList) { assertTrue(distanceList.distances().size() > 0);
for(Distance distance : distanceList.distances()){
vinli/android-net
android-net/src/test/java/li/vin/net/MessagesIntegrationTests.java
// Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getDeviceId(){ // String deviceId = BuildConfig.DEVICE_ID; // return deviceId.equals("DEFAULT_DEVICE_ID") ? null : deviceId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getSecondVehicleId(){ // String secondVehicleId = BuildConfig.SECOND_VEHICLE_ID; // return secondVehicleId.equals("DEFAULT_SECOND_VEHICLE_ID") ? null : secondVehicleId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getVehicleId(){ // String vehicleId = BuildConfig.VEHICLE_ID; // return vehicleId.equals("DEFAULT_VEHICLE_ID") ? null : vehicleId; // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import rx.Subscriber; import static junit.framework.Assert.assertTrue; import static li.vin.net.TestHelper.getDeviceId; import static li.vin.net.TestHelper.getSecondVehicleId; import static li.vin.net.TestHelper.getVehicleId;
package li.vin.net; @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = 22) public class MessagesIntegrationTests { public VinliApp vinliApp; public VinliApp vehicleVinliApp; @Before public void setup() { assertTrue(TestHelper.getAccessToken() != null); vinliApp = TestHelper.getVinliApp(); assertTrue(TestHelper.getVehicleAccessToken() != null); vehicleVinliApp = TestHelper.getVehicleVinliApp(); } @Test public void getPagedMessagesByDeviceId() {
// Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getDeviceId(){ // String deviceId = BuildConfig.DEVICE_ID; // return deviceId.equals("DEFAULT_DEVICE_ID") ? null : deviceId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getSecondVehicleId(){ // String secondVehicleId = BuildConfig.SECOND_VEHICLE_ID; // return secondVehicleId.equals("DEFAULT_SECOND_VEHICLE_ID") ? null : secondVehicleId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getVehicleId(){ // String vehicleId = BuildConfig.VEHICLE_ID; // return vehicleId.equals("DEFAULT_VEHICLE_ID") ? null : vehicleId; // } // Path: android-net/src/test/java/li/vin/net/MessagesIntegrationTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import rx.Subscriber; import static junit.framework.Assert.assertTrue; import static li.vin.net.TestHelper.getDeviceId; import static li.vin.net.TestHelper.getSecondVehicleId; import static li.vin.net.TestHelper.getVehicleId; package li.vin.net; @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = 22) public class MessagesIntegrationTests { public VinliApp vinliApp; public VinliApp vehicleVinliApp; @Before public void setup() { assertTrue(TestHelper.getAccessToken() != null); vinliApp = TestHelper.getVinliApp(); assertTrue(TestHelper.getVehicleAccessToken() != null); vehicleVinliApp = TestHelper.getVehicleVinliApp(); } @Test public void getPagedMessagesByDeviceId() {
assertTrue(getDeviceId() != null);
vinli/android-net
android-net/src/test/java/li/vin/net/MessagesIntegrationTests.java
// Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getDeviceId(){ // String deviceId = BuildConfig.DEVICE_ID; // return deviceId.equals("DEFAULT_DEVICE_ID") ? null : deviceId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getSecondVehicleId(){ // String secondVehicleId = BuildConfig.SECOND_VEHICLE_ID; // return secondVehicleId.equals("DEFAULT_SECOND_VEHICLE_ID") ? null : secondVehicleId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getVehicleId(){ // String vehicleId = BuildConfig.VEHICLE_ID; // return vehicleId.equals("DEFAULT_VEHICLE_ID") ? null : vehicleId; // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import rx.Subscriber; import static junit.framework.Assert.assertTrue; import static li.vin.net.TestHelper.getDeviceId; import static li.vin.net.TestHelper.getSecondVehicleId; import static li.vin.net.TestHelper.getVehicleId;
@Override public void onNext(TimeSeries<Message> messageTimeSeries) { for (Message message : messageTimeSeries.getItems()) { assertTrue(message.id() != null && message.id().length() > 0); assertTrue(message.timestamp != null && message.timestamp.length() > 0); } if (messageTimeSeries.hasPrior()) { messageTimeSeries.loadPrior().toBlocking() .subscribe(new Subscriber<TimeSeries<Message>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { e.printStackTrace(); assertTrue(false); } @Override public void onNext(TimeSeries<Message> messageTimeSeries) { for (Message message : messageTimeSeries.getItems()) { assertTrue(message.id() != null && message.id().length() > 0); assertTrue(message.timestamp != null && message.timestamp.length() > 0); } } }); } } }); } @Test public void getPagedMessagesByVehicleId() {
// Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getDeviceId(){ // String deviceId = BuildConfig.DEVICE_ID; // return deviceId.equals("DEFAULT_DEVICE_ID") ? null : deviceId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getSecondVehicleId(){ // String secondVehicleId = BuildConfig.SECOND_VEHICLE_ID; // return secondVehicleId.equals("DEFAULT_SECOND_VEHICLE_ID") ? null : secondVehicleId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getVehicleId(){ // String vehicleId = BuildConfig.VEHICLE_ID; // return vehicleId.equals("DEFAULT_VEHICLE_ID") ? null : vehicleId; // } // Path: android-net/src/test/java/li/vin/net/MessagesIntegrationTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import rx.Subscriber; import static junit.framework.Assert.assertTrue; import static li.vin.net.TestHelper.getDeviceId; import static li.vin.net.TestHelper.getSecondVehicleId; import static li.vin.net.TestHelper.getVehicleId; @Override public void onNext(TimeSeries<Message> messageTimeSeries) { for (Message message : messageTimeSeries.getItems()) { assertTrue(message.id() != null && message.id().length() > 0); assertTrue(message.timestamp != null && message.timestamp.length() > 0); } if (messageTimeSeries.hasPrior()) { messageTimeSeries.loadPrior().toBlocking() .subscribe(new Subscriber<TimeSeries<Message>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { e.printStackTrace(); assertTrue(false); } @Override public void onNext(TimeSeries<Message> messageTimeSeries) { for (Message message : messageTimeSeries.getItems()) { assertTrue(message.id() != null && message.id().length() > 0); assertTrue(message.timestamp != null && message.timestamp.length() > 0); } } }); } } }); } @Test public void getPagedMessagesByVehicleId() {
assertTrue(getVehicleId() != null);
vinli/android-net
android-net/src/test/java/li/vin/net/MessagesIntegrationTests.java
// Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getDeviceId(){ // String deviceId = BuildConfig.DEVICE_ID; // return deviceId.equals("DEFAULT_DEVICE_ID") ? null : deviceId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getSecondVehicleId(){ // String secondVehicleId = BuildConfig.SECOND_VEHICLE_ID; // return secondVehicleId.equals("DEFAULT_SECOND_VEHICLE_ID") ? null : secondVehicleId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getVehicleId(){ // String vehicleId = BuildConfig.VEHICLE_ID; // return vehicleId.equals("DEFAULT_VEHICLE_ID") ? null : vehicleId; // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import rx.Subscriber; import static junit.framework.Assert.assertTrue; import static li.vin.net.TestHelper.getDeviceId; import static li.vin.net.TestHelper.getSecondVehicleId; import static li.vin.net.TestHelper.getVehicleId;
}); } @Test public void getMessagesByDeviceId() { assertTrue(getDeviceId() != null); Message.messagesWithDeviceId(getDeviceId(), (Long) null, null, null, null) .toBlocking() .subscribe(new Subscriber<TimeSeries<Message>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { e.printStackTrace(); assertTrue(false); } @Override public void onNext(TimeSeries<Message> messageTimeSeries) { assertTrue(messageTimeSeries.getItems().size() > 0); for (Message message : messageTimeSeries.getItems()) { assertTrue(message.id() != null && message.id().length() > 0); assertTrue(message.timestamp != null && message.timestamp.length() > 0); } } }); } @Test public void getMessagesByVehicleId() { assertTrue(getVehicleId() != null);
// Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getDeviceId(){ // String deviceId = BuildConfig.DEVICE_ID; // return deviceId.equals("DEFAULT_DEVICE_ID") ? null : deviceId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getSecondVehicleId(){ // String secondVehicleId = BuildConfig.SECOND_VEHICLE_ID; // return secondVehicleId.equals("DEFAULT_SECOND_VEHICLE_ID") ? null : secondVehicleId; // } // // Path: android-net/src/test/java/li/vin/net/TestHelper.java // public static String getVehicleId(){ // String vehicleId = BuildConfig.VEHICLE_ID; // return vehicleId.equals("DEFAULT_VEHICLE_ID") ? null : vehicleId; // } // Path: android-net/src/test/java/li/vin/net/MessagesIntegrationTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import rx.Subscriber; import static junit.framework.Assert.assertTrue; import static li.vin.net.TestHelper.getDeviceId; import static li.vin.net.TestHelper.getSecondVehicleId; import static li.vin.net.TestHelper.getVehicleId; }); } @Test public void getMessagesByDeviceId() { assertTrue(getDeviceId() != null); Message.messagesWithDeviceId(getDeviceId(), (Long) null, null, null, null) .toBlocking() .subscribe(new Subscriber<TimeSeries<Message>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { e.printStackTrace(); assertTrue(false); } @Override public void onNext(TimeSeries<Message> messageTimeSeries) { assertTrue(messageTimeSeries.getItems().size() > 0); for (Message message : messageTimeSeries.getItems()) { assertTrue(message.id() != null && message.id().length() > 0); assertTrue(message.timestamp != null && message.timestamp.length() > 0); } } }); } @Test public void getMessagesByVehicleId() { assertTrue(getVehicleId() != null);
vehicleVinliApp.messages().vehicleMessages(TestHelper.getSecondVehicleId(), null, null, null, null)
vinli/android-net
android-net/src/main/java/li/vin/net/StreamMessage.java
// Path: android-net/src/main/java/li/vin/net/Message.java // public static final class AccelData { // // /* // "accel": { // "maxZ": 6.282417, // "maxX": -2.911364, // "maxY": -2.489982, // "minX": -7.853021, // "minY": -10.649463, // "minZ": -0.804456 // } // */ // // private Double maxX; // private Double maxY; // private Double maxZ; // private Double minX; // private Double minY; // private Double minZ; // // AccelData(double maxX, double maxY, double maxZ, double minX, double minY, double minZ) { // this.maxX = maxX; // this.maxY = maxY; // this.maxZ = maxZ; // this.minX = minX; // this.minY = minY; // this.minZ = minZ; // } // // AccelData() { // } // // public double maxX() { // if (maxX == null) return 0d; // return maxX; // } // // public double maxY() { // if (maxY == null) return 0d; // return maxY; // } // // public double maxZ() { // if (maxZ == null) return 0d; // return maxZ; // } // // public double minX() { // if (minX == null) return 0d; // return minX; // } // // public double minY() { // if (minY == null) return 0d; // return minY; // } // // public double minZ() { // if (minZ == null) return 0d; // return minZ; // } // // @Override // public String toString() { // return "AccelData{" + // "maxX=" + maxX + // ", maxY=" + maxY + // ", maxZ=" + maxZ + // ", minX=" + minX + // ", minY=" + minY + // ", minZ=" + minZ + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // AccelData accelData = (AccelData) o; // return !(maxX != null // ? !maxX.equals(accelData.maxX) // : accelData.maxX != null) && !(maxY != null // ? !maxY.equals(accelData.maxY) // : accelData.maxY != null) && !(maxZ != null // ? !maxZ.equals(accelData.maxZ) // : accelData.maxZ != null) && !(minX != null // ? !minX.equals(accelData.minX) // : accelData.minX != null) && !(minY != null // ? !minY.equals(accelData.minY) // : accelData.minY != null) && !(minZ != null // ? !minZ.equals(accelData.minZ) // : accelData.minZ != null); // } // // @Override // public int hashCode() { // int result = maxX != null // ? maxX.hashCode() // : 0; // result = 31 * result + (maxY != null // ? maxY.hashCode() // : 0); // result = 31 * result + (maxZ != null // ? maxZ.hashCode() // : 0); // result = 31 * result + (minX != null // ? minX.hashCode() // : 0); // result = 31 * result + (minY != null // ? minY.hashCode() // : 0); // result = 31 * result + (minZ != null // ? minZ.hashCode() // : 0); // return result; // } // }
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import auto.parcel.AutoParcel; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.internal.LinkedTreeMap; import com.google.gson.stream.JsonReader; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import li.vin.net.Message.AccelData; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import rx.Observable; import rx.Subscriber; import rx.functions.Func1;
if (colonIndex == line.length() - 1) return; // can't end with colon pfx = line.substring(0, colonIndex); line = line.substring(colonIndex + 1); } else if (line.length() == 2) { pfx = line; line = null; } else if (line.startsWith("41")) { pfx = "41"; line = line.substring(2); } else { return; } if (pfx.equals("41") && line != null && line.length() > 2) { processObd(line.substring(0, 2), line.substring(2), dt, subscriber); } else if (pfx.equals("A") && line != null && line.length() >= 14) { StreamMessage sm = emptyStreamMessage(); boolean accelFound = false; try { sm.payload.data.put("udpCollision", Integer.valueOf(line.substring(line.length() - 2), 16) == 0 ? Boolean.FALSE : Boolean.TRUE); accelFound = true; } catch (Exception ignored) { } try { float xAccel = Integer.valueOf(line.substring(0, 4), 16).shortValue() * ACCEL_CONVERT; float yAccel = Integer.valueOf(line.substring(4, 8), 16).shortValue() * ACCEL_CONVERT; float zAccel = Integer.valueOf(line.substring(8, 12), 16).shortValue() * ACCEL_CONVERT;
// Path: android-net/src/main/java/li/vin/net/Message.java // public static final class AccelData { // // /* // "accel": { // "maxZ": 6.282417, // "maxX": -2.911364, // "maxY": -2.489982, // "minX": -7.853021, // "minY": -10.649463, // "minZ": -0.804456 // } // */ // // private Double maxX; // private Double maxY; // private Double maxZ; // private Double minX; // private Double minY; // private Double minZ; // // AccelData(double maxX, double maxY, double maxZ, double minX, double minY, double minZ) { // this.maxX = maxX; // this.maxY = maxY; // this.maxZ = maxZ; // this.minX = minX; // this.minY = minY; // this.minZ = minZ; // } // // AccelData() { // } // // public double maxX() { // if (maxX == null) return 0d; // return maxX; // } // // public double maxY() { // if (maxY == null) return 0d; // return maxY; // } // // public double maxZ() { // if (maxZ == null) return 0d; // return maxZ; // } // // public double minX() { // if (minX == null) return 0d; // return minX; // } // // public double minY() { // if (minY == null) return 0d; // return minY; // } // // public double minZ() { // if (minZ == null) return 0d; // return minZ; // } // // @Override // public String toString() { // return "AccelData{" + // "maxX=" + maxX + // ", maxY=" + maxY + // ", maxZ=" + maxZ + // ", minX=" + minX + // ", minY=" + minY + // ", minZ=" + minZ + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // AccelData accelData = (AccelData) o; // return !(maxX != null // ? !maxX.equals(accelData.maxX) // : accelData.maxX != null) && !(maxY != null // ? !maxY.equals(accelData.maxY) // : accelData.maxY != null) && !(maxZ != null // ? !maxZ.equals(accelData.maxZ) // : accelData.maxZ != null) && !(minX != null // ? !minX.equals(accelData.minX) // : accelData.minX != null) && !(minY != null // ? !minY.equals(accelData.minY) // : accelData.minY != null) && !(minZ != null // ? !minZ.equals(accelData.minZ) // : accelData.minZ != null); // } // // @Override // public int hashCode() { // int result = maxX != null // ? maxX.hashCode() // : 0; // result = 31 * result + (maxY != null // ? maxY.hashCode() // : 0); // result = 31 * result + (maxZ != null // ? maxZ.hashCode() // : 0); // result = 31 * result + (minX != null // ? minX.hashCode() // : 0); // result = 31 * result + (minY != null // ? minY.hashCode() // : 0); // result = 31 * result + (minZ != null // ? minZ.hashCode() // : 0); // return result; // } // } // Path: android-net/src/main/java/li/vin/net/StreamMessage.java import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import auto.parcel.AutoParcel; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.internal.LinkedTreeMap; import com.google.gson.stream.JsonReader; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import li.vin.net.Message.AccelData; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import rx.Observable; import rx.Subscriber; import rx.functions.Func1; if (colonIndex == line.length() - 1) return; // can't end with colon pfx = line.substring(0, colonIndex); line = line.substring(colonIndex + 1); } else if (line.length() == 2) { pfx = line; line = null; } else if (line.startsWith("41")) { pfx = "41"; line = line.substring(2); } else { return; } if (pfx.equals("41") && line != null && line.length() > 2) { processObd(line.substring(0, 2), line.substring(2), dt, subscriber); } else if (pfx.equals("A") && line != null && line.length() >= 14) { StreamMessage sm = emptyStreamMessage(); boolean accelFound = false; try { sm.payload.data.put("udpCollision", Integer.valueOf(line.substring(line.length() - 2), 16) == 0 ? Boolean.FALSE : Boolean.TRUE); accelFound = true; } catch (Exception ignored) { } try { float xAccel = Integer.valueOf(line.substring(0, 4), 16).shortValue() * ACCEL_CONVERT; float yAccel = Integer.valueOf(line.substring(4, 8), 16).shortValue() * ACCEL_CONVERT; float zAccel = Integer.valueOf(line.substring(8, 12), 16).shortValue() * ACCEL_CONVERT;
sm.payload.data.put("accel", new AccelData(xAccel, yAccel, zAccel, xAccel, yAccel, zAccel));
AbeelLab/genometools
scala/org/broad/igv/DataSource.java
// Path: scala/org/broad/igv/LocusScore.java // public interface LocusScore extends Feature { // // //public int getStart(); // // // public int getEnd(); // // public void setStart(int start); // // public void setEnd(int end); // // public float getScore(); // // public void setConfidence(float confidence); // // public float getConfidence(); // // public LocusScore copy(); // // /** // * Return a string to be used for popup text. The WindowFunction is passed // * in so it can be used t annotate the value. The LocusScore object itself // * does not "know" from what window function it was derived // * // * @param windowFunction // * @return // */ // public String getValueString(double position, WindowFunction windowFunction); // } // // Path: scala/org/broad/igv/WindowFunction.java // public enum WindowFunction { // // mean("Mean"), // median("Median"), // min("Minimum"), // max("Maximum"), // percentile2("2nd Percentile"), // percentile10("10th Percentile"), // percentile90("90th Percentile"), // percentile98("98th Percentile"), // // stddev("Standard Deviation"), // count("Count"); // // density("Density"); // // private String displayName = ""; // // WindowFunction(String displayName) { // this.displayName = displayName; // } // // public String getDisplayName() { // return displayName; // } // // static public WindowFunction getWindowFunction(String name) { // // WindowFunction windowFunction = null; // if (WindowFunction.mean.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.mean; // } else if (WindowFunction.median.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.median; // } else if (WindowFunction.min.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.min; // } else if (WindowFunction.max.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.max; // } else if (WindowFunction.percentile10.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile10; // } else if (WindowFunction.percentile90.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile90; // } else if (WindowFunction.percentile98.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile98; // // } else if (WindowFunction.stddev.name().equals(name)) { // // windowFunction = WindowFunction.stddev; // } else if (WindowFunction.count.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.count; // // } else if (WindowFunction.density.name().equals(name)) { // // windowFunction = WindowFunction.density; // } // return windowFunction; // } // }
import java.util.Collection; import java.util.List; import org.broad.igv.LocusScore; import org.broad.igv.WindowFunction;
/* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * @author jrobinso */ public interface DataSource { double getDataMax(); double getDataMin();
// Path: scala/org/broad/igv/LocusScore.java // public interface LocusScore extends Feature { // // //public int getStart(); // // // public int getEnd(); // // public void setStart(int start); // // public void setEnd(int end); // // public float getScore(); // // public void setConfidence(float confidence); // // public float getConfidence(); // // public LocusScore copy(); // // /** // * Return a string to be used for popup text. The WindowFunction is passed // * in so it can be used t annotate the value. The LocusScore object itself // * does not "know" from what window function it was derived // * // * @param windowFunction // * @return // */ // public String getValueString(double position, WindowFunction windowFunction); // } // // Path: scala/org/broad/igv/WindowFunction.java // public enum WindowFunction { // // mean("Mean"), // median("Median"), // min("Minimum"), // max("Maximum"), // percentile2("2nd Percentile"), // percentile10("10th Percentile"), // percentile90("90th Percentile"), // percentile98("98th Percentile"), // // stddev("Standard Deviation"), // count("Count"); // // density("Density"); // // private String displayName = ""; // // WindowFunction(String displayName) { // this.displayName = displayName; // } // // public String getDisplayName() { // return displayName; // } // // static public WindowFunction getWindowFunction(String name) { // // WindowFunction windowFunction = null; // if (WindowFunction.mean.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.mean; // } else if (WindowFunction.median.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.median; // } else if (WindowFunction.min.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.min; // } else if (WindowFunction.max.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.max; // } else if (WindowFunction.percentile10.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile10; // } else if (WindowFunction.percentile90.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile90; // } else if (WindowFunction.percentile98.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile98; // // } else if (WindowFunction.stddev.name().equals(name)) { // // windowFunction = WindowFunction.stddev; // } else if (WindowFunction.count.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.count; // // } else if (WindowFunction.density.name().equals(name)) { // // windowFunction = WindowFunction.density; // } // return windowFunction; // } // } // Path: scala/org/broad/igv/DataSource.java import java.util.Collection; import java.util.List; import org.broad.igv.LocusScore; import org.broad.igv.WindowFunction; /* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * @author jrobinso */ public interface DataSource { double getDataMax(); double getDataMin();
List<LocusScore> getSummaryScoresForRange(String chr, int startLocation, int endLocation, int zoom);
AbeelLab/genometools
scala/org/broad/igv/DataSource.java
// Path: scala/org/broad/igv/LocusScore.java // public interface LocusScore extends Feature { // // //public int getStart(); // // // public int getEnd(); // // public void setStart(int start); // // public void setEnd(int end); // // public float getScore(); // // public void setConfidence(float confidence); // // public float getConfidence(); // // public LocusScore copy(); // // /** // * Return a string to be used for popup text. The WindowFunction is passed // * in so it can be used t annotate the value. The LocusScore object itself // * does not "know" from what window function it was derived // * // * @param windowFunction // * @return // */ // public String getValueString(double position, WindowFunction windowFunction); // } // // Path: scala/org/broad/igv/WindowFunction.java // public enum WindowFunction { // // mean("Mean"), // median("Median"), // min("Minimum"), // max("Maximum"), // percentile2("2nd Percentile"), // percentile10("10th Percentile"), // percentile90("90th Percentile"), // percentile98("98th Percentile"), // // stddev("Standard Deviation"), // count("Count"); // // density("Density"); // // private String displayName = ""; // // WindowFunction(String displayName) { // this.displayName = displayName; // } // // public String getDisplayName() { // return displayName; // } // // static public WindowFunction getWindowFunction(String name) { // // WindowFunction windowFunction = null; // if (WindowFunction.mean.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.mean; // } else if (WindowFunction.median.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.median; // } else if (WindowFunction.min.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.min; // } else if (WindowFunction.max.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.max; // } else if (WindowFunction.percentile10.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile10; // } else if (WindowFunction.percentile90.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile90; // } else if (WindowFunction.percentile98.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile98; // // } else if (WindowFunction.stddev.name().equals(name)) { // // windowFunction = WindowFunction.stddev; // } else if (WindowFunction.count.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.count; // // } else if (WindowFunction.density.name().equals(name)) { // // windowFunction = WindowFunction.density; // } // return windowFunction; // } // }
import java.util.Collection; import java.util.List; import org.broad.igv.LocusScore; import org.broad.igv.WindowFunction;
/* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * @author jrobinso */ public interface DataSource { double getDataMax(); double getDataMin(); List<LocusScore> getSummaryScoresForRange(String chr, int startLocation, int endLocation, int zoom);
// Path: scala/org/broad/igv/LocusScore.java // public interface LocusScore extends Feature { // // //public int getStart(); // // // public int getEnd(); // // public void setStart(int start); // // public void setEnd(int end); // // public float getScore(); // // public void setConfidence(float confidence); // // public float getConfidence(); // // public LocusScore copy(); // // /** // * Return a string to be used for popup text. The WindowFunction is passed // * in so it can be used t annotate the value. The LocusScore object itself // * does not "know" from what window function it was derived // * // * @param windowFunction // * @return // */ // public String getValueString(double position, WindowFunction windowFunction); // } // // Path: scala/org/broad/igv/WindowFunction.java // public enum WindowFunction { // // mean("Mean"), // median("Median"), // min("Minimum"), // max("Maximum"), // percentile2("2nd Percentile"), // percentile10("10th Percentile"), // percentile90("90th Percentile"), // percentile98("98th Percentile"), // // stddev("Standard Deviation"), // count("Count"); // // density("Density"); // // private String displayName = ""; // // WindowFunction(String displayName) { // this.displayName = displayName; // } // // public String getDisplayName() { // return displayName; // } // // static public WindowFunction getWindowFunction(String name) { // // WindowFunction windowFunction = null; // if (WindowFunction.mean.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.mean; // } else if (WindowFunction.median.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.median; // } else if (WindowFunction.min.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.min; // } else if (WindowFunction.max.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.max; // } else if (WindowFunction.percentile10.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile10; // } else if (WindowFunction.percentile90.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile90; // } else if (WindowFunction.percentile98.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile98; // // } else if (WindowFunction.stddev.name().equals(name)) { // // windowFunction = WindowFunction.stddev; // } else if (WindowFunction.count.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.count; // // } else if (WindowFunction.density.name().equals(name)) { // // windowFunction = WindowFunction.density; // } // return windowFunction; // } // } // Path: scala/org/broad/igv/DataSource.java import java.util.Collection; import java.util.List; import org.broad.igv.LocusScore; import org.broad.igv.WindowFunction; /* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * @author jrobinso */ public interface DataSource { double getDataMax(); double getDataMin(); List<LocusScore> getSummaryScoresForRange(String chr, int startLocation, int endLocation, int zoom);
void setWindowFunction(WindowFunction statType);
AbeelLab/genometools
scala/org/broad/igv/LocusScore.java
// Path: scala/org/broad/igv/WindowFunction.java // public enum WindowFunction { // // mean("Mean"), // median("Median"), // min("Minimum"), // max("Maximum"), // percentile2("2nd Percentile"), // percentile10("10th Percentile"), // percentile90("90th Percentile"), // percentile98("98th Percentile"), // // stddev("Standard Deviation"), // count("Count"); // // density("Density"); // // private String displayName = ""; // // WindowFunction(String displayName) { // this.displayName = displayName; // } // // public String getDisplayName() { // return displayName; // } // // static public WindowFunction getWindowFunction(String name) { // // WindowFunction windowFunction = null; // if (WindowFunction.mean.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.mean; // } else if (WindowFunction.median.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.median; // } else if (WindowFunction.min.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.min; // } else if (WindowFunction.max.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.max; // } else if (WindowFunction.percentile10.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile10; // } else if (WindowFunction.percentile90.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile90; // } else if (WindowFunction.percentile98.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile98; // // } else if (WindowFunction.stddev.name().equals(name)) { // // windowFunction = WindowFunction.stddev; // } else if (WindowFunction.count.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.count; // // } else if (WindowFunction.density.name().equals(name)) { // // windowFunction = WindowFunction.density; // } // return windowFunction; // } // }
import org.broad.igv.WindowFunction; import org.broad.tribble.Feature;
/* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * @author jrobinso */ public interface LocusScore extends Feature { //public int getStart(); // public int getEnd(); public void setStart(int start); public void setEnd(int end); public float getScore(); public void setConfidence(float confidence); public float getConfidence(); public LocusScore copy(); /** * Return a string to be used for popup text. The WindowFunction is passed * in so it can be used t annotate the value. The LocusScore object itself * does not "know" from what window function it was derived * * @param windowFunction * @return */
// Path: scala/org/broad/igv/WindowFunction.java // public enum WindowFunction { // // mean("Mean"), // median("Median"), // min("Minimum"), // max("Maximum"), // percentile2("2nd Percentile"), // percentile10("10th Percentile"), // percentile90("90th Percentile"), // percentile98("98th Percentile"), // // stddev("Standard Deviation"), // count("Count"); // // density("Density"); // // private String displayName = ""; // // WindowFunction(String displayName) { // this.displayName = displayName; // } // // public String getDisplayName() { // return displayName; // } // // static public WindowFunction getWindowFunction(String name) { // // WindowFunction windowFunction = null; // if (WindowFunction.mean.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.mean; // } else if (WindowFunction.median.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.median; // } else if (WindowFunction.min.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.min; // } else if (WindowFunction.max.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.max; // } else if (WindowFunction.percentile10.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile10; // } else if (WindowFunction.percentile90.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile90; // } else if (WindowFunction.percentile98.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile98; // // } else if (WindowFunction.stddev.name().equals(name)) { // // windowFunction = WindowFunction.stddev; // } else if (WindowFunction.count.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.count; // // } else if (WindowFunction.density.name().equals(name)) { // // windowFunction = WindowFunction.density; // } // return windowFunction; // } // } // Path: scala/org/broad/igv/LocusScore.java import org.broad.igv.WindowFunction; import org.broad.tribble.Feature; /* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * @author jrobinso */ public interface LocusScore extends Feature { //public int getStart(); // public int getEnd(); public void setStart(int start); public void setEnd(int end); public float getScore(); public void setConfidence(float confidence); public float getConfidence(); public LocusScore copy(); /** * Return a string to be used for popup text. The WindowFunction is passed * in so it can be used t annotate the value. The LocusScore object itself * does not "know" from what window function it was derived * * @param windowFunction * @return */
public String getValueString(double position, WindowFunction windowFunction);
AbeelLab/genometools
scala/org/broad/igv/TileFactory.java
// Path: scala/org/broad/igv/StringUtils.java // public class StringUtils { // // // public static List<String> breakQuotedString(String string, char splitToken) { // // ArrayList<String> strings = new ArrayList(); // if (string.length() == 0) { // return strings; // } // // char[] characters = string.toCharArray(); // char c = characters[0]; // // boolean isQuoted = false; // StringBuffer buff = new StringBuffer(100); // for (int i = 0; i < characters.length; i++) { // c = characters[i]; // if (isQuoted) { // if (c == '"') { // isQuoted = false; // } // buff.append(c); // } else if (c == '"') { // isQuoted = true; // buff.append(c); // } else { // if (c == splitToken) { // strings.add(buff.toString().trim()); // buff.setLength(0); // } else { // buff.append(c); // } // } // } // if (buff.length() > 0) { // strings.add(buff.toString().trim()); // } // return strings; // // } // // // public static short genoToShort(String genotype) { // byte[] bytes = genotype.getBytes(); // return (short) ((bytes[0] & 0xff) << 8 | (bytes[1] & 0xff)); // } // // public static String readString(ByteBuffer byteBuffer) throws IOException { // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // byte b = -1; // while ((b = byteBuffer.get()) != 0) { // bytes.write(b); // } // return new String(bytes.toByteArray()); // } // // public static void main(String[] args) { // // String genotype = "AC"; // short genoShort = genoToShort(genotype); // // char allel1 = (char) ((genoShort >>> 8) & 0xFF); // char allel2 = (char) ((genoShort >>> 0) & 0xFF); // // System.out.println("Allele1: " + allel1); // System.out.println("Allele2: " + allel2); // // } // }
import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.broad.igv.StringUtils;
/* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * @author jrobinso */ public class TileFactory { public static TDFTile createTile(byte[] buffer, int nSamples) throws IOException { ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
// Path: scala/org/broad/igv/StringUtils.java // public class StringUtils { // // // public static List<String> breakQuotedString(String string, char splitToken) { // // ArrayList<String> strings = new ArrayList(); // if (string.length() == 0) { // return strings; // } // // char[] characters = string.toCharArray(); // char c = characters[0]; // // boolean isQuoted = false; // StringBuffer buff = new StringBuffer(100); // for (int i = 0; i < characters.length; i++) { // c = characters[i]; // if (isQuoted) { // if (c == '"') { // isQuoted = false; // } // buff.append(c); // } else if (c == '"') { // isQuoted = true; // buff.append(c); // } else { // if (c == splitToken) { // strings.add(buff.toString().trim()); // buff.setLength(0); // } else { // buff.append(c); // } // } // } // if (buff.length() > 0) { // strings.add(buff.toString().trim()); // } // return strings; // // } // // // public static short genoToShort(String genotype) { // byte[] bytes = genotype.getBytes(); // return (short) ((bytes[0] & 0xff) << 8 | (bytes[1] & 0xff)); // } // // public static String readString(ByteBuffer byteBuffer) throws IOException { // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // byte b = -1; // while ((b = byteBuffer.get()) != 0) { // bytes.write(b); // } // return new String(bytes.toByteArray()); // } // // public static void main(String[] args) { // // String genotype = "AC"; // short genoShort = genoToShort(genotype); // // char allel1 = (char) ((genoShort >>> 8) & 0xFF); // char allel2 = (char) ((genoShort >>> 0) & 0xFF); // // System.out.println("Allele1: " + allel1); // System.out.println("Allele2: " + allel2); // // } // } // Path: scala/org/broad/igv/TileFactory.java import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.broad.igv.StringUtils; /* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * @author jrobinso */ public class TileFactory { public static TDFTile createTile(byte[] buffer, int nSamples) throws IOException { ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
String typeString = StringUtils.readString(byteBuffer);
AbeelLab/genometools
scala/org/broad/igv/TileManager.java
// Path: scala/org/broad/igv/WindowFunction.java // public enum WindowFunction { // // mean("Mean"), // median("Median"), // min("Minimum"), // max("Maximum"), // percentile2("2nd Percentile"), // percentile10("10th Percentile"), // percentile90("90th Percentile"), // percentile98("98th Percentile"), // // stddev("Standard Deviation"), // count("Count"); // // density("Density"); // // private String displayName = ""; // // WindowFunction(String displayName) { // this.displayName = displayName; // } // // public String getDisplayName() { // return displayName; // } // // static public WindowFunction getWindowFunction(String name) { // // WindowFunction windowFunction = null; // if (WindowFunction.mean.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.mean; // } else if (WindowFunction.median.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.median; // } else if (WindowFunction.min.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.min; // } else if (WindowFunction.max.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.max; // } else if (WindowFunction.percentile10.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile10; // } else if (WindowFunction.percentile90.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile90; // } else if (WindowFunction.percentile98.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile98; // // } else if (WindowFunction.stddev.name().equals(name)) { // // windowFunction = WindowFunction.stddev; // } else if (WindowFunction.count.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.count; // // } else if (WindowFunction.density.name().equals(name)) { // // windowFunction = WindowFunction.density; // } // return windowFunction; // } // }
import java.util.List; import org.broad.igv.WindowFunction;
/* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * @author jrobinso */ public class TileManager { TDFReader reader; public TileManager(TDFReader reader) { this.reader = reader; } public List<TDFTile> getTiles(String chr, int start, int end, int zoom) {
// Path: scala/org/broad/igv/WindowFunction.java // public enum WindowFunction { // // mean("Mean"), // median("Median"), // min("Minimum"), // max("Maximum"), // percentile2("2nd Percentile"), // percentile10("10th Percentile"), // percentile90("90th Percentile"), // percentile98("98th Percentile"), // // stddev("Standard Deviation"), // count("Count"); // // density("Density"); // // private String displayName = ""; // // WindowFunction(String displayName) { // this.displayName = displayName; // } // // public String getDisplayName() { // return displayName; // } // // static public WindowFunction getWindowFunction(String name) { // // WindowFunction windowFunction = null; // if (WindowFunction.mean.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.mean; // } else if (WindowFunction.median.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.median; // } else if (WindowFunction.min.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.min; // } else if (WindowFunction.max.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.max; // } else if (WindowFunction.percentile10.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile10; // } else if (WindowFunction.percentile90.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile90; // } else if (WindowFunction.percentile98.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile98; // // } else if (WindowFunction.stddev.name().equals(name)) { // // windowFunction = WindowFunction.stddev; // } else if (WindowFunction.count.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.count; // // } else if (WindowFunction.density.name().equals(name)) { // // windowFunction = WindowFunction.density; // } // return windowFunction; // } // } // Path: scala/org/broad/igv/TileManager.java import java.util.List; import org.broad.igv.WindowFunction; /* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * @author jrobinso */ public class TileManager { TDFReader reader; public TileManager(TDFReader reader) { this.reader = reader; } public List<TDFTile> getTiles(String chr, int start, int end, int zoom) {
TDFDataset ds = reader.getDataset(chr, zoom, WindowFunction.mean);
AbeelLab/genometools
scala/org/broad/igv/TDFUtils.java
// Path: scala/org/broad/igv/WindowFunction.java // public enum WindowFunction { // // mean("Mean"), // median("Median"), // min("Minimum"), // max("Maximum"), // percentile2("2nd Percentile"), // percentile10("10th Percentile"), // percentile90("90th Percentile"), // percentile98("98th Percentile"), // // stddev("Standard Deviation"), // count("Count"); // // density("Density"); // // private String displayName = ""; // // WindowFunction(String displayName) { // this.displayName = displayName; // } // // public String getDisplayName() { // return displayName; // } // // static public WindowFunction getWindowFunction(String name) { // // WindowFunction windowFunction = null; // if (WindowFunction.mean.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.mean; // } else if (WindowFunction.median.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.median; // } else if (WindowFunction.min.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.min; // } else if (WindowFunction.max.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.max; // } else if (WindowFunction.percentile10.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile10; // } else if (WindowFunction.percentile90.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile90; // } else if (WindowFunction.percentile98.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile98; // // } else if (WindowFunction.stddev.name().equals(name)) { // // windowFunction = WindowFunction.stddev; // } else if (WindowFunction.count.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.count; // // } else if (WindowFunction.density.name().equals(name)) { // // windowFunction = WindowFunction.density; // } // return windowFunction; // } // }
import java.io.File; import java.io.FileNotFoundException; import java.net.URISyntaxException; import java.util.Map; import org.broad.igv.WindowFunction; import net.sf.samtools.seekablestream.SeekableFileStream;
int start = tile.getStartPosition(b); int end = tile.getEndPosition(b); if (start > endLocation) { break; } if (end >= startLocation) { System.out.print(tile.getStartPosition(b)); for (int t = 0; t < nTracks; t++) { System.out.print("\t" + tile.getValue(t, b)); } System.out.println(); } } } } } } /* * magic number (4 bytes) version index position index size (bytes) # of * window functions [window functions] track type (string) track line * (string) # of tracks [track names] */ public static void dumpSummary(String ibfFile) throws URISyntaxException, FileNotFoundException { TDFReader reader = TDFReader.getReader(new SeekableFileStream(new File(ibfFile))); System.out.println("Version: " + reader.getVersion()); System.out.println("Window Functions");
// Path: scala/org/broad/igv/WindowFunction.java // public enum WindowFunction { // // mean("Mean"), // median("Median"), // min("Minimum"), // max("Maximum"), // percentile2("2nd Percentile"), // percentile10("10th Percentile"), // percentile90("90th Percentile"), // percentile98("98th Percentile"), // // stddev("Standard Deviation"), // count("Count"); // // density("Density"); // // private String displayName = ""; // // WindowFunction(String displayName) { // this.displayName = displayName; // } // // public String getDisplayName() { // return displayName; // } // // static public WindowFunction getWindowFunction(String name) { // // WindowFunction windowFunction = null; // if (WindowFunction.mean.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.mean; // } else if (WindowFunction.median.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.median; // } else if (WindowFunction.min.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.min; // } else if (WindowFunction.max.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.max; // } else if (WindowFunction.percentile10.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile10; // } else if (WindowFunction.percentile90.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile90; // } else if (WindowFunction.percentile98.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.percentile98; // // } else if (WindowFunction.stddev.name().equals(name)) { // // windowFunction = WindowFunction.stddev; // } else if (WindowFunction.count.name().equalsIgnoreCase(name)) { // windowFunction = WindowFunction.count; // // } else if (WindowFunction.density.name().equals(name)) { // // windowFunction = WindowFunction.density; // } // return windowFunction; // } // } // Path: scala/org/broad/igv/TDFUtils.java import java.io.File; import java.io.FileNotFoundException; import java.net.URISyntaxException; import java.util.Map; import org.broad.igv.WindowFunction; import net.sf.samtools.seekablestream.SeekableFileStream; int start = tile.getStartPosition(b); int end = tile.getEndPosition(b); if (start > endLocation) { break; } if (end >= startLocation) { System.out.print(tile.getStartPosition(b)); for (int t = 0; t < nTracks; t++) { System.out.print("\t" + tile.getValue(t, b)); } System.out.println(); } } } } } } /* * magic number (4 bytes) version index position index size (bytes) # of * window functions [window functions] track type (string) track line * (string) # of tracks [track names] */ public static void dumpSummary(String ibfFile) throws URISyntaxException, FileNotFoundException { TDFReader reader = TDFReader.getReader(new SeekableFileStream(new File(ibfFile))); System.out.println("Version: " + reader.getVersion()); System.out.println("Window Functions");
for (WindowFunction wf : reader.getWindowFunctions()) {
AbeelLab/genometools
scala/org/broad/igv/TDFDataset.java
// Path: scala/org/broad/igv/StringUtils.java // public class StringUtils { // // // public static List<String> breakQuotedString(String string, char splitToken) { // // ArrayList<String> strings = new ArrayList(); // if (string.length() == 0) { // return strings; // } // // char[] characters = string.toCharArray(); // char c = characters[0]; // // boolean isQuoted = false; // StringBuffer buff = new StringBuffer(100); // for (int i = 0; i < characters.length; i++) { // c = characters[i]; // if (isQuoted) { // if (c == '"') { // isQuoted = false; // } // buff.append(c); // } else if (c == '"') { // isQuoted = true; // buff.append(c); // } else { // if (c == splitToken) { // strings.add(buff.toString().trim()); // buff.setLength(0); // } else { // buff.append(c); // } // } // } // if (buff.length() > 0) { // strings.add(buff.toString().trim()); // } // return strings; // // } // // // public static short genoToShort(String genotype) { // byte[] bytes = genotype.getBytes(); // return (short) ((bytes[0] & 0xff) << 8 | (bytes[1] & 0xff)); // } // // public static String readString(ByteBuffer byteBuffer) throws IOException { // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // byte b = -1; // while ((b = byteBuffer.get()) != 0) { // bytes.write(b); // } // return new String(bytes.toByteArray()); // } // // public static void main(String[] args) { // // String genotype = "AC"; // short genoShort = genoToShort(genotype); // // char allel1 = (char) ((genoShort >>> 8) & 0xFF); // char allel2 = (char) ((genoShort >>> 0) & 0xFF); // // System.out.println("Allele1: " + allel1); // System.out.println("Allele2: " + allel2); // // } // } // // Path: scala/abeel/genometools/bam2tdf/LRUCache.java // public class LRUCache<K, V> extends LinkedHashMap<K, V> { // // private static final long serialVersionUID = 3108325620729125294L; // // private Logger log = Logger.getLogger(LRUCache.class.getCanonicalName()); // // private int maxEntries = 100; // // public LRUCache(int maxEntries) { // super(maxEntries,0.75f,true); // this.maxEntries = maxEntries; // } // // @Override // protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { // if (size() > maxEntries) { // return true; // } else if (getAvailableMemoryFraction() < 0.1) { // log.info("Memory low. Free cache entry"); // return true; // } else { // return false; // } // } // public double getAvailableMemoryFraction() { // Runtime runtime = Runtime.getRuntime(); // long maxMemory = runtime.maxMemory(); // long allocatedMemory = runtime.totalMemory(); // long freeMemory = runtime.freeMemory(); // return (double) ((freeMemory + (maxMemory - allocatedMemory))) / maxMemory; // // } // }
import abeel.genometools.bam2tdf.LRUCache; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.broad.igv.StringUtils;
/* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * Represents the data for a particular chromosome and zoom level * * @author jrobinso */ public class TDFDataset extends TDFEntity { public enum DataType { BYTE, SHORT, INT, FLOAT, DOUBLE, STRING } ; DataType dataType; int tileWidth; long[] tilePositions; int[] tileSizes; int nTiles;
// Path: scala/org/broad/igv/StringUtils.java // public class StringUtils { // // // public static List<String> breakQuotedString(String string, char splitToken) { // // ArrayList<String> strings = new ArrayList(); // if (string.length() == 0) { // return strings; // } // // char[] characters = string.toCharArray(); // char c = characters[0]; // // boolean isQuoted = false; // StringBuffer buff = new StringBuffer(100); // for (int i = 0; i < characters.length; i++) { // c = characters[i]; // if (isQuoted) { // if (c == '"') { // isQuoted = false; // } // buff.append(c); // } else if (c == '"') { // isQuoted = true; // buff.append(c); // } else { // if (c == splitToken) { // strings.add(buff.toString().trim()); // buff.setLength(0); // } else { // buff.append(c); // } // } // } // if (buff.length() > 0) { // strings.add(buff.toString().trim()); // } // return strings; // // } // // // public static short genoToShort(String genotype) { // byte[] bytes = genotype.getBytes(); // return (short) ((bytes[0] & 0xff) << 8 | (bytes[1] & 0xff)); // } // // public static String readString(ByteBuffer byteBuffer) throws IOException { // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // byte b = -1; // while ((b = byteBuffer.get()) != 0) { // bytes.write(b); // } // return new String(bytes.toByteArray()); // } // // public static void main(String[] args) { // // String genotype = "AC"; // short genoShort = genoToShort(genotype); // // char allel1 = (char) ((genoShort >>> 8) & 0xFF); // char allel2 = (char) ((genoShort >>> 0) & 0xFF); // // System.out.println("Allele1: " + allel1); // System.out.println("Allele2: " + allel2); // // } // } // // Path: scala/abeel/genometools/bam2tdf/LRUCache.java // public class LRUCache<K, V> extends LinkedHashMap<K, V> { // // private static final long serialVersionUID = 3108325620729125294L; // // private Logger log = Logger.getLogger(LRUCache.class.getCanonicalName()); // // private int maxEntries = 100; // // public LRUCache(int maxEntries) { // super(maxEntries,0.75f,true); // this.maxEntries = maxEntries; // } // // @Override // protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { // if (size() > maxEntries) { // return true; // } else if (getAvailableMemoryFraction() < 0.1) { // log.info("Memory low. Free cache entry"); // return true; // } else { // return false; // } // } // public double getAvailableMemoryFraction() { // Runtime runtime = Runtime.getRuntime(); // long maxMemory = runtime.maxMemory(); // long allocatedMemory = runtime.totalMemory(); // long freeMemory = runtime.freeMemory(); // return (double) ((freeMemory + (maxMemory - allocatedMemory))) / maxMemory; // // } // } // Path: scala/org/broad/igv/TDFDataset.java import abeel.genometools.bam2tdf.LRUCache; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.broad.igv.StringUtils; /* * Copyright (c) 2007-2010 by The Broad Institute, Inc. and the Massachusetts Institute of Technology. * All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), Version 2.1 which * is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR WARRANTIES OF * ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT * OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR * RESPECTIVE TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES OF * ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, ECONOMIC * DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER THE BROAD OR MIT SHALL * BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE * FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv; /** * Represents the data for a particular chromosome and zoom level * * @author jrobinso */ public class TDFDataset extends TDFEntity { public enum DataType { BYTE, SHORT, INT, FLOAT, DOUBLE, STRING } ; DataType dataType; int tileWidth; long[] tilePositions; int[] tileSizes; int nTiles;
LRUCache<String, TDFTile> cache = new LRUCache(20);
AbeelLab/genometools
scala/org/broad/igv/TDFDataset.java
// Path: scala/org/broad/igv/StringUtils.java // public class StringUtils { // // // public static List<String> breakQuotedString(String string, char splitToken) { // // ArrayList<String> strings = new ArrayList(); // if (string.length() == 0) { // return strings; // } // // char[] characters = string.toCharArray(); // char c = characters[0]; // // boolean isQuoted = false; // StringBuffer buff = new StringBuffer(100); // for (int i = 0; i < characters.length; i++) { // c = characters[i]; // if (isQuoted) { // if (c == '"') { // isQuoted = false; // } // buff.append(c); // } else if (c == '"') { // isQuoted = true; // buff.append(c); // } else { // if (c == splitToken) { // strings.add(buff.toString().trim()); // buff.setLength(0); // } else { // buff.append(c); // } // } // } // if (buff.length() > 0) { // strings.add(buff.toString().trim()); // } // return strings; // // } // // // public static short genoToShort(String genotype) { // byte[] bytes = genotype.getBytes(); // return (short) ((bytes[0] & 0xff) << 8 | (bytes[1] & 0xff)); // } // // public static String readString(ByteBuffer byteBuffer) throws IOException { // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // byte b = -1; // while ((b = byteBuffer.get()) != 0) { // bytes.write(b); // } // return new String(bytes.toByteArray()); // } // // public static void main(String[] args) { // // String genotype = "AC"; // short genoShort = genoToShort(genotype); // // char allel1 = (char) ((genoShort >>> 8) & 0xFF); // char allel2 = (char) ((genoShort >>> 0) & 0xFF); // // System.out.println("Allele1: " + allel1); // System.out.println("Allele2: " + allel2); // // } // } // // Path: scala/abeel/genometools/bam2tdf/LRUCache.java // public class LRUCache<K, V> extends LinkedHashMap<K, V> { // // private static final long serialVersionUID = 3108325620729125294L; // // private Logger log = Logger.getLogger(LRUCache.class.getCanonicalName()); // // private int maxEntries = 100; // // public LRUCache(int maxEntries) { // super(maxEntries,0.75f,true); // this.maxEntries = maxEntries; // } // // @Override // protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { // if (size() > maxEntries) { // return true; // } else if (getAvailableMemoryFraction() < 0.1) { // log.info("Memory low. Free cache entry"); // return true; // } else { // return false; // } // } // public double getAvailableMemoryFraction() { // Runtime runtime = Runtime.getRuntime(); // long maxMemory = runtime.maxMemory(); // long allocatedMemory = runtime.totalMemory(); // long freeMemory = runtime.freeMemory(); // return (double) ((freeMemory + (maxMemory - allocatedMemory))) / maxMemory; // // } // }
import abeel.genometools.bam2tdf.LRUCache; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.broad.igv.StringUtils;
Arrays.fill(tilePositions, -1); } public TDFDataset(String name, ByteBuffer byteBuffer, TDFReader reader) throws IOException { super(name); this.reader = reader; fill(byteBuffer); } public void write(BufferedByteWriter dos) throws IOException { writeAttributes(dos); writeString(dos, dataType.toString()); dos.putFloat(tileWidth); // dos.writeFloat(binWidth); dos.putInt(tilePositions.length); for (int i = 0; i < tilePositions.length; i++) { dos.putLong(tilePositions[i]); dos.putInt(tileSizes[i]); } } private void fill(ByteBuffer byteBuffer) throws IOException { // Attributes readAttributes(byteBuffer);
// Path: scala/org/broad/igv/StringUtils.java // public class StringUtils { // // // public static List<String> breakQuotedString(String string, char splitToken) { // // ArrayList<String> strings = new ArrayList(); // if (string.length() == 0) { // return strings; // } // // char[] characters = string.toCharArray(); // char c = characters[0]; // // boolean isQuoted = false; // StringBuffer buff = new StringBuffer(100); // for (int i = 0; i < characters.length; i++) { // c = characters[i]; // if (isQuoted) { // if (c == '"') { // isQuoted = false; // } // buff.append(c); // } else if (c == '"') { // isQuoted = true; // buff.append(c); // } else { // if (c == splitToken) { // strings.add(buff.toString().trim()); // buff.setLength(0); // } else { // buff.append(c); // } // } // } // if (buff.length() > 0) { // strings.add(buff.toString().trim()); // } // return strings; // // } // // // public static short genoToShort(String genotype) { // byte[] bytes = genotype.getBytes(); // return (short) ((bytes[0] & 0xff) << 8 | (bytes[1] & 0xff)); // } // // public static String readString(ByteBuffer byteBuffer) throws IOException { // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // byte b = -1; // while ((b = byteBuffer.get()) != 0) { // bytes.write(b); // } // return new String(bytes.toByteArray()); // } // // public static void main(String[] args) { // // String genotype = "AC"; // short genoShort = genoToShort(genotype); // // char allel1 = (char) ((genoShort >>> 8) & 0xFF); // char allel2 = (char) ((genoShort >>> 0) & 0xFF); // // System.out.println("Allele1: " + allel1); // System.out.println("Allele2: " + allel2); // // } // } // // Path: scala/abeel/genometools/bam2tdf/LRUCache.java // public class LRUCache<K, V> extends LinkedHashMap<K, V> { // // private static final long serialVersionUID = 3108325620729125294L; // // private Logger log = Logger.getLogger(LRUCache.class.getCanonicalName()); // // private int maxEntries = 100; // // public LRUCache(int maxEntries) { // super(maxEntries,0.75f,true); // this.maxEntries = maxEntries; // } // // @Override // protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { // if (size() > maxEntries) { // return true; // } else if (getAvailableMemoryFraction() < 0.1) { // log.info("Memory low. Free cache entry"); // return true; // } else { // return false; // } // } // public double getAvailableMemoryFraction() { // Runtime runtime = Runtime.getRuntime(); // long maxMemory = runtime.maxMemory(); // long allocatedMemory = runtime.totalMemory(); // long freeMemory = runtime.freeMemory(); // return (double) ((freeMemory + (maxMemory - allocatedMemory))) / maxMemory; // // } // } // Path: scala/org/broad/igv/TDFDataset.java import abeel.genometools.bam2tdf.LRUCache; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.broad.igv.StringUtils; Arrays.fill(tilePositions, -1); } public TDFDataset(String name, ByteBuffer byteBuffer, TDFReader reader) throws IOException { super(name); this.reader = reader; fill(byteBuffer); } public void write(BufferedByteWriter dos) throws IOException { writeAttributes(dos); writeString(dos, dataType.toString()); dos.putFloat(tileWidth); // dos.writeFloat(binWidth); dos.putInt(tilePositions.length); for (int i = 0; i < tilePositions.length; i++) { dos.putLong(tilePositions[i]); dos.putInt(tileSizes[i]); } } private void fill(ByteBuffer byteBuffer) throws IOException { // Attributes readAttributes(byteBuffer);
String typeString = StringUtils.readString(byteBuffer);
GluuFederation/SCIM-Client
src/main/java/gluu/scim2/client/UmaScimClient.java
// Path: src/main/java/gluu/scim2/client/exception/ScimInitializationException.java // public class ScimInitializationException extends RuntimeException { // // private static final long serialVersionUID = -6376075805135656133L; // // public ScimInitializationException(String message) { // super(message); // } // // public ScimInitializationException(String message, Throwable cause) { // super(message, cause); // } // // }
import java.util.List; import javax.ws.rs.core.Response; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.gluu.oxauth.model.common.AuthenticationMethod; import org.gluu.oxauth.model.common.GrantType; import org.gluu.oxauth.model.crypto.OxAuthCryptoProvider; import org.gluu.oxauth.model.token.ClientAssertionType; import org.gluu.oxauth.model.uma.UmaMetadata; import org.gluu.oxauth.model.uma.UmaTokenResponse; import org.gluu.util.StringHelper; import org.gluu.oxauth.client.TokenRequest; import org.gluu.oxauth.client.uma.UmaClientFactory; import org.gluu.oxauth.client.uma.UmaTokenService; import gluu.scim2.client.exception.ScimInitializationException;
/** * Recomputes a new RPT according to UMA workflow if the response passed as parameter has status code 401 (unauthorized). * @param response A Response object corresponding to the request obtained in the previous call to a service method * @return If the parameter passed has a status code different to 401, it returns false. Otherwise it returns the success * of the attempt made to get a new RPT */ @Override boolean authorize(Response response) { boolean value = false; if (response.getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()) { try { String permissionTicketResponse = response.getHeaderString("WWW-Authenticate"); String permissionTicket = null; String asUri = null; String[] headerKeyValues = StringHelper.split(permissionTicketResponse, ","); for (String headerKeyValue : headerKeyValues) { if (headerKeyValue.startsWith("ticket=")) { permissionTicket = headerKeyValue.substring(7); } if (headerKeyValue.startsWith("as_uri=")) { asUri = headerKeyValue.substring(7); } } value= StringHelper.isNotEmpty(asUri) && StringHelper.isNotEmpty(permissionTicket) && obtainAuthorizedRpt(asUri, permissionTicket); } catch (Exception e) {
// Path: src/main/java/gluu/scim2/client/exception/ScimInitializationException.java // public class ScimInitializationException extends RuntimeException { // // private static final long serialVersionUID = -6376075805135656133L; // // public ScimInitializationException(String message) { // super(message); // } // // public ScimInitializationException(String message, Throwable cause) { // super(message, cause); // } // // } // Path: src/main/java/gluu/scim2/client/UmaScimClient.java import java.util.List; import javax.ws.rs.core.Response; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.gluu.oxauth.model.common.AuthenticationMethod; import org.gluu.oxauth.model.common.GrantType; import org.gluu.oxauth.model.crypto.OxAuthCryptoProvider; import org.gluu.oxauth.model.token.ClientAssertionType; import org.gluu.oxauth.model.uma.UmaMetadata; import org.gluu.oxauth.model.uma.UmaTokenResponse; import org.gluu.util.StringHelper; import org.gluu.oxauth.client.TokenRequest; import org.gluu.oxauth.client.uma.UmaClientFactory; import org.gluu.oxauth.client.uma.UmaTokenService; import gluu.scim2.client.exception.ScimInitializationException; /** * Recomputes a new RPT according to UMA workflow if the response passed as parameter has status code 401 (unauthorized). * @param response A Response object corresponding to the request obtained in the previous call to a service method * @return If the parameter passed has a status code different to 401, it returns false. Otherwise it returns the success * of the attempt made to get a new RPT */ @Override boolean authorize(Response response) { boolean value = false; if (response.getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()) { try { String permissionTicketResponse = response.getHeaderString("WWW-Authenticate"); String permissionTicket = null; String asUri = null; String[] headerKeyValues = StringHelper.split(permissionTicketResponse, ","); for (String headerKeyValue : headerKeyValues) { if (headerKeyValue.startsWith("ticket=")) { permissionTicket = headerKeyValue.substring(7); } if (headerKeyValue.startsWith("as_uri=")) { asUri = headerKeyValue.substring(7); } } value= StringHelper.isNotEmpty(asUri) && StringHelper.isNotEmpty(permissionTicket) && obtainAuthorizedRpt(asUri, permissionTicket); } catch (Exception e) {
throw new ScimInitializationException(e.getMessage(), e);
GluuFederation/SCIM-Client
src/main/java/gluu/scim2/client/rest/provider/AuthorizationInjectionFilter.java
// Path: src/main/java/gluu/scim2/client/ClientMap.java // public class ClientMap { // // private static ClientMap map = new ClientMap(); // // private static Map<Client, String> mappings = new HashMap<>(); // // private ClientMap() { // } // // /** // * Puts a new client/value pair in the map. If client already exists, the value is replaced. // * // * @param client RestEasy client // * @param value Value to associate to this client - normally an access token // */ // public static void update(Client client, String value) { // mappings.put(client, value); // } // // /** // * Removes a client from the map and then calls its close method to free resources. // * // * @param client Client to remove // */ // public static void remove(Client client) { // //Frees the resources associated to this RestEasy client // client.close(); // mappings.remove(client); // } // // /** // * Gets the value associated to this client in the map. // * // * @param client RestEasy client // * @return A string value. If there is no entry for client in the map, returns null // */ // public static String getValue(Client client) { // return mappings.get(client); // } // // /** // * Flushes the client/value map (it will be empty after invocation). // * Call this method when your application is being shut-down. // */ // public static void clean() { // for (Client client : mappings.keySet()) { // remove(client); // } // } // // }
import gluu.scim2.client.ClientMap; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; import java.util.Arrays; import java.util.Collections; import java.util.Optional;
package gluu.scim2.client.rest.provider; /** * A Client-side filter employed to "inject" headers to the outgoing request. This filter applies only for * requests issued by concrete instances of {@link gluu.scim2.client.AbstractScimClient AbstractScimClient} class. * <p>Developers do not need to manipulate this class for their SCIM applications.</p> */ /* * Created by jgomer on 2017-11-25. */ @Provider public class AuthorizationInjectionFilter implements ClientRequestFilter { private Logger logger = LogManager.getLogger(getClass()); public void filter(ClientRequestContext context) { MultivaluedMap<String, Object> headers = context.getHeaders();
// Path: src/main/java/gluu/scim2/client/ClientMap.java // public class ClientMap { // // private static ClientMap map = new ClientMap(); // // private static Map<Client, String> mappings = new HashMap<>(); // // private ClientMap() { // } // // /** // * Puts a new client/value pair in the map. If client already exists, the value is replaced. // * // * @param client RestEasy client // * @param value Value to associate to this client - normally an access token // */ // public static void update(Client client, String value) { // mappings.put(client, value); // } // // /** // * Removes a client from the map and then calls its close method to free resources. // * // * @param client Client to remove // */ // public static void remove(Client client) { // //Frees the resources associated to this RestEasy client // client.close(); // mappings.remove(client); // } // // /** // * Gets the value associated to this client in the map. // * // * @param client RestEasy client // * @return A string value. If there is no entry for client in the map, returns null // */ // public static String getValue(Client client) { // return mappings.get(client); // } // // /** // * Flushes the client/value map (it will be empty after invocation). // * Call this method when your application is being shut-down. // */ // public static void clean() { // for (Client client : mappings.keySet()) { // remove(client); // } // } // // } // Path: src/main/java/gluu/scim2/client/rest/provider/AuthorizationInjectionFilter.java import gluu.scim2.client.ClientMap; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; import java.util.Arrays; import java.util.Collections; import java.util.Optional; package gluu.scim2.client.rest.provider; /** * A Client-side filter employed to "inject" headers to the outgoing request. This filter applies only for * requests issued by concrete instances of {@link gluu.scim2.client.AbstractScimClient AbstractScimClient} class. * <p>Developers do not need to manipulate this class for their SCIM applications.</p> */ /* * Created by jgomer on 2017-11-25. */ @Provider public class AuthorizationInjectionFilter implements ClientRequestFilter { private Logger logger = LogManager.getLogger(getClass()); public void filter(ClientRequestContext context) { MultivaluedMap<String, Object> headers = context.getHeaders();
String authzHeader = ClientMap.getValue(context.getClient());
TestFX/Monocle
src/main/java/com/sun/glass/ui/monocle/AndroidInputDeviceRegistry.java
// Path: src/main/java/com/sun/glass/ui/monocle/TouchState.java // static class Point { // int id; // int x; // int y; // // /** // * Copies a touch point's data to a target Point // * // * @param target the Point object to which to copy this object's data // */ // void copyTo(Point target) { // target.id = id; // target.x = x; // target.y = y; // } // @Override // public String toString() { // return "TouchState.Point[id=" + id + ",x=" + x + ",y=" + y + "]"; // } // }
import com.sun.glass.ui.monocle.TouchState.Point; import java.security.AllPermission; import javafx.application.Platform;
/* * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.glass.ui.monocle; public class AndroidInputDeviceRegistry extends InputDeviceRegistry { private static AndroidInputDeviceRegistry instance = new AndroidInputDeviceRegistry(); private AndroidInputDevice androidDevice; private AndroidInputProcessor processor; private final KeyState keyState = new KeyState(); static AndroidInputDeviceRegistry getInstance() { return instance; } public static void registerDevice() { Platform.runLater(() -> instance.createDevice()); } public static void gotTouchEventFromNative(int count, int[] actions, int[] ids, int[] x, int[] y, int primary) { TouchState touchState = new TouchState(); if (primary == -1) { System.out.println("don't add points, primary = -1"); } else { for (int i = 0; i < count; i++) {
// Path: src/main/java/com/sun/glass/ui/monocle/TouchState.java // static class Point { // int id; // int x; // int y; // // /** // * Copies a touch point's data to a target Point // * // * @param target the Point object to which to copy this object's data // */ // void copyTo(Point target) { // target.id = id; // target.x = x; // target.y = y; // } // @Override // public String toString() { // return "TouchState.Point[id=" + id + ",x=" + x + ",y=" + y + "]"; // } // } // Path: src/main/java/com/sun/glass/ui/monocle/AndroidInputDeviceRegistry.java import com.sun.glass.ui.monocle.TouchState.Point; import java.security.AllPermission; import javafx.application.Platform; /* * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.glass.ui.monocle; public class AndroidInputDeviceRegistry extends InputDeviceRegistry { private static AndroidInputDeviceRegistry instance = new AndroidInputDeviceRegistry(); private AndroidInputDevice androidDevice; private AndroidInputProcessor processor; private final KeyState keyState = new KeyState(); static AndroidInputDeviceRegistry getInstance() { return instance; } public static void registerDevice() { Platform.runLater(() -> instance.createDevice()); } public static void gotTouchEventFromNative(int count, int[] actions, int[] ids, int[] x, int[] y, int primary) { TouchState touchState = new TouchState(); if (primary == -1) { System.out.println("don't add points, primary = -1"); } else { for (int i = 0; i < count; i++) {
Point p = new Point();
concordion/cubano
cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/dataWriter/RawDataWriter.java
// Path: cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/logging/LogManager.java // public class LogManager { // private boolean logRequest; // private boolean logRequestDetails; // // private LogWriter logWriter; // private LogBuffer logBuffer = null; // // public LogManager(LogWriter logWriter, boolean logRequestDetails) { // if (logWriter == null) { // this.logRequest = false; // this.logRequestDetails = false; // } else { // this.logRequest = HttpEasyDefaults.getLogRequest() || logRequestDetails; // this.logRequestDetails = logRequestDetails; // } // // this.logWriter = logWriter; // } // // public boolean isLogRequestDetails() { // return logRequestDetails; // } // // public void info(String msg, Object... args) { // if (logWriter == null) // return; // // if (logRequest) { // logWriter.info(msg, args); // } // } // // public void error(String message, Throwable t) { // if (logWriter == null) // return; // // logWriter.error(message, t); // } // // public void flushInfo() { // if (logWriter != null) { // if (this.logRequest && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // // String[] lines = logBuffer.toString().split("\\r?\\n"); // // for (String line : lines) { // logWriter.info(line); // } // } // } // } // // logBuffer = null; // } // // public void flushRequest() { // if (logWriter != null) { // if (this.logRequestDetails && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // logWriter.request(logBuffer.toString()); // } // } // } // // logBuffer = null; // } // // public void flushResponse() { // if (logWriter != null) { // if (this.logRequestDetails && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // logWriter.response(logBuffer.toString()); // } // } // } // // logBuffer = null; // } // // public LogBuffer getBuffer() { // if (this.logBuffer == null) { // this.logBuffer = new LogBuffer(); // } // // return this.logBuffer; // } // }
import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import org.concordion.cubano.driver.http.logging.LogManager; import com.google.common.net.MediaType;
package org.concordion.cubano.driver.http.dataWriter; /** * Attach a File or data to an http request. * * @author Andrew Sumner */ public class RawDataWriter implements DataWriter { private HttpURLConnection connection; private String mediaType; private byte[] postEndcoded = null; private File uploadFile = null; private InputStream uploadStream = null; private String uploadFileName; /** * Constructor. * * @param connection The connection * @param rawData data (File or String) * @param rawDataMediaType Type of attachment * @param fileName file name for InputStream */ public RawDataWriter(HttpURLConnection connection, Object rawData, MediaType rawDataMediaType, String fileName) { this.connection = connection; this.mediaType = rawDataMediaType.toString(); if (rawData instanceof File) { uploadFile = (File) rawData; connection.setRequestProperty("Content-Type", rawDataMediaType.toString()); connection.setRequestProperty("Content-Length", Long.toString(uploadFile.length())); connection.setFixedLengthStreamingMode(uploadFile.length()); } else if (rawData instanceof InputStream) { uploadStream = (InputStream) rawData; uploadFileName = fileName; connection.setRequestProperty("Content-Type", rawDataMediaType.toString()); } else { // Assume data is encoded correctly this.postEndcoded = String.valueOf(rawData).getBytes(StandardCharsets.UTF_8); connection.setRequestProperty("charset", StandardCharsets.UTF_8.name()); connection.setRequestProperty("Content-Type", rawDataMediaType.toString()); connection.setRequestProperty("Content-Length", Integer.toString(postEndcoded.length)); } } @Override
// Path: cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/logging/LogManager.java // public class LogManager { // private boolean logRequest; // private boolean logRequestDetails; // // private LogWriter logWriter; // private LogBuffer logBuffer = null; // // public LogManager(LogWriter logWriter, boolean logRequestDetails) { // if (logWriter == null) { // this.logRequest = false; // this.logRequestDetails = false; // } else { // this.logRequest = HttpEasyDefaults.getLogRequest() || logRequestDetails; // this.logRequestDetails = logRequestDetails; // } // // this.logWriter = logWriter; // } // // public boolean isLogRequestDetails() { // return logRequestDetails; // } // // public void info(String msg, Object... args) { // if (logWriter == null) // return; // // if (logRequest) { // logWriter.info(msg, args); // } // } // // public void error(String message, Throwable t) { // if (logWriter == null) // return; // // logWriter.error(message, t); // } // // public void flushInfo() { // if (logWriter != null) { // if (this.logRequest && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // // String[] lines = logBuffer.toString().split("\\r?\\n"); // // for (String line : lines) { // logWriter.info(line); // } // } // } // } // // logBuffer = null; // } // // public void flushRequest() { // if (logWriter != null) { // if (this.logRequestDetails && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // logWriter.request(logBuffer.toString()); // } // } // } // // logBuffer = null; // } // // public void flushResponse() { // if (logWriter != null) { // if (this.logRequestDetails && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // logWriter.response(logBuffer.toString()); // } // } // } // // logBuffer = null; // } // // public LogBuffer getBuffer() { // if (this.logBuffer == null) { // this.logBuffer = new LogBuffer(); // } // // return this.logBuffer; // } // } // Path: cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/dataWriter/RawDataWriter.java import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import org.concordion.cubano.driver.http.logging.LogManager; import com.google.common.net.MediaType; package org.concordion.cubano.driver.http.dataWriter; /** * Attach a File or data to an http request. * * @author Andrew Sumner */ public class RawDataWriter implements DataWriter { private HttpURLConnection connection; private String mediaType; private byte[] postEndcoded = null; private File uploadFile = null; private InputStream uploadStream = null; private String uploadFileName; /** * Constructor. * * @param connection The connection * @param rawData data (File or String) * @param rawDataMediaType Type of attachment * @param fileName file name for InputStream */ public RawDataWriter(HttpURLConnection connection, Object rawData, MediaType rawDataMediaType, String fileName) { this.connection = connection; this.mediaType = rawDataMediaType.toString(); if (rawData instanceof File) { uploadFile = (File) rawData; connection.setRequestProperty("Content-Type", rawDataMediaType.toString()); connection.setRequestProperty("Content-Length", Long.toString(uploadFile.length())); connection.setFixedLengthStreamingMode(uploadFile.length()); } else if (rawData instanceof InputStream) { uploadStream = (InputStream) rawData; uploadFileName = fileName; connection.setRequestProperty("Content-Type", rawDataMediaType.toString()); } else { // Assume data is encoded correctly this.postEndcoded = String.valueOf(rawData).getBytes(StandardCharsets.UTF_8); connection.setRequestProperty("charset", StandardCharsets.UTF_8.name()); connection.setRequestProperty("Content-Type", rawDataMediaType.toString()); connection.setRequestProperty("Content-Length", Integer.toString(postEndcoded.length)); } } @Override
public void write(LogManager logger) throws IOException {
concordion/cubano
cubano-concordion/src/main/java/org/concordion/cubano/framework/ConcordionBase.java
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureListener.java // public interface FixtureListener { // void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureLogger.java // public class FixtureLogger implements FixtureListener { // @Override // public void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the acceptance test class {} on thread {}", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // // @Override // public void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the test suite (called from test class {} on thread {}). ", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceRegistry.java // public interface ResourceRegistry { // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope); // // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. Call the // * relevant methods on <code>listener</code> before and after closing the resource. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope, CloseListener listener); // // /** // * Ascertains whether the <code>resource</code> is registered at the specified <code>scope</code>. // */ // boolean isRegistered(Closeable resource, ResourceScope scope); // // /** // * Close and deregister the specified <code>resource</code> from all scopes. // */ // void closeResource(Closeable resource); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // }
import org.apache.commons.lang3.tuple.ImmutablePair; import org.concordion.api.*; import org.concordion.api.option.ConcordionOptions; import org.concordion.api.option.MarkdownExtensions; import org.concordion.cubano.framework.fixture.FixtureListener; import org.concordion.cubano.framework.fixture.FixtureLogger; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceRegistry; import org.concordion.cubano.framework.resource.ResourceScope; import org.concordion.integration.junit4.ConcordionRunner; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.EnumSet; import java.util.Optional; import java.util.concurrent.ConcurrentLinkedDeque;
package org.concordion.cubano.framework; /** * Basic Concordion Fixture for inheritance by index fixtures with no tests. * <p> * Supports the automatic closing of {@link Closeable} resources at either the {@link ResourceScope#SPECIFICATION} * or {@link ResourceScope#SUITE} level. After calling {@link #registerCloseableResource(Closeable, ResourceScope)} * , the resource will automatically be closed at the end of the specified scope. * Resources will be closed in the reverse order to which they were registered. * </p> * The resource registry is thread-safe for SUITE scoped resources. It is not thread-safe for EXAMPLE and SPECIFICATION * scoped resources which rely on Concordion creating a new instance for each test. **/ @RunWith(ConcordionRunner.class) @ConcordionOptions(markdownExtensions = {MarkdownExtensions.HARDWRAPS, MarkdownExtensions.AUTOLINKS})
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureListener.java // public interface FixtureListener { // void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureLogger.java // public class FixtureLogger implements FixtureListener { // @Override // public void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the acceptance test class {} on thread {}", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // // @Override // public void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the test suite (called from test class {} on thread {}). ", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceRegistry.java // public interface ResourceRegistry { // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope); // // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. Call the // * relevant methods on <code>listener</code> before and after closing the resource. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope, CloseListener listener); // // /** // * Ascertains whether the <code>resource</code> is registered at the specified <code>scope</code>. // */ // boolean isRegistered(Closeable resource, ResourceScope scope); // // /** // * Close and deregister the specified <code>resource</code> from all scopes. // */ // void closeResource(Closeable resource); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // } // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/ConcordionBase.java import org.apache.commons.lang3.tuple.ImmutablePair; import org.concordion.api.*; import org.concordion.api.option.ConcordionOptions; import org.concordion.api.option.MarkdownExtensions; import org.concordion.cubano.framework.fixture.FixtureListener; import org.concordion.cubano.framework.fixture.FixtureLogger; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceRegistry; import org.concordion.cubano.framework.resource.ResourceScope; import org.concordion.integration.junit4.ConcordionRunner; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.EnumSet; import java.util.Optional; import java.util.concurrent.ConcurrentLinkedDeque; package org.concordion.cubano.framework; /** * Basic Concordion Fixture for inheritance by index fixtures with no tests. * <p> * Supports the automatic closing of {@link Closeable} resources at either the {@link ResourceScope#SPECIFICATION} * or {@link ResourceScope#SUITE} level. After calling {@link #registerCloseableResource(Closeable, ResourceScope)} * , the resource will automatically be closed at the end of the specified scope. * Resources will be closed in the reverse order to which they were registered. * </p> * The resource registry is thread-safe for SUITE scoped resources. It is not thread-safe for EXAMPLE and SPECIFICATION * scoped resources which rely on Concordion creating a new instance for each test. **/ @RunWith(ConcordionRunner.class) @ConcordionOptions(markdownExtensions = {MarkdownExtensions.HARDWRAPS, MarkdownExtensions.AUTOLINKS})
public abstract class ConcordionBase implements ResourceRegistry {
concordion/cubano
cubano-concordion/src/main/java/org/concordion/cubano/framework/ConcordionBase.java
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureListener.java // public interface FixtureListener { // void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureLogger.java // public class FixtureLogger implements FixtureListener { // @Override // public void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the acceptance test class {} on thread {}", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // // @Override // public void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the test suite (called from test class {} on thread {}). ", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceRegistry.java // public interface ResourceRegistry { // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope); // // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. Call the // * relevant methods on <code>listener</code> before and after closing the resource. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope, CloseListener listener); // // /** // * Ascertains whether the <code>resource</code> is registered at the specified <code>scope</code>. // */ // boolean isRegistered(Closeable resource, ResourceScope scope); // // /** // * Close and deregister the specified <code>resource</code> from all scopes. // */ // void closeResource(Closeable resource); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // }
import org.apache.commons.lang3.tuple.ImmutablePair; import org.concordion.api.*; import org.concordion.api.option.ConcordionOptions; import org.concordion.api.option.MarkdownExtensions; import org.concordion.cubano.framework.fixture.FixtureListener; import org.concordion.cubano.framework.fixture.FixtureLogger; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceRegistry; import org.concordion.cubano.framework.resource.ResourceScope; import org.concordion.integration.junit4.ConcordionRunner; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.EnumSet; import java.util.Optional; import java.util.concurrent.ConcurrentLinkedDeque;
package org.concordion.cubano.framework; /** * Basic Concordion Fixture for inheritance by index fixtures with no tests. * <p> * Supports the automatic closing of {@link Closeable} resources at either the {@link ResourceScope#SPECIFICATION} * or {@link ResourceScope#SUITE} level. After calling {@link #registerCloseableResource(Closeable, ResourceScope)} * , the resource will automatically be closed at the end of the specified scope. * Resources will be closed in the reverse order to which they were registered. * </p> * The resource registry is thread-safe for SUITE scoped resources. It is not thread-safe for EXAMPLE and SPECIFICATION * scoped resources which rely on Concordion creating a new instance for each test. **/ @RunWith(ConcordionRunner.class) @ConcordionOptions(markdownExtensions = {MarkdownExtensions.HARDWRAPS, MarkdownExtensions.AUTOLINKS}) public abstract class ConcordionBase implements ResourceRegistry { protected final Logger logger = LoggerFactory.getLogger(this.getClass());
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureListener.java // public interface FixtureListener { // void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureLogger.java // public class FixtureLogger implements FixtureListener { // @Override // public void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the acceptance test class {} on thread {}", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // // @Override // public void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the test suite (called from test class {} on thread {}). ", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceRegistry.java // public interface ResourceRegistry { // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope); // // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. Call the // * relevant methods on <code>listener</code> before and after closing the resource. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope, CloseListener listener); // // /** // * Ascertains whether the <code>resource</code> is registered at the specified <code>scope</code>. // */ // boolean isRegistered(Closeable resource, ResourceScope scope); // // /** // * Close and deregister the specified <code>resource</code> from all scopes. // */ // void closeResource(Closeable resource); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // } // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/ConcordionBase.java import org.apache.commons.lang3.tuple.ImmutablePair; import org.concordion.api.*; import org.concordion.api.option.ConcordionOptions; import org.concordion.api.option.MarkdownExtensions; import org.concordion.cubano.framework.fixture.FixtureListener; import org.concordion.cubano.framework.fixture.FixtureLogger; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceRegistry; import org.concordion.cubano.framework.resource.ResourceScope; import org.concordion.integration.junit4.ConcordionRunner; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.EnumSet; import java.util.Optional; import java.util.concurrent.ConcurrentLinkedDeque; package org.concordion.cubano.framework; /** * Basic Concordion Fixture for inheritance by index fixtures with no tests. * <p> * Supports the automatic closing of {@link Closeable} resources at either the {@link ResourceScope#SPECIFICATION} * or {@link ResourceScope#SUITE} level. After calling {@link #registerCloseableResource(Closeable, ResourceScope)} * , the resource will automatically be closed at the end of the specified scope. * Resources will be closed in the reverse order to which they were registered. * </p> * The resource registry is thread-safe for SUITE scoped resources. It is not thread-safe for EXAMPLE and SPECIFICATION * scoped resources which rely on Concordion creating a new instance for each test. **/ @RunWith(ConcordionRunner.class) @ConcordionOptions(markdownExtensions = {MarkdownExtensions.HARDWRAPS, MarkdownExtensions.AUTOLINKS}) public abstract class ConcordionBase implements ResourceRegistry { protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected FixtureListener fixtureListener = new FixtureLogger();
concordion/cubano
cubano-concordion/src/main/java/org/concordion/cubano/framework/ConcordionBase.java
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureListener.java // public interface FixtureListener { // void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureLogger.java // public class FixtureLogger implements FixtureListener { // @Override // public void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the acceptance test class {} on thread {}", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // // @Override // public void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the test suite (called from test class {} on thread {}). ", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceRegistry.java // public interface ResourceRegistry { // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope); // // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. Call the // * relevant methods on <code>listener</code> before and after closing the resource. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope, CloseListener listener); // // /** // * Ascertains whether the <code>resource</code> is registered at the specified <code>scope</code>. // */ // boolean isRegistered(Closeable resource, ResourceScope scope); // // /** // * Close and deregister the specified <code>resource</code> from all scopes. // */ // void closeResource(Closeable resource); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // }
import org.apache.commons.lang3.tuple.ImmutablePair; import org.concordion.api.*; import org.concordion.api.option.ConcordionOptions; import org.concordion.api.option.MarkdownExtensions; import org.concordion.cubano.framework.fixture.FixtureListener; import org.concordion.cubano.framework.fixture.FixtureLogger; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceRegistry; import org.concordion.cubano.framework.resource.ResourceScope; import org.concordion.integration.junit4.ConcordionRunner; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.EnumSet; import java.util.Optional; import java.util.concurrent.ConcurrentLinkedDeque;
package org.concordion.cubano.framework; /** * Basic Concordion Fixture for inheritance by index fixtures with no tests. * <p> * Supports the automatic closing of {@link Closeable} resources at either the {@link ResourceScope#SPECIFICATION} * or {@link ResourceScope#SUITE} level. After calling {@link #registerCloseableResource(Closeable, ResourceScope)} * , the resource will automatically be closed at the end of the specified scope. * Resources will be closed in the reverse order to which they were registered. * </p> * The resource registry is thread-safe for SUITE scoped resources. It is not thread-safe for EXAMPLE and SPECIFICATION * scoped resources which rely on Concordion creating a new instance for each test. **/ @RunWith(ConcordionRunner.class) @ConcordionOptions(markdownExtensions = {MarkdownExtensions.HARDWRAPS, MarkdownExtensions.AUTOLINKS}) public abstract class ConcordionBase implements ResourceRegistry { protected final Logger logger = LoggerFactory.getLogger(this.getClass());
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureListener.java // public interface FixtureListener { // void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureLogger.java // public class FixtureLogger implements FixtureListener { // @Override // public void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the acceptance test class {} on thread {}", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // // @Override // public void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the test suite (called from test class {} on thread {}). ", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceRegistry.java // public interface ResourceRegistry { // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope); // // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. Call the // * relevant methods on <code>listener</code> before and after closing the resource. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope, CloseListener listener); // // /** // * Ascertains whether the <code>resource</code> is registered at the specified <code>scope</code>. // */ // boolean isRegistered(Closeable resource, ResourceScope scope); // // /** // * Close and deregister the specified <code>resource</code> from all scopes. // */ // void closeResource(Closeable resource); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // } // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/ConcordionBase.java import org.apache.commons.lang3.tuple.ImmutablePair; import org.concordion.api.*; import org.concordion.api.option.ConcordionOptions; import org.concordion.api.option.MarkdownExtensions; import org.concordion.cubano.framework.fixture.FixtureListener; import org.concordion.cubano.framework.fixture.FixtureLogger; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceRegistry; import org.concordion.cubano.framework.resource.ResourceScope; import org.concordion.integration.junit4.ConcordionRunner; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.EnumSet; import java.util.Optional; import java.util.concurrent.ConcurrentLinkedDeque; package org.concordion.cubano.framework; /** * Basic Concordion Fixture for inheritance by index fixtures with no tests. * <p> * Supports the automatic closing of {@link Closeable} resources at either the {@link ResourceScope#SPECIFICATION} * or {@link ResourceScope#SUITE} level. After calling {@link #registerCloseableResource(Closeable, ResourceScope)} * , the resource will automatically be closed at the end of the specified scope. * Resources will be closed in the reverse order to which they were registered. * </p> * The resource registry is thread-safe for SUITE scoped resources. It is not thread-safe for EXAMPLE and SPECIFICATION * scoped resources which rely on Concordion creating a new instance for each test. **/ @RunWith(ConcordionRunner.class) @ConcordionOptions(markdownExtensions = {MarkdownExtensions.HARDWRAPS, MarkdownExtensions.AUTOLINKS}) public abstract class ConcordionBase implements ResourceRegistry { protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected FixtureListener fixtureListener = new FixtureLogger();
concordion/cubano
cubano-concordion/src/main/java/org/concordion/cubano/framework/ConcordionBase.java
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureListener.java // public interface FixtureListener { // void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureLogger.java // public class FixtureLogger implements FixtureListener { // @Override // public void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the acceptance test class {} on thread {}", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // // @Override // public void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the test suite (called from test class {} on thread {}). ", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceRegistry.java // public interface ResourceRegistry { // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope); // // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. Call the // * relevant methods on <code>listener</code> before and after closing the resource. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope, CloseListener listener); // // /** // * Ascertains whether the <code>resource</code> is registered at the specified <code>scope</code>. // */ // boolean isRegistered(Closeable resource, ResourceScope scope); // // /** // * Close and deregister the specified <code>resource</code> from all scopes. // */ // void closeResource(Closeable resource); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // }
import org.apache.commons.lang3.tuple.ImmutablePair; import org.concordion.api.*; import org.concordion.api.option.ConcordionOptions; import org.concordion.api.option.MarkdownExtensions; import org.concordion.cubano.framework.fixture.FixtureListener; import org.concordion.cubano.framework.fixture.FixtureLogger; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceRegistry; import org.concordion.cubano.framework.resource.ResourceScope; import org.concordion.integration.junit4.ConcordionRunner; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.EnumSet; import java.util.Optional; import java.util.concurrent.ConcurrentLinkedDeque;
package org.concordion.cubano.framework; /** * Basic Concordion Fixture for inheritance by index fixtures with no tests. * <p> * Supports the automatic closing of {@link Closeable} resources at either the {@link ResourceScope#SPECIFICATION} * or {@link ResourceScope#SUITE} level. After calling {@link #registerCloseableResource(Closeable, ResourceScope)} * , the resource will automatically be closed at the end of the specified scope. * Resources will be closed in the reverse order to which they were registered. * </p> * The resource registry is thread-safe for SUITE scoped resources. It is not thread-safe for EXAMPLE and SPECIFICATION * scoped resources which rely on Concordion creating a new instance for each test. **/ @RunWith(ConcordionRunner.class) @ConcordionOptions(markdownExtensions = {MarkdownExtensions.HARDWRAPS, MarkdownExtensions.AUTOLINKS}) public abstract class ConcordionBase implements ResourceRegistry { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected FixtureListener fixtureListener = new FixtureLogger();
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureListener.java // public interface FixtureListener { // void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger); // // void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger); // // void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger); // // void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/fixture/FixtureLogger.java // public class FixtureLogger implements FixtureListener { // @Override // public void beforeExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void afterExample(Class<? extends ConcordionBase> aClass, String exampleName, Logger logger) { // } // // @Override // public void beforeSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSpecification(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the acceptance test class {} on thread {}", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // // @Override // public void beforeSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // } // // @Override // public void afterSuite(Class<? extends ConcordionBase> aClass, Logger logger) { // logger.info("Tearing down the test suite (called from test class {} on thread {}). ", // aClass.getSimpleName(), Thread.currentThread().getName()); // } // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceRegistry.java // public interface ResourceRegistry { // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope); // // /** // * Automatically close the <code>resource</code> at the end of the specified <code>scope</code>. Call the // * relevant methods on <code>listener</code> before and after closing the resource. // */ // void registerCloseableResource(Closeable resource, ResourceScope scope, CloseListener listener); // // /** // * Ascertains whether the <code>resource</code> is registered at the specified <code>scope</code>. // */ // boolean isRegistered(Closeable resource, ResourceScope scope); // // /** // * Close and deregister the specified <code>resource</code> from all scopes. // */ // void closeResource(Closeable resource); // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // } // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/ConcordionBase.java import org.apache.commons.lang3.tuple.ImmutablePair; import org.concordion.api.*; import org.concordion.api.option.ConcordionOptions; import org.concordion.api.option.MarkdownExtensions; import org.concordion.cubano.framework.fixture.FixtureListener; import org.concordion.cubano.framework.fixture.FixtureLogger; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceRegistry; import org.concordion.cubano.framework.resource.ResourceScope; import org.concordion.integration.junit4.ConcordionRunner; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.EnumSet; import java.util.Optional; import java.util.concurrent.ConcurrentLinkedDeque; package org.concordion.cubano.framework; /** * Basic Concordion Fixture for inheritance by index fixtures with no tests. * <p> * Supports the automatic closing of {@link Closeable} resources at either the {@link ResourceScope#SPECIFICATION} * or {@link ResourceScope#SUITE} level. After calling {@link #registerCloseableResource(Closeable, ResourceScope)} * , the resource will automatically be closed at the end of the specified scope. * Resources will be closed in the reverse order to which they were registered. * </p> * The resource registry is thread-safe for SUITE scoped resources. It is not thread-safe for EXAMPLE and SPECIFICATION * scoped resources which rely on Concordion creating a new instance for each test. **/ @RunWith(ConcordionRunner.class) @ConcordionOptions(markdownExtensions = {MarkdownExtensions.HARDWRAPS, MarkdownExtensions.AUTOLINKS}) public abstract class ConcordionBase implements ResourceRegistry { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected FixtureListener fixtureListener = new FixtureLogger();
private final Deque<ImmutablePair<Closeable, CloseListener>> examplePairs = new ArrayDeque<>();
concordion/cubano
cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/HttpEasyReader.java
// Path: cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/logging/LogManager.java // public class LogManager { // private boolean logRequest; // private boolean logRequestDetails; // // private LogWriter logWriter; // private LogBuffer logBuffer = null; // // public LogManager(LogWriter logWriter, boolean logRequestDetails) { // if (logWriter == null) { // this.logRequest = false; // this.logRequestDetails = false; // } else { // this.logRequest = HttpEasyDefaults.getLogRequest() || logRequestDetails; // this.logRequestDetails = logRequestDetails; // } // // this.logWriter = logWriter; // } // // public boolean isLogRequestDetails() { // return logRequestDetails; // } // // public void info(String msg, Object... args) { // if (logWriter == null) // return; // // if (logRequest) { // logWriter.info(msg, args); // } // } // // public void error(String message, Throwable t) { // if (logWriter == null) // return; // // logWriter.error(message, t); // } // // public void flushInfo() { // if (logWriter != null) { // if (this.logRequest && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // // String[] lines = logBuffer.toString().split("\\r?\\n"); // // for (String line : lines) { // logWriter.info(line); // } // } // } // } // // logBuffer = null; // } // // public void flushRequest() { // if (logWriter != null) { // if (this.logRequestDetails && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // logWriter.request(logBuffer.toString()); // } // } // } // // logBuffer = null; // } // // public void flushResponse() { // if (logWriter != null) { // if (this.logRequestDetails && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // logWriter.response(logBuffer.toString()); // } // } // } // // logBuffer = null; // } // // public LogBuffer getBuffer() { // if (this.logBuffer == null) { // this.logBuffer = new LogBuffer(); // } // // return this.logBuffer; // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import javax.xml.parsers.ParserConfigurationException; import org.concordion.cubano.driver.http.logging.LogManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException;
package org.concordion.cubano.driver.http; /** * Response reader for HTTP requests, can parse JSON and XML and download files. * * @author Andrew Sumner */ public class HttpEasyReader { private HttpURLConnection connection; private String returned = null; private static final Logger LOGGER = LoggerFactory.getLogger(HttpEasyReader.class); /** * Create new HttpEasyReader. * * @param connection HttpURLConnection * @param request Request that is creating this reader * @throws HttpResponseException if request failed * @throws IOException for connection errors */ public HttpEasyReader(HttpURLConnection connection, HttpEasy request) throws HttpResponseException, IOException { this.connection = connection; Family responseFamily = getResponseCodeFamily(); logResponse(request); if (responseFamily != Family.SUCCESSFUL) { if (listContains(request.ignoreResponseCodes, getResponseCode())) { return; } if (listContains(request.ignoreResponseFamily, responseFamily)) { return; } throw new HttpResponseException(getResponseCode(), "Server returned HTTP response code " + connection.getResponseCode() + ": " + connection.getResponseMessage() + "\r\nResponse Content: " + asString()); } } private void logResponse(HttpEasy request) throws IOException { if (!request.getLogManager().isLogRequestDetails()) { return; }
// Path: cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/logging/LogManager.java // public class LogManager { // private boolean logRequest; // private boolean logRequestDetails; // // private LogWriter logWriter; // private LogBuffer logBuffer = null; // // public LogManager(LogWriter logWriter, boolean logRequestDetails) { // if (logWriter == null) { // this.logRequest = false; // this.logRequestDetails = false; // } else { // this.logRequest = HttpEasyDefaults.getLogRequest() || logRequestDetails; // this.logRequestDetails = logRequestDetails; // } // // this.logWriter = logWriter; // } // // public boolean isLogRequestDetails() { // return logRequestDetails; // } // // public void info(String msg, Object... args) { // if (logWriter == null) // return; // // if (logRequest) { // logWriter.info(msg, args); // } // } // // public void error(String message, Throwable t) { // if (logWriter == null) // return; // // logWriter.error(message, t); // } // // public void flushInfo() { // if (logWriter != null) { // if (this.logRequest && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // // String[] lines = logBuffer.toString().split("\\r?\\n"); // // for (String line : lines) { // logWriter.info(line); // } // } // } // } // // logBuffer = null; // } // // public void flushRequest() { // if (logWriter != null) { // if (this.logRequestDetails && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // logWriter.request(logBuffer.toString()); // } // } // } // // logBuffer = null; // } // // public void flushResponse() { // if (logWriter != null) { // if (this.logRequestDetails && logBuffer != null) { // if (logBuffer.length() > 0) { // logBuffer.trimNewLine(); // logWriter.response(logBuffer.toString()); // } // } // } // // logBuffer = null; // } // // public LogBuffer getBuffer() { // if (this.logBuffer == null) { // this.logBuffer = new LogBuffer(); // } // // return this.logBuffer; // } // } // Path: cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/HttpEasyReader.java import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import javax.xml.parsers.ParserConfigurationException; import org.concordion.cubano.driver.http.logging.LogManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; package org.concordion.cubano.driver.http; /** * Response reader for HTTP requests, can parse JSON and XML and download files. * * @author Andrew Sumner */ public class HttpEasyReader { private HttpURLConnection connection; private String returned = null; private static final Logger LOGGER = LoggerFactory.getLogger(HttpEasyReader.class); /** * Create new HttpEasyReader. * * @param connection HttpURLConnection * @param request Request that is creating this reader * @throws HttpResponseException if request failed * @throws IOException for connection errors */ public HttpEasyReader(HttpURLConnection connection, HttpEasy request) throws HttpResponseException, IOException { this.connection = connection; Family responseFamily = getResponseCodeFamily(); logResponse(request); if (responseFamily != Family.SUCCESSFUL) { if (listContains(request.ignoreResponseCodes, getResponseCode())) { return; } if (listContains(request.ignoreResponseFamily, responseFamily)) { return; } throw new HttpResponseException(getResponseCode(), "Server returned HTTP response code " + connection.getResponseCode() + ": " + connection.getResponseMessage() + "\r\nResponse Content: " + asString()); } } private void logResponse(HttpEasy request) throws IOException { if (!request.getLogManager().isLogRequestDetails()) { return; }
LogManager logger = request.getLogManager();
concordion/cubano
cubano-concordion/src/test/java/org/concordion/cubano/framework/ConcordionBaseTest.java
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // }
import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.*; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceScope; import org.junit.Test; import org.mockito.InOrder; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package org.concordion.cubano.framework; public class ConcordionBaseTest { private final TestResource resource0 = new TestResource("0"); private final TestResource resource1 = new TestResource("1"); private final TestResource resource2 = new TestResource("2"); private final TestResource resource3 = new TestResource("3"); private final TestResource resource4 = new TestResource("4"); private final TestResource resource5 = new TestResource("5"); private ConcordionBase test1 = new ConcordionBase() {}; private List<String> closedResources = new ArrayList<>();
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // } // Path: cubano-concordion/src/test/java/org/concordion/cubano/framework/ConcordionBaseTest.java import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.*; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceScope; import org.junit.Test; import org.mockito.InOrder; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; package org.concordion.cubano.framework; public class ConcordionBaseTest { private final TestResource resource0 = new TestResource("0"); private final TestResource resource1 = new TestResource("1"); private final TestResource resource2 = new TestResource("2"); private final TestResource resource3 = new TestResource("3"); private final TestResource resource4 = new TestResource("4"); private final TestResource resource5 = new TestResource("5"); private ConcordionBase test1 = new ConcordionBase() {}; private List<String> closedResources = new ArrayList<>();
private CloseListener listener = spy(CloseListener.class);
concordion/cubano
cubano-concordion/src/test/java/org/concordion/cubano/framework/ConcordionBaseTest.java
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // }
import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.*; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceScope; import org.junit.Test; import org.mockito.InOrder; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package org.concordion.cubano.framework; public class ConcordionBaseTest { private final TestResource resource0 = new TestResource("0"); private final TestResource resource1 = new TestResource("1"); private final TestResource resource2 = new TestResource("2"); private final TestResource resource3 = new TestResource("3"); private final TestResource resource4 = new TestResource("4"); private final TestResource resource5 = new TestResource("5"); private ConcordionBase test1 = new ConcordionBase() {}; private List<String> closedResources = new ArrayList<>(); private CloseListener listener = spy(CloseListener.class); private class TestResource implements Closeable { private final String name; private TestResource(String name) { this.name = name; } @Override public void close() throws IOException { closedResources.add(name); } } @Test public void isRegisteredReturnsFalseIfNotRegistered() {
// Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/CloseListener.java // public interface CloseListener { // default void beforeClosing(Closeable resource) {}; // default void afterClosing(Closeable resource) {}; // } // // Path: cubano-concordion/src/main/java/org/concordion/cubano/framework/resource/ResourceScope.java // public enum ResourceScope { // /** // * Per Concordion Specification Example // */ // EXAMPLE, // /** // * Per Concordion Specification // */ // SPECIFICATION, // /** // * Per Concordion Suite, where a Suite equates to the top-level test that is invoked (normally using JUnit). // * Other tests that are invoked from the top-level test using the Run Command are part of the suite. // * Other tests invoked directly (from JUnit) form independent suites. // */ // SUITE; // } // Path: cubano-concordion/src/test/java/org/concordion/cubano/framework/ConcordionBaseTest.java import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.*; import org.concordion.cubano.framework.resource.CloseListener; import org.concordion.cubano.framework.resource.ResourceScope; import org.junit.Test; import org.mockito.InOrder; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; package org.concordion.cubano.framework; public class ConcordionBaseTest { private final TestResource resource0 = new TestResource("0"); private final TestResource resource1 = new TestResource("1"); private final TestResource resource2 = new TestResource("2"); private final TestResource resource3 = new TestResource("3"); private final TestResource resource4 = new TestResource("4"); private final TestResource resource5 = new TestResource("5"); private ConcordionBase test1 = new ConcordionBase() {}; private List<String> closedResources = new ArrayList<>(); private CloseListener listener = spy(CloseListener.class); private class TestResource implements Closeable { private final String name; private TestResource(String name) { this.name = name; } @Override public void close() throws IOException { closedResources.add(name); } } @Test public void isRegisteredReturnsFalseIfNotRegistered() {
assertFalse(test1.isRegistered(resource0, ResourceScope.SPECIFICATION));
concordion/cubano
cubano-webdriver/src/main/java/org/concordion/cubano/driver/web/provider/SauceLabsBrowserProvider.java
// Path: cubano-webdriver/src/main/java/org/concordion/cubano/driver/web/config/WebDriverConfig.java // public final class WebDriverConfig { // // private final PropertyLoader propertyLoader; // // // Browser // private String browserProvider; // private String browserDimension; // private String browserPosition; // private boolean browserMaximized; // private boolean eventLoggingEnabled; // private boolean cleanupDriver; // // private String remoteUserName; // private String remoteApiKey; // // private int restartBrowserAfterXTests; // // private static class WDCHolder { // static final WebDriverConfig INSTANCE = new WebDriverConfig(); // } // // /** // * @return singleton instance // */ // public static WebDriverConfig getInstance() { // return WDCHolder.INSTANCE; // } // // /** // * Uses the default Config class's property loader to import the config and user properties files. // */ // protected WebDriverConfig() { // propertyLoader = Config.getInstance().getPropertyLoader(); // loadProperties(); // } // // /** // * Uses the supplied PropertiesLoader to import the config and user properties files. // * // * @param propertiesLoader Configuration loader // */ // protected WebDriverConfig(PropertiesLoader propertiesLoader) { // this(propertiesLoader.getProperties()); // } // // /** // * Allow injection of properties for testing purposes. // * // * @param properties Default properties // */ // protected WebDriverConfig(Properties properties) { // propertyLoader = new DefaultPropertyLoader(properties); // loadProperties(); // } // // /** // * @return a loader for loading properties across config.properties and user.properties, taking environment into account. // */ // public PropertyLoader getPropertyLoader() { // return propertyLoader; // } // // private void loadProperties() { // // Browser // browserProvider = System.getProperty("browserProvider"); // if (browserProvider == null) { // browserProvider = propertyLoader.getProperty("webdriver.browserProvider", "FirefoxBrowserProvider"); // } // // if (!browserProvider.contains(".")) { // browserProvider = "org.concordion.cubano.driver.web.provider." + browserProvider; // } // // browserDimension = propertyLoader.getProperty("webdriver.browser.dimension", null); // browserPosition = propertyLoader.getProperty("webdriver.browser.position", null); // browserMaximized = propertyLoader.getPropertyAsBoolean("webdriver.browser.maximized", "false"); // eventLoggingEnabled = propertyLoader.getPropertyAsBoolean("webdriver.event.logging", "true"); // cleanupDriver = propertyLoader.getPropertyAsBoolean("webdriver.browserdriver.cleanup", "false"); // // remoteUserName = propertyLoader.getProperty("remotewebdriver.userName", null); // remoteApiKey = propertyLoader.getProperty("remotewebdriver.apiKey", null); // // // Yandex HtmlElements automatically implement 5 second implicit wait, default to zero so as not to interfere with // // explicit waits // System.setProperty("webdriver.timeouts.implicitlywait", propertyLoader.getProperty("webdriver.timeouts.implicitlywait", "0")); // // restartBrowserAfterXTests = propertyLoader.getPropertyAsInteger("webdriver.browser.restartAfterXTests", "0"); // } // // public String getBrowserProvider() { // return browserProvider; // } // // /** // * Position to locate browser window. // * // * @return Size in WxH format // */ // public String getBrowserPosition() { // return browserPosition; // } // // /** // * Size to set browser window. // * // * @return Size in WxH format // */ // public String getBrowserDimension() { // return browserDimension; // } // // /** // * Number of tests to run before restarting browser to clear memory. // * // * @return 0 for never, otherwise limit // */ // public int getRestartBrowserAfterXTests() { // return restartBrowserAfterXTests; // } // // /** // * Browser should be maximized or not. // * // * @return is Browser Maximized // */ // public boolean isBrowserMaximized() { // return browserMaximized; // } // // /** // * Selenium WebDriver logging should be enabled. // * // * @return is Event Logging Enabled // */ // public boolean isEventLoggingEnabled() { // return eventLoggingEnabled; // } // // /** // * Terminate browser driver. // * // * @return is cleanup enabled // */ // public boolean isCleanupDriver() { // return cleanupDriver; // } // // /** // * Username for remote selenium grid service. // * // * @return Username // */ // public String getRemoteUserName() { // return remoteUserName; // } // // /** // * Api Key to access a remote selenium grid service. // * // * @return Api Key // */ // public String getRemoteApiKey() { // return remoteApiKey; // } // }
import org.concordion.cubano.driver.web.config.WebDriverConfig; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities;
iPhone6(); break; case "iPhone6PlusEmulator": iPhone6PlusEmulator(); break; case "samsungGalaxyS5": samsungGalaxyS5(); break; case "samsungGalaxyS4Emulator": samsungGalaxyS4Emulator(); break; case "googleNexus7CEmulator": googleNexus7CEmulator(); break; default: break; } throw new RuntimeException("Browser '" + browser + "' is not currently supported"); } @Override protected String getRemoteDriverUrl() { return REMOTE_URL.replace("[USER_NAME]",
// Path: cubano-webdriver/src/main/java/org/concordion/cubano/driver/web/config/WebDriverConfig.java // public final class WebDriverConfig { // // private final PropertyLoader propertyLoader; // // // Browser // private String browserProvider; // private String browserDimension; // private String browserPosition; // private boolean browserMaximized; // private boolean eventLoggingEnabled; // private boolean cleanupDriver; // // private String remoteUserName; // private String remoteApiKey; // // private int restartBrowserAfterXTests; // // private static class WDCHolder { // static final WebDriverConfig INSTANCE = new WebDriverConfig(); // } // // /** // * @return singleton instance // */ // public static WebDriverConfig getInstance() { // return WDCHolder.INSTANCE; // } // // /** // * Uses the default Config class's property loader to import the config and user properties files. // */ // protected WebDriverConfig() { // propertyLoader = Config.getInstance().getPropertyLoader(); // loadProperties(); // } // // /** // * Uses the supplied PropertiesLoader to import the config and user properties files. // * // * @param propertiesLoader Configuration loader // */ // protected WebDriverConfig(PropertiesLoader propertiesLoader) { // this(propertiesLoader.getProperties()); // } // // /** // * Allow injection of properties for testing purposes. // * // * @param properties Default properties // */ // protected WebDriverConfig(Properties properties) { // propertyLoader = new DefaultPropertyLoader(properties); // loadProperties(); // } // // /** // * @return a loader for loading properties across config.properties and user.properties, taking environment into account. // */ // public PropertyLoader getPropertyLoader() { // return propertyLoader; // } // // private void loadProperties() { // // Browser // browserProvider = System.getProperty("browserProvider"); // if (browserProvider == null) { // browserProvider = propertyLoader.getProperty("webdriver.browserProvider", "FirefoxBrowserProvider"); // } // // if (!browserProvider.contains(".")) { // browserProvider = "org.concordion.cubano.driver.web.provider." + browserProvider; // } // // browserDimension = propertyLoader.getProperty("webdriver.browser.dimension", null); // browserPosition = propertyLoader.getProperty("webdriver.browser.position", null); // browserMaximized = propertyLoader.getPropertyAsBoolean("webdriver.browser.maximized", "false"); // eventLoggingEnabled = propertyLoader.getPropertyAsBoolean("webdriver.event.logging", "true"); // cleanupDriver = propertyLoader.getPropertyAsBoolean("webdriver.browserdriver.cleanup", "false"); // // remoteUserName = propertyLoader.getProperty("remotewebdriver.userName", null); // remoteApiKey = propertyLoader.getProperty("remotewebdriver.apiKey", null); // // // Yandex HtmlElements automatically implement 5 second implicit wait, default to zero so as not to interfere with // // explicit waits // System.setProperty("webdriver.timeouts.implicitlywait", propertyLoader.getProperty("webdriver.timeouts.implicitlywait", "0")); // // restartBrowserAfterXTests = propertyLoader.getPropertyAsInteger("webdriver.browser.restartAfterXTests", "0"); // } // // public String getBrowserProvider() { // return browserProvider; // } // // /** // * Position to locate browser window. // * // * @return Size in WxH format // */ // public String getBrowserPosition() { // return browserPosition; // } // // /** // * Size to set browser window. // * // * @return Size in WxH format // */ // public String getBrowserDimension() { // return browserDimension; // } // // /** // * Number of tests to run before restarting browser to clear memory. // * // * @return 0 for never, otherwise limit // */ // public int getRestartBrowserAfterXTests() { // return restartBrowserAfterXTests; // } // // /** // * Browser should be maximized or not. // * // * @return is Browser Maximized // */ // public boolean isBrowserMaximized() { // return browserMaximized; // } // // /** // * Selenium WebDriver logging should be enabled. // * // * @return is Event Logging Enabled // */ // public boolean isEventLoggingEnabled() { // return eventLoggingEnabled; // } // // /** // * Terminate browser driver. // * // * @return is cleanup enabled // */ // public boolean isCleanupDriver() { // return cleanupDriver; // } // // /** // * Username for remote selenium grid service. // * // * @return Username // */ // public String getRemoteUserName() { // return remoteUserName; // } // // /** // * Api Key to access a remote selenium grid service. // * // * @return Api Key // */ // public String getRemoteApiKey() { // return remoteApiKey; // } // } // Path: cubano-webdriver/src/main/java/org/concordion/cubano/driver/web/provider/SauceLabsBrowserProvider.java import org.concordion.cubano.driver.web.config.WebDriverConfig; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; iPhone6(); break; case "iPhone6PlusEmulator": iPhone6PlusEmulator(); break; case "samsungGalaxyS5": samsungGalaxyS5(); break; case "samsungGalaxyS4Emulator": samsungGalaxyS4Emulator(); break; case "googleNexus7CEmulator": googleNexus7CEmulator(); break; default: break; } throw new RuntimeException("Browser '" + browser + "' is not currently supported"); } @Override protected String getRemoteDriverUrl() { return REMOTE_URL.replace("[USER_NAME]",
WebDriverConfig.getInstance().getRemoteUserName()).replace("[API_KEY]",
concordion/cubano
cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/HttpEasyDefaults.java
// Path: cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/logging/LoggerLogWriter.java // public class LoggerLogWriter extends LogWriter { // static final Logger LOGGER = LoggerFactory.getLogger(HttpEasy.class); // // @Override // public void info(String msg, Object... args) { // LOGGER.debug(msg, args); // } // // @Override // public void request(String msg, Object... args) { // LOGGER.trace(msg, args); // } // // @Override // public void response(String msg, Object... args) { // LOGGER.trace(msg, args); // } // // @Override // public void error(String message, Throwable t) { // LOGGER.error(message, t); // } // }
import java.net.Proxy; import java.net.ProxySelector; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.concordion.cubano.driver.http.logging.LoggerLogWriter; import com.github.markusbernhardt.proxy.ProxySearch; import com.github.markusbernhardt.proxy.util.Logger;
package org.concordion.cubano.driver.http; /** * Allows setting of default properties used by all subsequent HttpEasy requests. * * @author Andrew Sumner */ public class HttpEasyDefaults { public static final String DEFAULT_PROXY_BYPASS_HOSTS = "localhost,127.0.0.1"; private static String baseUrl = ""; private static boolean trustAllCertificates = false; private static boolean trustAllHosts = false; private static List<String> sensitiveParameters = new ArrayList<>(); // Request authorisation private static String authUser = null; private static String authPassword = null; // Proxy private static ProxyConfiguration proxyConfiguration = ProxyConfiguration.MANUAL; private static volatile ProxySelector proxySearch = null; private static Proxy proxy = Proxy.NO_PROXY; private static String proxyUser = null; private static String proxyPassword = null; private static boolean bypassProxy = false; private static List<String> nonProxyHosts = splitHosts(DEFAULT_PROXY_BYPASS_HOSTS); // Logging
// Path: cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/logging/LoggerLogWriter.java // public class LoggerLogWriter extends LogWriter { // static final Logger LOGGER = LoggerFactory.getLogger(HttpEasy.class); // // @Override // public void info(String msg, Object... args) { // LOGGER.debug(msg, args); // } // // @Override // public void request(String msg, Object... args) { // LOGGER.trace(msg, args); // } // // @Override // public void response(String msg, Object... args) { // LOGGER.trace(msg, args); // } // // @Override // public void error(String message, Throwable t) { // LOGGER.error(message, t); // } // } // Path: cubano-httpeasy/src/main/java/org/concordion/cubano/driver/http/HttpEasyDefaults.java import java.net.Proxy; import java.net.ProxySelector; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.concordion.cubano.driver.http.logging.LoggerLogWriter; import com.github.markusbernhardt.proxy.ProxySearch; import com.github.markusbernhardt.proxy.util.Logger; package org.concordion.cubano.driver.http; /** * Allows setting of default properties used by all subsequent HttpEasy requests. * * @author Andrew Sumner */ public class HttpEasyDefaults { public static final String DEFAULT_PROXY_BYPASS_HOSTS = "localhost,127.0.0.1"; private static String baseUrl = ""; private static boolean trustAllCertificates = false; private static boolean trustAllHosts = false; private static List<String> sensitiveParameters = new ArrayList<>(); // Request authorisation private static String authUser = null; private static String authPassword = null; // Proxy private static ProxyConfiguration proxyConfiguration = ProxyConfiguration.MANUAL; private static volatile ProxySelector proxySearch = null; private static Proxy proxy = Proxy.NO_PROXY; private static String proxyUser = null; private static String proxyPassword = null; private static boolean bypassProxy = false; private static List<String> nonProxyHosts = splitHosts(DEFAULT_PROXY_BYPASS_HOSTS); // Logging
private static LogWriter defaultLogWriter = new LoggerLogWriter();
concordion/cubano
cubano-webdriver/src/main/java/org/concordion/cubano/driver/web/provider/BrowserStackBrowserProvider.java
// Path: cubano-webdriver/src/main/java/org/concordion/cubano/driver/web/config/WebDriverConfig.java // public final class WebDriverConfig { // // private final PropertyLoader propertyLoader; // // // Browser // private String browserProvider; // private String browserDimension; // private String browserPosition; // private boolean browserMaximized; // private boolean eventLoggingEnabled; // private boolean cleanupDriver; // // private String remoteUserName; // private String remoteApiKey; // // private int restartBrowserAfterXTests; // // private static class WDCHolder { // static final WebDriverConfig INSTANCE = new WebDriverConfig(); // } // // /** // * @return singleton instance // */ // public static WebDriverConfig getInstance() { // return WDCHolder.INSTANCE; // } // // /** // * Uses the default Config class's property loader to import the config and user properties files. // */ // protected WebDriverConfig() { // propertyLoader = Config.getInstance().getPropertyLoader(); // loadProperties(); // } // // /** // * Uses the supplied PropertiesLoader to import the config and user properties files. // * // * @param propertiesLoader Configuration loader // */ // protected WebDriverConfig(PropertiesLoader propertiesLoader) { // this(propertiesLoader.getProperties()); // } // // /** // * Allow injection of properties for testing purposes. // * // * @param properties Default properties // */ // protected WebDriverConfig(Properties properties) { // propertyLoader = new DefaultPropertyLoader(properties); // loadProperties(); // } // // /** // * @return a loader for loading properties across config.properties and user.properties, taking environment into account. // */ // public PropertyLoader getPropertyLoader() { // return propertyLoader; // } // // private void loadProperties() { // // Browser // browserProvider = System.getProperty("browserProvider"); // if (browserProvider == null) { // browserProvider = propertyLoader.getProperty("webdriver.browserProvider", "FirefoxBrowserProvider"); // } // // if (!browserProvider.contains(".")) { // browserProvider = "org.concordion.cubano.driver.web.provider." + browserProvider; // } // // browserDimension = propertyLoader.getProperty("webdriver.browser.dimension", null); // browserPosition = propertyLoader.getProperty("webdriver.browser.position", null); // browserMaximized = propertyLoader.getPropertyAsBoolean("webdriver.browser.maximized", "false"); // eventLoggingEnabled = propertyLoader.getPropertyAsBoolean("webdriver.event.logging", "true"); // cleanupDriver = propertyLoader.getPropertyAsBoolean("webdriver.browserdriver.cleanup", "false"); // // remoteUserName = propertyLoader.getProperty("remotewebdriver.userName", null); // remoteApiKey = propertyLoader.getProperty("remotewebdriver.apiKey", null); // // // Yandex HtmlElements automatically implement 5 second implicit wait, default to zero so as not to interfere with // // explicit waits // System.setProperty("webdriver.timeouts.implicitlywait", propertyLoader.getProperty("webdriver.timeouts.implicitlywait", "0")); // // restartBrowserAfterXTests = propertyLoader.getPropertyAsInteger("webdriver.browser.restartAfterXTests", "0"); // } // // public String getBrowserProvider() { // return browserProvider; // } // // /** // * Position to locate browser window. // * // * @return Size in WxH format // */ // public String getBrowserPosition() { // return browserPosition; // } // // /** // * Size to set browser window. // * // * @return Size in WxH format // */ // public String getBrowserDimension() { // return browserDimension; // } // // /** // * Number of tests to run before restarting browser to clear memory. // * // * @return 0 for never, otherwise limit // */ // public int getRestartBrowserAfterXTests() { // return restartBrowserAfterXTests; // } // // /** // * Browser should be maximized or not. // * // * @return is Browser Maximized // */ // public boolean isBrowserMaximized() { // return browserMaximized; // } // // /** // * Selenium WebDriver logging should be enabled. // * // * @return is Event Logging Enabled // */ // public boolean isEventLoggingEnabled() { // return eventLoggingEnabled; // } // // /** // * Terminate browser driver. // * // * @return is cleanup enabled // */ // public boolean isCleanupDriver() { // return cleanupDriver; // } // // /** // * Username for remote selenium grid service. // * // * @return Username // */ // public String getRemoteUserName() { // return remoteUserName; // } // // /** // * Api Key to access a remote selenium grid service. // * // * @return Api Key // */ // public String getRemoteApiKey() { // return remoteApiKey; // } // }
import org.concordion.cubano.driver.web.config.WebDriverConfig; import org.openqa.selenium.remote.DesiredCapabilities;
case "safari": safari(version); break; default: break; } } // check devices switch (browser) { case "iphone 6s plus": iPhone6SPlusEmulator(); break; case "google nexus 5": googleNexus5Emulator(); break; default: break; } throw new RuntimeException("Browser '" + browser + "' is not currently supported"); } @Override protected String getRemoteDriverUrl() { return REMOTE_URL.replace("[USER_NAME]",
// Path: cubano-webdriver/src/main/java/org/concordion/cubano/driver/web/config/WebDriverConfig.java // public final class WebDriverConfig { // // private final PropertyLoader propertyLoader; // // // Browser // private String browserProvider; // private String browserDimension; // private String browserPosition; // private boolean browserMaximized; // private boolean eventLoggingEnabled; // private boolean cleanupDriver; // // private String remoteUserName; // private String remoteApiKey; // // private int restartBrowserAfterXTests; // // private static class WDCHolder { // static final WebDriverConfig INSTANCE = new WebDriverConfig(); // } // // /** // * @return singleton instance // */ // public static WebDriverConfig getInstance() { // return WDCHolder.INSTANCE; // } // // /** // * Uses the default Config class's property loader to import the config and user properties files. // */ // protected WebDriverConfig() { // propertyLoader = Config.getInstance().getPropertyLoader(); // loadProperties(); // } // // /** // * Uses the supplied PropertiesLoader to import the config and user properties files. // * // * @param propertiesLoader Configuration loader // */ // protected WebDriverConfig(PropertiesLoader propertiesLoader) { // this(propertiesLoader.getProperties()); // } // // /** // * Allow injection of properties for testing purposes. // * // * @param properties Default properties // */ // protected WebDriverConfig(Properties properties) { // propertyLoader = new DefaultPropertyLoader(properties); // loadProperties(); // } // // /** // * @return a loader for loading properties across config.properties and user.properties, taking environment into account. // */ // public PropertyLoader getPropertyLoader() { // return propertyLoader; // } // // private void loadProperties() { // // Browser // browserProvider = System.getProperty("browserProvider"); // if (browserProvider == null) { // browserProvider = propertyLoader.getProperty("webdriver.browserProvider", "FirefoxBrowserProvider"); // } // // if (!browserProvider.contains(".")) { // browserProvider = "org.concordion.cubano.driver.web.provider." + browserProvider; // } // // browserDimension = propertyLoader.getProperty("webdriver.browser.dimension", null); // browserPosition = propertyLoader.getProperty("webdriver.browser.position", null); // browserMaximized = propertyLoader.getPropertyAsBoolean("webdriver.browser.maximized", "false"); // eventLoggingEnabled = propertyLoader.getPropertyAsBoolean("webdriver.event.logging", "true"); // cleanupDriver = propertyLoader.getPropertyAsBoolean("webdriver.browserdriver.cleanup", "false"); // // remoteUserName = propertyLoader.getProperty("remotewebdriver.userName", null); // remoteApiKey = propertyLoader.getProperty("remotewebdriver.apiKey", null); // // // Yandex HtmlElements automatically implement 5 second implicit wait, default to zero so as not to interfere with // // explicit waits // System.setProperty("webdriver.timeouts.implicitlywait", propertyLoader.getProperty("webdriver.timeouts.implicitlywait", "0")); // // restartBrowserAfterXTests = propertyLoader.getPropertyAsInteger("webdriver.browser.restartAfterXTests", "0"); // } // // public String getBrowserProvider() { // return browserProvider; // } // // /** // * Position to locate browser window. // * // * @return Size in WxH format // */ // public String getBrowserPosition() { // return browserPosition; // } // // /** // * Size to set browser window. // * // * @return Size in WxH format // */ // public String getBrowserDimension() { // return browserDimension; // } // // /** // * Number of tests to run before restarting browser to clear memory. // * // * @return 0 for never, otherwise limit // */ // public int getRestartBrowserAfterXTests() { // return restartBrowserAfterXTests; // } // // /** // * Browser should be maximized or not. // * // * @return is Browser Maximized // */ // public boolean isBrowserMaximized() { // return browserMaximized; // } // // /** // * Selenium WebDriver logging should be enabled. // * // * @return is Event Logging Enabled // */ // public boolean isEventLoggingEnabled() { // return eventLoggingEnabled; // } // // /** // * Terminate browser driver. // * // * @return is cleanup enabled // */ // public boolean isCleanupDriver() { // return cleanupDriver; // } // // /** // * Username for remote selenium grid service. // * // * @return Username // */ // public String getRemoteUserName() { // return remoteUserName; // } // // /** // * Api Key to access a remote selenium grid service. // * // * @return Api Key // */ // public String getRemoteApiKey() { // return remoteApiKey; // } // } // Path: cubano-webdriver/src/main/java/org/concordion/cubano/driver/web/provider/BrowserStackBrowserProvider.java import org.concordion.cubano.driver.web.config.WebDriverConfig; import org.openqa.selenium.remote.DesiredCapabilities; case "safari": safari(version); break; default: break; } } // check devices switch (browser) { case "iphone 6s plus": iPhone6SPlusEmulator(); break; case "google nexus 5": googleNexus5Emulator(); break; default: break; } throw new RuntimeException("Browser '" + browser + "' is not currently supported"); } @Override protected String getRemoteDriverUrl() { return REMOTE_URL.replace("[USER_NAME]",
WebDriverConfig.getInstance().getRemoteUserName()).replace("[API_KEY]",
concordion/cubano
cubano-webdriver/src/test/java/org/concordion/cubano/driver/web/config/WebDriverConfigTest.java
// Path: cubano-config/src/main/java/org/concordion/cubano/config/PropertyLoader.java // public interface PropertyLoader { // // /** // * Get the property for the current environment, if that is not found it will look for "{@literal <key>}". // * // * @param key Id of the property to look up // * @return Property value if found, defaultValue if not found // */ // String getProperty(String key); // // /** // * Get the property for the current environment, if that is not found it will look for "{@literal <key>}". // * // * @param key Id of the property to look up // * @param defaultValue value to use if property is not found // * @return Property value if found, defaultValue if not found // */ // String getProperty(String key, String defaultValue); // // /** // * Get the property for the current environment as a boolean value, if that is not found it will look for "{@literal <key>}". // * // * @param key Id of the property to look up // * @param defaultValue value to use if property is not found // * @return Property value if found, defaultValue if not found // */ // boolean getPropertyAsBoolean(String key, String defaultValue); // // /** // * Get the property for the current environment as a numeric value, if that is not found it will look for "{@literal <key>}". // * // * @param key Id of the property to look up // * @param defaultValue value to use if property is not found // * @return Property value if found, defaultValue if not found // */ // int getPropertyAsInteger(String key, String defaultValue); // // /** // * Returns a map of key value pairs of properties starting with a prefix. // * // * @param keyPrefix Search string // * @return Map // */ // Map<String, String> getPropertiesStartingWith(String keyPrefix); // // /** // * Returns a map of key value pairs of properties starting with a prefix. // * // * @param keyPrefix Search string // * @param trimPrefix Remove prefix from key in returned set // * @return Map // */ // Map<String, String> getPropertiesStartingWith(String keyPrefix, boolean trimPrefix); // }
import org.concordion.cubano.config.PropertyLoader; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; import java.util.Collections; import java.util.Enumeration; import java.util.Properties; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock;
package org.concordion.cubano.driver.web.config; public class WebDriverConfigTest { @Rule public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties(); private Enumeration<String> empty = Collections.enumeration(Collections.<String>emptyList()); @Test public void localBrowserSettings() { Properties properties = givenDefaultProperties(); given(properties.getProperty("webdriver.browser.dimension")).willReturn("1280x1024"); given(properties.getProperty("webdriver.browser.position")).willReturn("10x10"); given(properties.getProperty("webdriver.browserSize")).willReturn("1280x1024"); given(properties.getProperty("firefox.exe")).willReturn("%USERPROFILE%/bin/firefox"); given(properties.getProperty("firefox.profile")).willReturn("default"); WebDriverConfig config = new WebDriverConfig(properties);
// Path: cubano-config/src/main/java/org/concordion/cubano/config/PropertyLoader.java // public interface PropertyLoader { // // /** // * Get the property for the current environment, if that is not found it will look for "{@literal <key>}". // * // * @param key Id of the property to look up // * @return Property value if found, defaultValue if not found // */ // String getProperty(String key); // // /** // * Get the property for the current environment, if that is not found it will look for "{@literal <key>}". // * // * @param key Id of the property to look up // * @param defaultValue value to use if property is not found // * @return Property value if found, defaultValue if not found // */ // String getProperty(String key, String defaultValue); // // /** // * Get the property for the current environment as a boolean value, if that is not found it will look for "{@literal <key>}". // * // * @param key Id of the property to look up // * @param defaultValue value to use if property is not found // * @return Property value if found, defaultValue if not found // */ // boolean getPropertyAsBoolean(String key, String defaultValue); // // /** // * Get the property for the current environment as a numeric value, if that is not found it will look for "{@literal <key>}". // * // * @param key Id of the property to look up // * @param defaultValue value to use if property is not found // * @return Property value if found, defaultValue if not found // */ // int getPropertyAsInteger(String key, String defaultValue); // // /** // * Returns a map of key value pairs of properties starting with a prefix. // * // * @param keyPrefix Search string // * @return Map // */ // Map<String, String> getPropertiesStartingWith(String keyPrefix); // // /** // * Returns a map of key value pairs of properties starting with a prefix. // * // * @param keyPrefix Search string // * @param trimPrefix Remove prefix from key in returned set // * @return Map // */ // Map<String, String> getPropertiesStartingWith(String keyPrefix, boolean trimPrefix); // } // Path: cubano-webdriver/src/test/java/org/concordion/cubano/driver/web/config/WebDriverConfigTest.java import org.concordion.cubano.config.PropertyLoader; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; import java.util.Collections; import java.util.Enumeration; import java.util.Properties; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; package org.concordion.cubano.driver.web.config; public class WebDriverConfigTest { @Rule public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties(); private Enumeration<String> empty = Collections.enumeration(Collections.<String>emptyList()); @Test public void localBrowserSettings() { Properties properties = givenDefaultProperties(); given(properties.getProperty("webdriver.browser.dimension")).willReturn("1280x1024"); given(properties.getProperty("webdriver.browser.position")).willReturn("10x10"); given(properties.getProperty("webdriver.browserSize")).willReturn("1280x1024"); given(properties.getProperty("firefox.exe")).willReturn("%USERPROFILE%/bin/firefox"); given(properties.getProperty("firefox.profile")).willReturn("default"); WebDriverConfig config = new WebDriverConfig(properties);
PropertyLoader propertyLoader = config.getPropertyLoader();
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java // public class MainActivity extends BaseActivity implements MainPageView, AdapterView.OnItemSelectedListener { // // public static MainComponent component; // // @Inject // MainPresenter mPresenter; // // @InjectView(R.id.mainPage_messageText) // TextView messageTextView; // @InjectView(R.id.mainPage_actionSpinner) // Spinner actionSpinner; // @InjectView(R.id.mainPage_inputEditText) // EditText inputText; // @InjectView(R.id.mainPage_submitButton) // Button submitButton; // @InjectView(R.id.mainPage_progress) // View progress; // // @Override // protected void onCreateComponent() { // // MainComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.inject(this); // // initSpinner(); // initSubmitButton(); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // if (resultCode == Activity.RESULT_OK) { // mPresenter.updateUser(); // } // } // // private void initSubmitButton() { // submitButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // // if(inputText.getText().toString().isEmpty()) { // MainActivity.this.onActionError(); // return; // } // // mPresenter.calcFib(Integer.valueOf(inputText.getText().toString())); // } // }); // } // // private void initSpinner() { // String[] actionTexts = {"Hello", "Bye", "Fibonacci"}; // ArrayAdapter<String> actionTextArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, actionTexts); // actionSpinner.setAdapter(actionTextArray); // actionSpinner.setOnItemSelectedListener(this); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // int id = item.getItemId(); // // if (id == R.id.action_settings) { // Intent intent = new Intent(this, SettingActivity.class); // startActivityForResult(intent, 17); // return true; // } // // return super.onOptionsItemSelected(item); // } // // @Override // public void showActionResultText(String resultText) { // messageTextView.setText(resultText); // } // // @Override // public void showInputMethodView(boolean isShow) { // int status = (isShow) ? View.VISIBLE : View.GONE; // // inputText.setVisibility(status); // submitButton.setVisibility(status); // } // // @Override // public void showLoading() { // progress.setVisibility(View.VISIBLE); // } // // @Override // public void hideLoading() { // progress.setVisibility(View.GONE); // } // // @Override // public void onActionError() { // messageTextView.setText(getString(R.string.main_error)); // } // // @Override // public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // switch (position) { // case 0: // mPresenter.onActionSelected(ActionType.HELLO); // break; // case 1: // mPresenter.onActionSelected(ActionType.BYE); // break; // case 2: // mPresenter.onActionSelected(ActionType.FIBONACCI); // break; // // } // } // // @Override // public void onNothingSelected(AdapterView<?> parent) { // // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/MainTestCase.java // public class MainTestCase extends ActivityInstrumentationTestCase2<MainActivity> { // // @Inject // protected Action mMockAction; // // public MainTestCase() { // super(MainActivity.class); // } // // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java // @Module // public class TestMainModule { // MainPageView mView; // // @Mock // Action mActionModel; // // public TestMainModule(MainPageView view) { // mView = view; // MockitoAnnotations.initMocks(this); // } // // @Provides // @Singleton // public MainPresenter getPresenter(Action action) { // // return new MainPresenterImpl(mView, action); // } // // @Provides // @Singleton // public Action getAction() { // return mActionModel; // } // }
import android.app.Application; import com.newegg.tr.dagger2prac.view.MainPageView; import com.newegg.tr.dagger2prac.view.activity.MainActivity; import com.newegg.tr.dagger2prac.view.MainTestCase; import com.newegg.tr.dagger2prac.view.module.TestMainModule; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/1/29. */ @Singleton @Component(
// Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java // public class MainActivity extends BaseActivity implements MainPageView, AdapterView.OnItemSelectedListener { // // public static MainComponent component; // // @Inject // MainPresenter mPresenter; // // @InjectView(R.id.mainPage_messageText) // TextView messageTextView; // @InjectView(R.id.mainPage_actionSpinner) // Spinner actionSpinner; // @InjectView(R.id.mainPage_inputEditText) // EditText inputText; // @InjectView(R.id.mainPage_submitButton) // Button submitButton; // @InjectView(R.id.mainPage_progress) // View progress; // // @Override // protected void onCreateComponent() { // // MainComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.inject(this); // // initSpinner(); // initSubmitButton(); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // if (resultCode == Activity.RESULT_OK) { // mPresenter.updateUser(); // } // } // // private void initSubmitButton() { // submitButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // // if(inputText.getText().toString().isEmpty()) { // MainActivity.this.onActionError(); // return; // } // // mPresenter.calcFib(Integer.valueOf(inputText.getText().toString())); // } // }); // } // // private void initSpinner() { // String[] actionTexts = {"Hello", "Bye", "Fibonacci"}; // ArrayAdapter<String> actionTextArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, actionTexts); // actionSpinner.setAdapter(actionTextArray); // actionSpinner.setOnItemSelectedListener(this); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // int id = item.getItemId(); // // if (id == R.id.action_settings) { // Intent intent = new Intent(this, SettingActivity.class); // startActivityForResult(intent, 17); // return true; // } // // return super.onOptionsItemSelected(item); // } // // @Override // public void showActionResultText(String resultText) { // messageTextView.setText(resultText); // } // // @Override // public void showInputMethodView(boolean isShow) { // int status = (isShow) ? View.VISIBLE : View.GONE; // // inputText.setVisibility(status); // submitButton.setVisibility(status); // } // // @Override // public void showLoading() { // progress.setVisibility(View.VISIBLE); // } // // @Override // public void hideLoading() { // progress.setVisibility(View.GONE); // } // // @Override // public void onActionError() { // messageTextView.setText(getString(R.string.main_error)); // } // // @Override // public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // switch (position) { // case 0: // mPresenter.onActionSelected(ActionType.HELLO); // break; // case 1: // mPresenter.onActionSelected(ActionType.BYE); // break; // case 2: // mPresenter.onActionSelected(ActionType.FIBONACCI); // break; // // } // } // // @Override // public void onNothingSelected(AdapterView<?> parent) { // // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/MainTestCase.java // public class MainTestCase extends ActivityInstrumentationTestCase2<MainActivity> { // // @Inject // protected Action mMockAction; // // public MainTestCase() { // super(MainActivity.class); // } // // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java // @Module // public class TestMainModule { // MainPageView mView; // // @Mock // Action mActionModel; // // public TestMainModule(MainPageView view) { // mView = view; // MockitoAnnotations.initMocks(this); // } // // @Provides // @Singleton // public MainPresenter getPresenter(Action action) { // // return new MainPresenterImpl(mView, action); // } // // @Provides // @Singleton // public Action getAction() { // return mActionModel; // } // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.view.MainPageView; import com.newegg.tr.dagger2prac.view.activity.MainActivity; import com.newegg.tr.dagger2prac.view.MainTestCase; import com.newegg.tr.dagger2prac.view.module.TestMainModule; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/1/29. */ @Singleton @Component(
modules = TestMainModule.class
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java // public class MainActivity extends BaseActivity implements MainPageView, AdapterView.OnItemSelectedListener { // // public static MainComponent component; // // @Inject // MainPresenter mPresenter; // // @InjectView(R.id.mainPage_messageText) // TextView messageTextView; // @InjectView(R.id.mainPage_actionSpinner) // Spinner actionSpinner; // @InjectView(R.id.mainPage_inputEditText) // EditText inputText; // @InjectView(R.id.mainPage_submitButton) // Button submitButton; // @InjectView(R.id.mainPage_progress) // View progress; // // @Override // protected void onCreateComponent() { // // MainComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.inject(this); // // initSpinner(); // initSubmitButton(); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // if (resultCode == Activity.RESULT_OK) { // mPresenter.updateUser(); // } // } // // private void initSubmitButton() { // submitButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // // if(inputText.getText().toString().isEmpty()) { // MainActivity.this.onActionError(); // return; // } // // mPresenter.calcFib(Integer.valueOf(inputText.getText().toString())); // } // }); // } // // private void initSpinner() { // String[] actionTexts = {"Hello", "Bye", "Fibonacci"}; // ArrayAdapter<String> actionTextArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, actionTexts); // actionSpinner.setAdapter(actionTextArray); // actionSpinner.setOnItemSelectedListener(this); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // int id = item.getItemId(); // // if (id == R.id.action_settings) { // Intent intent = new Intent(this, SettingActivity.class); // startActivityForResult(intent, 17); // return true; // } // // return super.onOptionsItemSelected(item); // } // // @Override // public void showActionResultText(String resultText) { // messageTextView.setText(resultText); // } // // @Override // public void showInputMethodView(boolean isShow) { // int status = (isShow) ? View.VISIBLE : View.GONE; // // inputText.setVisibility(status); // submitButton.setVisibility(status); // } // // @Override // public void showLoading() { // progress.setVisibility(View.VISIBLE); // } // // @Override // public void hideLoading() { // progress.setVisibility(View.GONE); // } // // @Override // public void onActionError() { // messageTextView.setText(getString(R.string.main_error)); // } // // @Override // public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // switch (position) { // case 0: // mPresenter.onActionSelected(ActionType.HELLO); // break; // case 1: // mPresenter.onActionSelected(ActionType.BYE); // break; // case 2: // mPresenter.onActionSelected(ActionType.FIBONACCI); // break; // // } // } // // @Override // public void onNothingSelected(AdapterView<?> parent) { // // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/MainTestCase.java // public class MainTestCase extends ActivityInstrumentationTestCase2<MainActivity> { // // @Inject // protected Action mMockAction; // // public MainTestCase() { // super(MainActivity.class); // } // // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java // @Module // public class TestMainModule { // MainPageView mView; // // @Mock // Action mActionModel; // // public TestMainModule(MainPageView view) { // mView = view; // MockitoAnnotations.initMocks(this); // } // // @Provides // @Singleton // public MainPresenter getPresenter(Action action) { // // return new MainPresenterImpl(mView, action); // } // // @Provides // @Singleton // public Action getAction() { // return mActionModel; // } // }
import android.app.Application; import com.newegg.tr.dagger2prac.view.MainPageView; import com.newegg.tr.dagger2prac.view.activity.MainActivity; import com.newegg.tr.dagger2prac.view.MainTestCase; import com.newegg.tr.dagger2prac.view.module.TestMainModule; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/1/29. */ @Singleton @Component( modules = TestMainModule.class ) public interface MainComponent {
// Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java // public class MainActivity extends BaseActivity implements MainPageView, AdapterView.OnItemSelectedListener { // // public static MainComponent component; // // @Inject // MainPresenter mPresenter; // // @InjectView(R.id.mainPage_messageText) // TextView messageTextView; // @InjectView(R.id.mainPage_actionSpinner) // Spinner actionSpinner; // @InjectView(R.id.mainPage_inputEditText) // EditText inputText; // @InjectView(R.id.mainPage_submitButton) // Button submitButton; // @InjectView(R.id.mainPage_progress) // View progress; // // @Override // protected void onCreateComponent() { // // MainComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.inject(this); // // initSpinner(); // initSubmitButton(); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // if (resultCode == Activity.RESULT_OK) { // mPresenter.updateUser(); // } // } // // private void initSubmitButton() { // submitButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // // if(inputText.getText().toString().isEmpty()) { // MainActivity.this.onActionError(); // return; // } // // mPresenter.calcFib(Integer.valueOf(inputText.getText().toString())); // } // }); // } // // private void initSpinner() { // String[] actionTexts = {"Hello", "Bye", "Fibonacci"}; // ArrayAdapter<String> actionTextArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, actionTexts); // actionSpinner.setAdapter(actionTextArray); // actionSpinner.setOnItemSelectedListener(this); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // int id = item.getItemId(); // // if (id == R.id.action_settings) { // Intent intent = new Intent(this, SettingActivity.class); // startActivityForResult(intent, 17); // return true; // } // // return super.onOptionsItemSelected(item); // } // // @Override // public void showActionResultText(String resultText) { // messageTextView.setText(resultText); // } // // @Override // public void showInputMethodView(boolean isShow) { // int status = (isShow) ? View.VISIBLE : View.GONE; // // inputText.setVisibility(status); // submitButton.setVisibility(status); // } // // @Override // public void showLoading() { // progress.setVisibility(View.VISIBLE); // } // // @Override // public void hideLoading() { // progress.setVisibility(View.GONE); // } // // @Override // public void onActionError() { // messageTextView.setText(getString(R.string.main_error)); // } // // @Override // public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // switch (position) { // case 0: // mPresenter.onActionSelected(ActionType.HELLO); // break; // case 1: // mPresenter.onActionSelected(ActionType.BYE); // break; // case 2: // mPresenter.onActionSelected(ActionType.FIBONACCI); // break; // // } // } // // @Override // public void onNothingSelected(AdapterView<?> parent) { // // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/MainTestCase.java // public class MainTestCase extends ActivityInstrumentationTestCase2<MainActivity> { // // @Inject // protected Action mMockAction; // // public MainTestCase() { // super(MainActivity.class); // } // // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java // @Module // public class TestMainModule { // MainPageView mView; // // @Mock // Action mActionModel; // // public TestMainModule(MainPageView view) { // mView = view; // MockitoAnnotations.initMocks(this); // } // // @Provides // @Singleton // public MainPresenter getPresenter(Action action) { // // return new MainPresenterImpl(mView, action); // } // // @Provides // @Singleton // public Action getAction() { // return mActionModel; // } // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.view.MainPageView; import com.newegg.tr.dagger2prac.view.activity.MainActivity; import com.newegg.tr.dagger2prac.view.MainTestCase; import com.newegg.tr.dagger2prac.view.module.TestMainModule; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/1/29. */ @Singleton @Component( modules = TestMainModule.class ) public interface MainComponent {
void inject(MainActivity activity);
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java // public class MainActivity extends BaseActivity implements MainPageView, AdapterView.OnItemSelectedListener { // // public static MainComponent component; // // @Inject // MainPresenter mPresenter; // // @InjectView(R.id.mainPage_messageText) // TextView messageTextView; // @InjectView(R.id.mainPage_actionSpinner) // Spinner actionSpinner; // @InjectView(R.id.mainPage_inputEditText) // EditText inputText; // @InjectView(R.id.mainPage_submitButton) // Button submitButton; // @InjectView(R.id.mainPage_progress) // View progress; // // @Override // protected void onCreateComponent() { // // MainComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.inject(this); // // initSpinner(); // initSubmitButton(); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // if (resultCode == Activity.RESULT_OK) { // mPresenter.updateUser(); // } // } // // private void initSubmitButton() { // submitButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // // if(inputText.getText().toString().isEmpty()) { // MainActivity.this.onActionError(); // return; // } // // mPresenter.calcFib(Integer.valueOf(inputText.getText().toString())); // } // }); // } // // private void initSpinner() { // String[] actionTexts = {"Hello", "Bye", "Fibonacci"}; // ArrayAdapter<String> actionTextArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, actionTexts); // actionSpinner.setAdapter(actionTextArray); // actionSpinner.setOnItemSelectedListener(this); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // int id = item.getItemId(); // // if (id == R.id.action_settings) { // Intent intent = new Intent(this, SettingActivity.class); // startActivityForResult(intent, 17); // return true; // } // // return super.onOptionsItemSelected(item); // } // // @Override // public void showActionResultText(String resultText) { // messageTextView.setText(resultText); // } // // @Override // public void showInputMethodView(boolean isShow) { // int status = (isShow) ? View.VISIBLE : View.GONE; // // inputText.setVisibility(status); // submitButton.setVisibility(status); // } // // @Override // public void showLoading() { // progress.setVisibility(View.VISIBLE); // } // // @Override // public void hideLoading() { // progress.setVisibility(View.GONE); // } // // @Override // public void onActionError() { // messageTextView.setText(getString(R.string.main_error)); // } // // @Override // public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // switch (position) { // case 0: // mPresenter.onActionSelected(ActionType.HELLO); // break; // case 1: // mPresenter.onActionSelected(ActionType.BYE); // break; // case 2: // mPresenter.onActionSelected(ActionType.FIBONACCI); // break; // // } // } // // @Override // public void onNothingSelected(AdapterView<?> parent) { // // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/MainTestCase.java // public class MainTestCase extends ActivityInstrumentationTestCase2<MainActivity> { // // @Inject // protected Action mMockAction; // // public MainTestCase() { // super(MainActivity.class); // } // // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java // @Module // public class TestMainModule { // MainPageView mView; // // @Mock // Action mActionModel; // // public TestMainModule(MainPageView view) { // mView = view; // MockitoAnnotations.initMocks(this); // } // // @Provides // @Singleton // public MainPresenter getPresenter(Action action) { // // return new MainPresenterImpl(mView, action); // } // // @Provides // @Singleton // public Action getAction() { // return mActionModel; // } // }
import android.app.Application; import com.newegg.tr.dagger2prac.view.MainPageView; import com.newegg.tr.dagger2prac.view.activity.MainActivity; import com.newegg.tr.dagger2prac.view.MainTestCase; import com.newegg.tr.dagger2prac.view.module.TestMainModule; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/1/29. */ @Singleton @Component( modules = TestMainModule.class ) public interface MainComponent { void inject(MainActivity activity);
// Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java // public class MainActivity extends BaseActivity implements MainPageView, AdapterView.OnItemSelectedListener { // // public static MainComponent component; // // @Inject // MainPresenter mPresenter; // // @InjectView(R.id.mainPage_messageText) // TextView messageTextView; // @InjectView(R.id.mainPage_actionSpinner) // Spinner actionSpinner; // @InjectView(R.id.mainPage_inputEditText) // EditText inputText; // @InjectView(R.id.mainPage_submitButton) // Button submitButton; // @InjectView(R.id.mainPage_progress) // View progress; // // @Override // protected void onCreateComponent() { // // MainComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.inject(this); // // initSpinner(); // initSubmitButton(); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // if (resultCode == Activity.RESULT_OK) { // mPresenter.updateUser(); // } // } // // private void initSubmitButton() { // submitButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // // if(inputText.getText().toString().isEmpty()) { // MainActivity.this.onActionError(); // return; // } // // mPresenter.calcFib(Integer.valueOf(inputText.getText().toString())); // } // }); // } // // private void initSpinner() { // String[] actionTexts = {"Hello", "Bye", "Fibonacci"}; // ArrayAdapter<String> actionTextArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, actionTexts); // actionSpinner.setAdapter(actionTextArray); // actionSpinner.setOnItemSelectedListener(this); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // int id = item.getItemId(); // // if (id == R.id.action_settings) { // Intent intent = new Intent(this, SettingActivity.class); // startActivityForResult(intent, 17); // return true; // } // // return super.onOptionsItemSelected(item); // } // // @Override // public void showActionResultText(String resultText) { // messageTextView.setText(resultText); // } // // @Override // public void showInputMethodView(boolean isShow) { // int status = (isShow) ? View.VISIBLE : View.GONE; // // inputText.setVisibility(status); // submitButton.setVisibility(status); // } // // @Override // public void showLoading() { // progress.setVisibility(View.VISIBLE); // } // // @Override // public void hideLoading() { // progress.setVisibility(View.GONE); // } // // @Override // public void onActionError() { // messageTextView.setText(getString(R.string.main_error)); // } // // @Override // public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // switch (position) { // case 0: // mPresenter.onActionSelected(ActionType.HELLO); // break; // case 1: // mPresenter.onActionSelected(ActionType.BYE); // break; // case 2: // mPresenter.onActionSelected(ActionType.FIBONACCI); // break; // // } // } // // @Override // public void onNothingSelected(AdapterView<?> parent) { // // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/MainTestCase.java // public class MainTestCase extends ActivityInstrumentationTestCase2<MainActivity> { // // @Inject // protected Action mMockAction; // // public MainTestCase() { // super(MainActivity.class); // } // // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java // @Module // public class TestMainModule { // MainPageView mView; // // @Mock // Action mActionModel; // // public TestMainModule(MainPageView view) { // mView = view; // MockitoAnnotations.initMocks(this); // } // // @Provides // @Singleton // public MainPresenter getPresenter(Action action) { // // return new MainPresenterImpl(mView, action); // } // // @Provides // @Singleton // public Action getAction() { // return mActionModel; // } // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.view.MainPageView; import com.newegg.tr.dagger2prac.view.activity.MainActivity; import com.newegg.tr.dagger2prac.view.MainTestCase; import com.newegg.tr.dagger2prac.view.module.TestMainModule; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/1/29. */ @Singleton @Component( modules = TestMainModule.class ) public interface MainComponent { void inject(MainActivity activity);
void inject(MainTestCase testCase);
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // }
import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component(
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component(
modules = TestSettingModule.class
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // }
import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component( modules = TestSettingModule.class ) public interface SettingComponent {
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component( modules = TestSettingModule.class ) public interface SettingComponent {
void inject(SettingActivity activity);
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // }
import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component( modules = TestSettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity);
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component( modules = TestSettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity);
void inject(SettingTestCase testSetting);
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // }
import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component( modules = TestSettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity); void inject(SettingTestCase testSetting);
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component( modules = TestSettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity); void inject(SettingTestCase testSetting);
Config getConfig();
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // }
import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component( modules = TestSettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity); void inject(SettingTestCase testSetting); Config getConfig(); public class Initializer { public static SettingComponent mInstance;
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component( modules = TestSettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity); void inject(SettingTestCase testSetting); Config getConfig(); public class Initializer { public static SettingComponent mInstance;
public static SettingComponent init(Application app, SettingView view) {
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // }
import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component( modules = TestSettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity); void inject(SettingTestCase testSetting); Config getConfig(); public class Initializer { public static SettingComponent mInstance; public static SettingComponent init(Application app, SettingView view) { SettingComponent component = Dagger_SettingComponent.builder()
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Singleton @Component( modules = TestSettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity); void inject(SettingTestCase testSetting); Config getConfig(); public class Initializer { public static SettingComponent mInstance; public static SettingComponent init(Application app, SettingView view) { SettingComponent component = Dagger_SettingComponent.builder()
.testSettingModule(new TestSettingModule(view, ((Dagger2pracApp) app).MOCK_MODE)).build();
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // }
import android.test.ActivityInstrumentationTestCase2; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import javax.inject.Inject;
package com.newegg.tr.dagger2prac.view; /** * Created by william on 15/2/16. */ public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { @Inject
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java import android.test.ActivityInstrumentationTestCase2; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import javax.inject.Inject; package com.newegg.tr.dagger2prac.view; /** * Created by william on 15/2/16. */ public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { @Inject
protected Config mMockConfig;
showang/dagger2Example
app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionType.java // public enum ActionType { // HELLO, BYE, FIBONACCI // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // }
import android.os.AsyncTask; import android.util.Log; import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionType; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.view.MainPageView; import javax.inject.Inject;
package com.newegg.tr.dagger2prac.presenter.internal; /** * Created by william on 15/2/2. */ public class MainPresenterImpl implements MainPresenter { private final static ActionType DEFAULT_ACTION = ActionType.HELLO;
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionType.java // public enum ActionType { // HELLO, BYE, FIBONACCI // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java import android.os.AsyncTask; import android.util.Log; import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionType; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.view.MainPageView; import javax.inject.Inject; package com.newegg.tr.dagger2prac.presenter.internal; /** * Created by william on 15/2/2. */ public class MainPresenterImpl implements MainPresenter { private final static ActionType DEFAULT_ACTION = ActionType.HELLO;
MainPageView mView;
showang/dagger2Example
app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionType.java // public enum ActionType { // HELLO, BYE, FIBONACCI // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // }
import android.os.AsyncTask; import android.util.Log; import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionType; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.view.MainPageView; import javax.inject.Inject;
package com.newegg.tr.dagger2prac.presenter.internal; /** * Created by william on 15/2/2. */ public class MainPresenterImpl implements MainPresenter { private final static ActionType DEFAULT_ACTION = ActionType.HELLO; MainPageView mView;
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionType.java // public enum ActionType { // HELLO, BYE, FIBONACCI // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java import android.os.AsyncTask; import android.util.Log; import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionType; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.view.MainPageView; import javax.inject.Inject; package com.newegg.tr.dagger2prac.presenter.internal; /** * Created by william on 15/2/2. */ public class MainPresenterImpl implements MainPresenter { private final static ActionType DEFAULT_ACTION = ActionType.HELLO; MainPageView mView;
Action mModel;
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/component/GlobalComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/GlobleModule.java // @Module // public class GlobleModule { // // @Provides // @Singleton // public Config provideConfig(){ // return new ConfigManager(); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // }
import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.module.GlobleModule; import com.newegg.tr.dagger2prac.model.config.Config; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/10. */ @Singleton @Component(
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/GlobleModule.java // @Module // public class GlobleModule { // // @Provides // @Singleton // public Config provideConfig(){ // return new ConfigManager(); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/component/GlobalComponent.java import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.module.GlobleModule; import com.newegg.tr.dagger2prac.model.config.Config; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/10. */ @Singleton @Component(
modules = GlobleModule.class
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/component/GlobalComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/GlobleModule.java // @Module // public class GlobleModule { // // @Provides // @Singleton // public Config provideConfig(){ // return new ConfigManager(); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // }
import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.module.GlobleModule; import com.newegg.tr.dagger2prac.model.config.Config; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/10. */ @Singleton @Component( modules = GlobleModule.class ) public interface GlobalComponent {
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/GlobleModule.java // @Module // public class GlobleModule { // // @Provides // @Singleton // public Config provideConfig(){ // return new ConfigManager(); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/component/GlobalComponent.java import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.module.GlobleModule; import com.newegg.tr.dagger2prac.model.config.Config; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/10. */ @Singleton @Component( modules = GlobleModule.class ) public interface GlobalComponent {
public void inject(Dagger2pracApp app);
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/component/GlobalComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/GlobleModule.java // @Module // public class GlobleModule { // // @Provides // @Singleton // public Config provideConfig(){ // return new ConfigManager(); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // }
import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.module.GlobleModule; import com.newegg.tr.dagger2prac.model.config.Config; import javax.inject.Singleton; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/10. */ @Singleton @Component( modules = GlobleModule.class ) public interface GlobalComponent { public void inject(Dagger2pracApp app);
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/GlobleModule.java // @Module // public class GlobleModule { // // @Provides // @Singleton // public Config provideConfig(){ // return new ConfigManager(); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/component/GlobalComponent.java import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.module.GlobleModule; import com.newegg.tr.dagger2prac.model.config.Config; import javax.inject.Singleton; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/10. */ @Singleton @Component( modules = GlobleModule.class ) public interface GlobalComponent { public void inject(Dagger2pracApp app);
public Config getConfig();
showang/dagger2Example
app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java // @Singleton // @Component( // modules = TestSettingModule.class // ) // public interface SettingComponent { // // void inject(SettingActivity activity); // // void inject(SettingTestCase testSetting); // // Config getConfig(); // // public class Initializer { // public static SettingComponent mInstance; // // public static SettingComponent init(Application app, SettingView view) { // // SettingComponent component = Dagger_SettingComponent.builder() // .testSettingModule(new TestSettingModule(view, ((Dagger2pracApp) app).MOCK_MODE)).build(); // // mInstance = component; // return component; // } // // } // // }
import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.component.SettingComponent; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.newegg.tr.dagger2prac.view.activity; public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { @Inject
// Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java // @Singleton // @Component( // modules = TestSettingModule.class // ) // public interface SettingComponent { // // void inject(SettingActivity activity); // // void inject(SettingTestCase testSetting); // // Config getConfig(); // // public class Initializer { // public static SettingComponent mInstance; // // public static SettingComponent init(Application app, SettingView view) { // // SettingComponent component = Dagger_SettingComponent.builder() // .testSettingModule(new TestSettingModule(view, ((Dagger2pracApp) app).MOCK_MODE)).build(); // // mInstance = component; // return component; // } // // } // // } // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.component.SettingComponent; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.newegg.tr.dagger2prac.view.activity; public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { @Inject
SettingPresenter mPresenter;
showang/dagger2Example
app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java // @Singleton // @Component( // modules = TestSettingModule.class // ) // public interface SettingComponent { // // void inject(SettingActivity activity); // // void inject(SettingTestCase testSetting); // // Config getConfig(); // // public class Initializer { // public static SettingComponent mInstance; // // public static SettingComponent init(Application app, SettingView view) { // // SettingComponent component = Dagger_SettingComponent.builder() // .testSettingModule(new TestSettingModule(view, ((Dagger2pracApp) app).MOCK_MODE)).build(); // // mInstance = component; // return component; // } // // } // // }
import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.component.SettingComponent; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.newegg.tr.dagger2prac.view.activity; public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { @Inject SettingPresenter mPresenter; @InjectView(R.id.settingPage_userNameTextView) TextView mUserNameTextView; @InjectView(R.id.settingPage_changeUserNameButton) TextView mChangeNameButton; @Override protected void onCreateComponent() {
// Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java // @Singleton // @Component( // modules = TestSettingModule.class // ) // public interface SettingComponent { // // void inject(SettingActivity activity); // // void inject(SettingTestCase testSetting); // // Config getConfig(); // // public class Initializer { // public static SettingComponent mInstance; // // public static SettingComponent init(Application app, SettingView view) { // // SettingComponent component = Dagger_SettingComponent.builder() // .testSettingModule(new TestSettingModule(view, ((Dagger2pracApp) app).MOCK_MODE)).build(); // // mInstance = component; // return component; // } // // } // // } // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.component.SettingComponent; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.newegg.tr.dagger2prac.view.activity; public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { @Inject SettingPresenter mPresenter; @InjectView(R.id.settingPage_userNameTextView) TextView mUserNameTextView; @InjectView(R.id.settingPage_changeUserNameButton) TextView mChangeNameButton; @Override protected void onCreateComponent() {
SettingComponent.Initializer.init(getApplication(), this).inject(this);
showang/dagger2Example
app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionModel.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.message.Messenger; import javax.inject.Inject;
package com.newegg.tr.dagger2prac.model.action; /** * Created by william on 15/1/30. */ public class ActionModel implements Action { private final Messenger mMessenger;
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // } // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionModel.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.message.Messenger; import javax.inject.Inject; package com.newegg.tr.dagger2prac.model.action; /** * Created by william on 15/1/30. */ public class ActionModel implements Action { private final Messenger mMessenger;
private final Config mConfig;
showang/dagger2Example
app/src/androidTest/java/com/newegg/tr/dagger2prac/model/ActionModelTest.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionModel.java // public class ActionModel implements Action { // // private final Messenger mMessenger; // // private final Config mConfig; // // @Inject // public ActionModel(Messenger messenger, Config config) { // // mMessenger = messenger; // // mConfig = config; // } // // @Override // public String hello() { // // return String.format(mMessenger.getHelloFormat(), mConfig.getUserName()); // } // // @Override // public String bye() { // // return String.format(mMessenger.getByeFormat(), mConfig.getUserName()); // } // // @Override // public String fibonacci() { // // return mMessenger.getFibInitMessage(); // // } // // @Override // public int calcFibNumber(int input) { // // if(input <=0 ) // return -1; // // return fibMethod(input); // } // // private int fibMethod(int n){ // if(n <= 0) // throw new IllegalArgumentException("Input must be positive integer"); // if(n == 1) // return 1; // if(n == 2) // return 1; // return fibMethod(n-2) + fibMethod(n-1); // } // // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // }
import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionModel; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/2. */ public class ActionModelTest extends TestCase { @Mock
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionModel.java // public class ActionModel implements Action { // // private final Messenger mMessenger; // // private final Config mConfig; // // @Inject // public ActionModel(Messenger messenger, Config config) { // // mMessenger = messenger; // // mConfig = config; // } // // @Override // public String hello() { // // return String.format(mMessenger.getHelloFormat(), mConfig.getUserName()); // } // // @Override // public String bye() { // // return String.format(mMessenger.getByeFormat(), mConfig.getUserName()); // } // // @Override // public String fibonacci() { // // return mMessenger.getFibInitMessage(); // // } // // @Override // public int calcFibNumber(int input) { // // if(input <=0 ) // return -1; // // return fibMethod(input); // } // // private int fibMethod(int n){ // if(n <= 0) // throw new IllegalArgumentException("Input must be positive integer"); // if(n == 1) // return 1; // if(n == 2) // return 1; // return fibMethod(n-2) + fibMethod(n-1); // } // // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // } // Path: app/src/androidTest/java/com/newegg/tr/dagger2prac/model/ActionModelTest.java import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionModel; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/2. */ public class ActionModelTest extends TestCase { @Mock
private Action action;
showang/dagger2Example
app/src/androidTest/java/com/newegg/tr/dagger2prac/model/ActionModelTest.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionModel.java // public class ActionModel implements Action { // // private final Messenger mMessenger; // // private final Config mConfig; // // @Inject // public ActionModel(Messenger messenger, Config config) { // // mMessenger = messenger; // // mConfig = config; // } // // @Override // public String hello() { // // return String.format(mMessenger.getHelloFormat(), mConfig.getUserName()); // } // // @Override // public String bye() { // // return String.format(mMessenger.getByeFormat(), mConfig.getUserName()); // } // // @Override // public String fibonacci() { // // return mMessenger.getFibInitMessage(); // // } // // @Override // public int calcFibNumber(int input) { // // if(input <=0 ) // return -1; // // return fibMethod(input); // } // // private int fibMethod(int n){ // if(n <= 0) // throw new IllegalArgumentException("Input must be positive integer"); // if(n == 1) // return 1; // if(n == 2) // return 1; // return fibMethod(n-2) + fibMethod(n-1); // } // // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // }
import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionModel; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/2. */ public class ActionModelTest extends TestCase { @Mock private Action action; @Mock
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionModel.java // public class ActionModel implements Action { // // private final Messenger mMessenger; // // private final Config mConfig; // // @Inject // public ActionModel(Messenger messenger, Config config) { // // mMessenger = messenger; // // mConfig = config; // } // // @Override // public String hello() { // // return String.format(mMessenger.getHelloFormat(), mConfig.getUserName()); // } // // @Override // public String bye() { // // return String.format(mMessenger.getByeFormat(), mConfig.getUserName()); // } // // @Override // public String fibonacci() { // // return mMessenger.getFibInitMessage(); // // } // // @Override // public int calcFibNumber(int input) { // // if(input <=0 ) // return -1; // // return fibMethod(input); // } // // private int fibMethod(int n){ // if(n <= 0) // throw new IllegalArgumentException("Input must be positive integer"); // if(n == 1) // return 1; // if(n == 2) // return 1; // return fibMethod(n-2) + fibMethod(n-1); // } // // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // } // Path: app/src/androidTest/java/com/newegg/tr/dagger2prac/model/ActionModelTest.java import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionModel; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/2. */ public class ActionModelTest extends TestCase { @Mock private Action action; @Mock
private Messenger mMessenger;
showang/dagger2Example
app/src/androidTest/java/com/newegg/tr/dagger2prac/model/ActionModelTest.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionModel.java // public class ActionModel implements Action { // // private final Messenger mMessenger; // // private final Config mConfig; // // @Inject // public ActionModel(Messenger messenger, Config config) { // // mMessenger = messenger; // // mConfig = config; // } // // @Override // public String hello() { // // return String.format(mMessenger.getHelloFormat(), mConfig.getUserName()); // } // // @Override // public String bye() { // // return String.format(mMessenger.getByeFormat(), mConfig.getUserName()); // } // // @Override // public String fibonacci() { // // return mMessenger.getFibInitMessage(); // // } // // @Override // public int calcFibNumber(int input) { // // if(input <=0 ) // return -1; // // return fibMethod(input); // } // // private int fibMethod(int n){ // if(n <= 0) // throw new IllegalArgumentException("Input must be positive integer"); // if(n == 1) // return 1; // if(n == 2) // return 1; // return fibMethod(n-2) + fibMethod(n-1); // } // // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // }
import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionModel; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/2. */ public class ActionModelTest extends TestCase { @Mock private Action action; @Mock private Messenger mMessenger; @Mock
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionModel.java // public class ActionModel implements Action { // // private final Messenger mMessenger; // // private final Config mConfig; // // @Inject // public ActionModel(Messenger messenger, Config config) { // // mMessenger = messenger; // // mConfig = config; // } // // @Override // public String hello() { // // return String.format(mMessenger.getHelloFormat(), mConfig.getUserName()); // } // // @Override // public String bye() { // // return String.format(mMessenger.getByeFormat(), mConfig.getUserName()); // } // // @Override // public String fibonacci() { // // return mMessenger.getFibInitMessage(); // // } // // @Override // public int calcFibNumber(int input) { // // if(input <=0 ) // return -1; // // return fibMethod(input); // } // // private int fibMethod(int n){ // if(n <= 0) // throw new IllegalArgumentException("Input must be positive integer"); // if(n == 1) // return 1; // if(n == 2) // return 1; // return fibMethod(n-2) + fibMethod(n-1); // } // // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // } // Path: app/src/androidTest/java/com/newegg/tr/dagger2prac/model/ActionModelTest.java import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionModel; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/2. */ public class ActionModelTest extends TestCase { @Mock private Action action; @Mock private Messenger mMessenger; @Mock
private Config mConfig;
showang/dagger2Example
app/src/androidTest/java/com/newegg/tr/dagger2prac/model/ActionModelTest.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionModel.java // public class ActionModel implements Action { // // private final Messenger mMessenger; // // private final Config mConfig; // // @Inject // public ActionModel(Messenger messenger, Config config) { // // mMessenger = messenger; // // mConfig = config; // } // // @Override // public String hello() { // // return String.format(mMessenger.getHelloFormat(), mConfig.getUserName()); // } // // @Override // public String bye() { // // return String.format(mMessenger.getByeFormat(), mConfig.getUserName()); // } // // @Override // public String fibonacci() { // // return mMessenger.getFibInitMessage(); // // } // // @Override // public int calcFibNumber(int input) { // // if(input <=0 ) // return -1; // // return fibMethod(input); // } // // private int fibMethod(int n){ // if(n <= 0) // throw new IllegalArgumentException("Input must be positive integer"); // if(n == 1) // return 1; // if(n == 2) // return 1; // return fibMethod(n-2) + fibMethod(n-1); // } // // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // }
import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionModel; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/2. */ public class ActionModelTest extends TestCase { @Mock private Action action; @Mock private Messenger mMessenger; @Mock private Config mConfig; @Override protected void setUp() throws Exception { super.setUp(); MockitoAnnotations.initMocks(this); } public void testHello() { String stubPerson = "Who is not important in this case."; String stubMessage = "Test Hello in stub with %s"; String exceptResult = "Test Hello in stub with Who is not important in this case."; when(mMessenger.getHelloFormat()).thenReturn(stubMessage); when(mConfig.getUserName()).thenReturn(stubPerson);
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionModel.java // public class ActionModel implements Action { // // private final Messenger mMessenger; // // private final Config mConfig; // // @Inject // public ActionModel(Messenger messenger, Config config) { // // mMessenger = messenger; // // mConfig = config; // } // // @Override // public String hello() { // // return String.format(mMessenger.getHelloFormat(), mConfig.getUserName()); // } // // @Override // public String bye() { // // return String.format(mMessenger.getByeFormat(), mConfig.getUserName()); // } // // @Override // public String fibonacci() { // // return mMessenger.getFibInitMessage(); // // } // // @Override // public int calcFibNumber(int input) { // // if(input <=0 ) // return -1; // // return fibMethod(input); // } // // private int fibMethod(int n){ // if(n <= 0) // throw new IllegalArgumentException("Input must be positive integer"); // if(n == 1) // return 1; // if(n == 2) // return 1; // return fibMethod(n-2) + fibMethod(n-1); // } // // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // } // Path: app/src/androidTest/java/com/newegg/tr/dagger2prac/model/ActionModelTest.java import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.model.action.ActionModel; import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/2. */ public class ActionModelTest extends TestCase { @Mock private Action action; @Mock private Messenger mMessenger; @Mock private Config mConfig; @Override protected void setUp() throws Exception { super.setUp(); MockitoAnnotations.initMocks(this); } public void testHello() { String stubPerson = "Who is not important in this case."; String stubMessage = "Test Hello in stub with %s"; String exceptResult = "Test Hello in stub with Who is not important in this case."; when(mMessenger.getHelloFormat()).thenReturn(stubMessage); when(mConfig.getUserName()).thenReturn(stubPerson);
action = new ActionModel(mMessenger, mConfig);
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/module/GlobleModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/10. */ @Module public class GlobleModule { @Provides @Singleton
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/GlobleModule.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/10. */ @Module public class GlobleModule { @Provides @Singleton
public Config provideConfig(){
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/module/GlobleModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/10. */ @Module public class GlobleModule { @Provides @Singleton public Config provideConfig(){
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/GlobleModule.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/10. */ @Module public class GlobleModule { @Provides @Singleton public Config provideConfig(){
return new ConfigManager();
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/MainTestCase.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java // public class MainActivity extends BaseActivity implements MainPageView, AdapterView.OnItemSelectedListener { // // public static MainComponent component; // // @Inject // MainPresenter mPresenter; // // @InjectView(R.id.mainPage_messageText) // TextView messageTextView; // @InjectView(R.id.mainPage_actionSpinner) // Spinner actionSpinner; // @InjectView(R.id.mainPage_inputEditText) // EditText inputText; // @InjectView(R.id.mainPage_submitButton) // Button submitButton; // @InjectView(R.id.mainPage_progress) // View progress; // // @Override // protected void onCreateComponent() { // // MainComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.inject(this); // // initSpinner(); // initSubmitButton(); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // if (resultCode == Activity.RESULT_OK) { // mPresenter.updateUser(); // } // } // // private void initSubmitButton() { // submitButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // // if(inputText.getText().toString().isEmpty()) { // MainActivity.this.onActionError(); // return; // } // // mPresenter.calcFib(Integer.valueOf(inputText.getText().toString())); // } // }); // } // // private void initSpinner() { // String[] actionTexts = {"Hello", "Bye", "Fibonacci"}; // ArrayAdapter<String> actionTextArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, actionTexts); // actionSpinner.setAdapter(actionTextArray); // actionSpinner.setOnItemSelectedListener(this); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // int id = item.getItemId(); // // if (id == R.id.action_settings) { // Intent intent = new Intent(this, SettingActivity.class); // startActivityForResult(intent, 17); // return true; // } // // return super.onOptionsItemSelected(item); // } // // @Override // public void showActionResultText(String resultText) { // messageTextView.setText(resultText); // } // // @Override // public void showInputMethodView(boolean isShow) { // int status = (isShow) ? View.VISIBLE : View.GONE; // // inputText.setVisibility(status); // submitButton.setVisibility(status); // } // // @Override // public void showLoading() { // progress.setVisibility(View.VISIBLE); // } // // @Override // public void hideLoading() { // progress.setVisibility(View.GONE); // } // // @Override // public void onActionError() { // messageTextView.setText(getString(R.string.main_error)); // } // // @Override // public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // switch (position) { // case 0: // mPresenter.onActionSelected(ActionType.HELLO); // break; // case 1: // mPresenter.onActionSelected(ActionType.BYE); // break; // case 2: // mPresenter.onActionSelected(ActionType.FIBONACCI); // break; // // } // } // // @Override // public void onNothingSelected(AdapterView<?> parent) { // // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java // @Singleton // @Component( // modules = TestMainModule.class // ) // public interface MainComponent { // // void inject(MainActivity activity); // // void inject(MainTestCase testCase); // // public class Initializer { // // public static MainComponent mInstance; // // public static MainComponent init(Application app, MainPageView view) { // // MainComponent component = Dagger_MainComponent.builder() // .testMainModule(new TestMainModule(view)) // .build(); // mInstance = component; // return component; // } // } // // }
import android.test.ActivityInstrumentationTestCase2; import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.view.activity.MainActivity; import com.newegg.tr.dagger2prac.view.component.MainComponent; import javax.inject.Inject;
package com.newegg.tr.dagger2prac.view; /** * Created by william on 15/2/17. */ public class MainTestCase extends ActivityInstrumentationTestCase2<MainActivity> { @Inject
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java // public class MainActivity extends BaseActivity implements MainPageView, AdapterView.OnItemSelectedListener { // // public static MainComponent component; // // @Inject // MainPresenter mPresenter; // // @InjectView(R.id.mainPage_messageText) // TextView messageTextView; // @InjectView(R.id.mainPage_actionSpinner) // Spinner actionSpinner; // @InjectView(R.id.mainPage_inputEditText) // EditText inputText; // @InjectView(R.id.mainPage_submitButton) // Button submitButton; // @InjectView(R.id.mainPage_progress) // View progress; // // @Override // protected void onCreateComponent() { // // MainComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.inject(this); // // initSpinner(); // initSubmitButton(); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // if (resultCode == Activity.RESULT_OK) { // mPresenter.updateUser(); // } // } // // private void initSubmitButton() { // submitButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // // if(inputText.getText().toString().isEmpty()) { // MainActivity.this.onActionError(); // return; // } // // mPresenter.calcFib(Integer.valueOf(inputText.getText().toString())); // } // }); // } // // private void initSpinner() { // String[] actionTexts = {"Hello", "Bye", "Fibonacci"}; // ArrayAdapter<String> actionTextArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, actionTexts); // actionSpinner.setAdapter(actionTextArray); // actionSpinner.setOnItemSelectedListener(this); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_main, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // int id = item.getItemId(); // // if (id == R.id.action_settings) { // Intent intent = new Intent(this, SettingActivity.class); // startActivityForResult(intent, 17); // return true; // } // // return super.onOptionsItemSelected(item); // } // // @Override // public void showActionResultText(String resultText) { // messageTextView.setText(resultText); // } // // @Override // public void showInputMethodView(boolean isShow) { // int status = (isShow) ? View.VISIBLE : View.GONE; // // inputText.setVisibility(status); // submitButton.setVisibility(status); // } // // @Override // public void showLoading() { // progress.setVisibility(View.VISIBLE); // } // // @Override // public void hideLoading() { // progress.setVisibility(View.GONE); // } // // @Override // public void onActionError() { // messageTextView.setText(getString(R.string.main_error)); // } // // @Override // public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // switch (position) { // case 0: // mPresenter.onActionSelected(ActionType.HELLO); // break; // case 1: // mPresenter.onActionSelected(ActionType.BYE); // break; // case 2: // mPresenter.onActionSelected(ActionType.FIBONACCI); // break; // // } // } // // @Override // public void onNothingSelected(AdapterView<?> parent) { // // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java // @Singleton // @Component( // modules = TestMainModule.class // ) // public interface MainComponent { // // void inject(MainActivity activity); // // void inject(MainTestCase testCase); // // public class Initializer { // // public static MainComponent mInstance; // // public static MainComponent init(Application app, MainPageView view) { // // MainComponent component = Dagger_MainComponent.builder() // .testMainModule(new TestMainModule(view)) // .build(); // mInstance = component; // return component; // } // } // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/MainTestCase.java import android.test.ActivityInstrumentationTestCase2; import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.view.activity.MainActivity; import com.newegg.tr.dagger2prac.view.component.MainComponent; import javax.inject.Inject; package com.newegg.tr.dagger2prac.view; /** * Created by william on 15/2/17. */ public class MainTestCase extends ActivityInstrumentationTestCase2<MainActivity> { @Inject
protected Action mMockAction;
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import dagger.Module; import dagger.Provides;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/3. */ @Module public class SettingModule {
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import dagger.Module; import dagger.Provides; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/3. */ @Module public class SettingModule {
SettingView view;
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import dagger.Module; import dagger.Provides;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/3. */ @Module public class SettingModule { SettingView view; public SettingModule(SettingView view) { this.view = view; } @Provides
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import dagger.Module; import dagger.Provides; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/3. */ @Module public class SettingModule { SettingView view; public SettingModule(SettingView view) { this.view = view; } @Provides
public SettingPresenter presenter(Config config){
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import dagger.Module; import dagger.Provides;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/3. */ @Module public class SettingModule { SettingView view; public SettingModule(SettingView view) { this.view = view; } @Provides
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import dagger.Module; import dagger.Provides; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/3. */ @Module public class SettingModule { SettingView view; public SettingModule(SettingView view) { this.view = view; } @Provides
public SettingPresenter presenter(Config config){
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import dagger.Module; import dagger.Provides;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/3. */ @Module public class SettingModule { SettingView view; public SettingModule(SettingView view) { this.view = view; } @Provides public SettingPresenter presenter(Config config){
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import dagger.Module; import dagger.Provides; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/3. */ @Module public class SettingModule { SettingView view; public SettingModule(SettingView view) { this.view = view; } @Provides public SettingPresenter presenter(Config config){
return new SettingPresenterImpl(view, config);
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java // @Module // public class SettingModule { // SettingView view; // // public SettingModule(SettingView view) { // this.view = view; // } // // @Provides // public SettingPresenter presenter(Config config){ // return new SettingPresenterImpl(view, config); // } // // // }
import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.module.SettingModule; import com.newegg.tr.dagger2prac.view.scope.Setting; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Setting @Component( dependencies = com.newegg.tr.dagger2prac.view.component.GlobalComponent.class,
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java // @Module // public class SettingModule { // SettingView view; // // public SettingModule(SettingView view) { // this.view = view; // } // // @Provides // public SettingPresenter presenter(Config config){ // return new SettingPresenterImpl(view, config); // } // // // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.module.SettingModule; import com.newegg.tr.dagger2prac.view.scope.Setting; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Setting @Component( dependencies = com.newegg.tr.dagger2prac.view.component.GlobalComponent.class,
modules = SettingModule.class
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java // @Module // public class SettingModule { // SettingView view; // // public SettingModule(SettingView view) { // this.view = view; // } // // @Provides // public SettingPresenter presenter(Config config){ // return new SettingPresenterImpl(view, config); // } // // // }
import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.module.SettingModule; import com.newegg.tr.dagger2prac.view.scope.Setting; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Setting @Component( dependencies = com.newegg.tr.dagger2prac.view.component.GlobalComponent.class, modules = SettingModule.class ) public interface SettingComponent {
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java // @Module // public class SettingModule { // SettingView view; // // public SettingModule(SettingView view) { // this.view = view; // } // // @Provides // public SettingPresenter presenter(Config config){ // return new SettingPresenterImpl(view, config); // } // // // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.module.SettingModule; import com.newegg.tr.dagger2prac.view.scope.Setting; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Setting @Component( dependencies = com.newegg.tr.dagger2prac.view.component.GlobalComponent.class, modules = SettingModule.class ) public interface SettingComponent {
void inject(SettingActivity activity);
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java // @Module // public class SettingModule { // SettingView view; // // public SettingModule(SettingView view) { // this.view = view; // } // // @Provides // public SettingPresenter presenter(Config config){ // return new SettingPresenterImpl(view, config); // } // // // }
import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.module.SettingModule; import com.newegg.tr.dagger2prac.view.scope.Setting; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Setting @Component( dependencies = com.newegg.tr.dagger2prac.view.component.GlobalComponent.class, modules = SettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity); public class Initializer {
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java // @Module // public class SettingModule { // SettingView view; // // public SettingModule(SettingView view) { // this.view = view; // } // // @Provides // public SettingPresenter presenter(Config config){ // return new SettingPresenterImpl(view, config); // } // // // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.module.SettingModule; import com.newegg.tr.dagger2prac.view.scope.Setting; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Setting @Component( dependencies = com.newegg.tr.dagger2prac.view.component.GlobalComponent.class, modules = SettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity); public class Initializer {
public static SettingComponent init(Application app, SettingView view) {
showang/dagger2Example
app/src/release/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java // @Module // public class SettingModule { // SettingView view; // // public SettingModule(SettingView view) { // this.view = view; // } // // @Provides // public SettingPresenter presenter(Config config){ // return new SettingPresenterImpl(view, config); // } // // // }
import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.module.SettingModule; import com.newegg.tr.dagger2prac.view.scope.Setting; import dagger.Component;
package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Setting @Component( dependencies = com.newegg.tr.dagger2prac.view.component.GlobalComponent.class, modules = SettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity); public class Initializer { public static SettingComponent init(Application app, SettingView view) { SettingComponent component = Dagger_SettingComponent.builder()
// Path: app/src/main/java/com/newegg/tr/dagger2prac/Dagger2pracApp.java // public class Dagger2pracApp extends Application { // // public static boolean MOCK_MODE = true; // // GlobalComponent mComponent; // // @Override // public void onCreate() { // super.onCreate(); // mComponent = Dagger_GlobalComponent.create(); // // } // // public GlobalComponent component() { // return mComponent; // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/SettingActivity.java // public class SettingActivity extends BaseActivity implements SettingView, View.OnClickListener { // // @Inject // SettingPresenter mPresenter; // // @InjectView(R.id.settingPage_userNameTextView) // TextView mUserNameTextView; // // @InjectView(R.id.settingPage_changeUserNameButton) // TextView mChangeNameButton; // // @Override // protected void onCreateComponent() { // SettingComponent.Initializer.init(getApplication(), this).inject(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_setting); // ButterKnife.inject(this); // // mChangeNameButton.setOnClickListener(this); // mUserNameTextView.setOnClickListener(this); // updateUserName(mPresenter.getUserName()); // } // // @Override // public void onClick(View v) { // // final View dialogView = getLayoutInflater().inflate(R.layout.activity_setting_dialog, null); // // final AlertDialog renameDialog = new AlertDialog.Builder(this).setTitle("Change User Name").setView(dialogView).setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // EditText renameEditText = (EditText) dialogView.findViewById(R.id.settingPage_dialogRenameEditText); // mPresenter.setUserName(renameEditText.getText().toString()); // dialog.dismiss(); // setResult(Activity.RESULT_OK); // } // }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }).create(); // // renameDialog.show(); // // } // // @Override // public void updateUserName(String userName) { // mUserNameTextView.setText(userName); // } // } // // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/module/SettingModule.java // @Module // public class SettingModule { // SettingView view; // // public SettingModule(SettingView view) { // this.view = view; // } // // @Provides // public SettingPresenter presenter(Config config){ // return new SettingPresenterImpl(view, config); // } // // // } // Path: app/src/release/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java import android.app.Application; import com.newegg.tr.dagger2prac.Dagger2pracApp; import com.newegg.tr.dagger2prac.view.SettingView; import com.newegg.tr.dagger2prac.view.activity.SettingActivity; import com.newegg.tr.dagger2prac.view.module.SettingModule; import com.newegg.tr.dagger2prac.view.scope.Setting; import dagger.Component; package com.newegg.tr.dagger2prac.view.component; /** * Created by william on 15/2/3. */ @Setting @Component( dependencies = com.newegg.tr.dagger2prac.view.component.GlobalComponent.class, modules = SettingModule.class ) public interface SettingComponent { void inject(SettingActivity activity); public class Initializer { public static SettingComponent init(Application app, SettingView view) { SettingComponent component = Dagger_SettingComponent.builder()
.globalComponent(((Dagger2pracApp) app).component())
showang/dagger2Example
app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionType.java // public enum ActionType { // HELLO, BYE, FIBONACCI // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java // @Singleton // @Component( // modules = TestMainModule.class // ) // public interface MainComponent { // // void inject(MainActivity activity); // // void inject(MainTestCase testCase); // // public class Initializer { // // public static MainComponent mInstance; // // public static MainComponent init(Application app, MainPageView view) { // // MainComponent component = Dagger_MainComponent.builder() // .testMainModule(new TestMainModule(view)) // .build(); // mInstance = component; // return component; // } // } // // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.model.action.ActionType; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.view.MainPageView; import com.newegg.tr.dagger2prac.view.component.MainComponent; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.newegg.tr.dagger2prac.view.activity; public class MainActivity extends BaseActivity implements MainPageView, AdapterView.OnItemSelectedListener { public static MainComponent component; @Inject
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionType.java // public enum ActionType { // HELLO, BYE, FIBONACCI // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java // @Singleton // @Component( // modules = TestMainModule.class // ) // public interface MainComponent { // // void inject(MainActivity activity); // // void inject(MainTestCase testCase); // // public class Initializer { // // public static MainComponent mInstance; // // public static MainComponent init(Application app, MainPageView view) { // // MainComponent component = Dagger_MainComponent.builder() // .testMainModule(new TestMainModule(view)) // .build(); // mInstance = component; // return component; // } // } // // } // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.model.action.ActionType; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.view.MainPageView; import com.newegg.tr.dagger2prac.view.component.MainComponent; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.newegg.tr.dagger2prac.view.activity; public class MainActivity extends BaseActivity implements MainPageView, AdapterView.OnItemSelectedListener { public static MainComponent component; @Inject
MainPresenter mPresenter;
showang/dagger2Example
app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionType.java // public enum ActionType { // HELLO, BYE, FIBONACCI // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java // @Singleton // @Component( // modules = TestMainModule.class // ) // public interface MainComponent { // // void inject(MainActivity activity); // // void inject(MainTestCase testCase); // // public class Initializer { // // public static MainComponent mInstance; // // public static MainComponent init(Application app, MainPageView view) { // // MainComponent component = Dagger_MainComponent.builder() // .testMainModule(new TestMainModule(view)) // .build(); // mInstance = component; // return component; // } // } // // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.model.action.ActionType; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.view.MainPageView; import com.newegg.tr.dagger2prac.view.component.MainComponent; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
messageTextView.setText(resultText); } @Override public void showInputMethodView(boolean isShow) { int status = (isShow) ? View.VISIBLE : View.GONE; inputText.setVisibility(status); submitButton.setVisibility(status); } @Override public void showLoading() { progress.setVisibility(View.VISIBLE); } @Override public void hideLoading() { progress.setVisibility(View.GONE); } @Override public void onActionError() { messageTextView.setText(getString(R.string.main_error)); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0:
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/ActionType.java // public enum ActionType { // HELLO, BYE, FIBONACCI // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java // @Singleton // @Component( // modules = TestMainModule.class // ) // public interface MainComponent { // // void inject(MainActivity activity); // // void inject(MainTestCase testCase); // // public class Initializer { // // public static MainComponent mInstance; // // public static MainComponent init(Application app, MainPageView view) { // // MainComponent component = Dagger_MainComponent.builder() // .testMainModule(new TestMainModule(view)) // .build(); // mInstance = component; // return component; // } // } // // } // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/activity/MainActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.model.action.ActionType; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.view.MainPageView; import com.newegg.tr.dagger2prac.view.component.MainComponent; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; messageTextView.setText(resultText); } @Override public void showInputMethodView(boolean isShow) { int status = (isShow) ? View.VISIBLE : View.GONE; inputText.setVisibility(status); submitButton.setVisibility(status); } @Override public void showLoading() { progress.setVisibility(View.VISIBLE); } @Override public void hideLoading() { progress.setVisibility(View.GONE); } @Override public void onActionError() { messageTextView.setText(getString(R.string.main_error)); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0:
mPresenter.onActionSelected(ActionType.HELLO);
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/13. */ @Module public class TestSettingModule { public final static String INIT_NAME = "大中天";
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/13. */ @Module public class TestSettingModule { public final static String INIT_NAME = "大中天";
SettingView mView;
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/13. */ @Module public class TestSettingModule { public final static String INIT_NAME = "大中天"; SettingView mView; @Mock
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/13. */ @Module public class TestSettingModule { public final static String INIT_NAME = "大中天"; SettingView mView; @Mock
Config mMockConfig;
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/13. */ @Module public class TestSettingModule { public final static String INIT_NAME = "大中天"; SettingView mView; @Mock Config mMockConfig; private boolean mIsMock; public TestSettingModule(SettingView view, boolean isMock) { mView = view; mIsMock = isMock; MockitoAnnotations.initMocks(this); when(mMockConfig.getUserName()).thenReturn(INIT_NAME); } @Singleton @Provides
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/13. */ @Module public class TestSettingModule { public final static String INIT_NAME = "大中天"; SettingView mView; @Mock Config mMockConfig; private boolean mIsMock; public TestSettingModule(SettingView view, boolean isMock) { mView = view; mIsMock = isMock; MockitoAnnotations.initMocks(this); when(mMockConfig.getUserName()).thenReturn(INIT_NAME); } @Singleton @Provides
public SettingPresenter provideSettingPresenter(Config config) {
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/13. */ @Module public class TestSettingModule { public final static String INIT_NAME = "大中天"; SettingView mView; @Mock Config mMockConfig; private boolean mIsMock; public TestSettingModule(SettingView view, boolean isMock) { mView = view; mIsMock = isMock; MockitoAnnotations.initMocks(this); when(mMockConfig.getUserName()).thenReturn(INIT_NAME); } @Singleton @Provides public SettingPresenter provideSettingPresenter(Config config) {
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/13. */ @Module public class TestSettingModule { public final static String INIT_NAME = "大中天"; SettingView mView; @Mock Config mMockConfig; private boolean mIsMock; public TestSettingModule(SettingView view, boolean isMock) { mView = view; mIsMock = isMock; MockitoAnnotations.initMocks(this); when(mMockConfig.getUserName()).thenReturn(INIT_NAME); } @Singleton @Provides public SettingPresenter provideSettingPresenter(Config config) {
return new SettingPresenterImpl(mView, config);
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/13. */ @Module public class TestSettingModule { public final static String INIT_NAME = "大中天"; SettingView mView; @Mock Config mMockConfig; private boolean mIsMock; public TestSettingModule(SettingView view, boolean isMock) { mView = view; mIsMock = isMock; MockitoAnnotations.initMocks(this); when(mMockConfig.getUserName()).thenReturn(INIT_NAME); } @Singleton @Provides public SettingPresenter provideSettingPresenter(Config config) { return new SettingPresenterImpl(mView, config); } @Singleton @Provides public Config provideConfig() {
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/ConfigManager.java // public class ConfigManager implements Config { // // private final static String DEFAULT_USER = "William"; // // private String mUserName = DEFAULT_USER; // // @Override // public String getUserName() { // return mUserName; // } // // @Override // public void setUserName(String userName) { // mUserName = userName; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java // public class SettingPresenterImpl implements SettingPresenter { // // SettingView mView; // Config mConfig; // // @Inject // public SettingPresenterImpl(SettingView view, Config config){ // mView = view; // mConfig = config; // } // // @Override // public String getUserName() { // return mConfig.getUserName(); // } // // @Override // public void setUserName(String name) { // mConfig.setUserName(name); // mView.updateUserName(name); // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.model.config.ConfigManager; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.presenter.internal.SettingPresenterImpl; import com.newegg.tr.dagger2prac.view.SettingView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/13. */ @Module public class TestSettingModule { public final static String INIT_NAME = "大中天"; SettingView mView; @Mock Config mMockConfig; private boolean mIsMock; public TestSettingModule(SettingView view, boolean isMock) { mView = view; mIsMock = isMock; MockitoAnnotations.initMocks(this); when(mMockConfig.getUserName()).thenReturn(INIT_NAME); } @Singleton @Provides public SettingPresenter provideSettingPresenter(Config config) { return new SettingPresenterImpl(mView, config); } @Singleton @Provides public Config provideConfig() {
return (mIsMock) ? mMockConfig : new ConfigManager();
showang/dagger2Example
app/src/androidTest/java/com/newegg/tr/dagger2prac/model/MessageModelTest.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/MessageModel.java // public class MessageModel implements Messenger { // // @Override // public String getHelloFormat() { // return "Hello %s!"; // } // // @Override // public String getByeFormat() { // return "Bye %s!!"; // } // // @Override // public String getFibInitMessage() { // return "Plz input a number."; // } // // @Override // public String getCalcText() { // return "Calculating..."; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // }
import com.newegg.tr.dagger2prac.model.message.MessageModel; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase;
package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/3. */ public class MessageModelTest extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); } public void testHelloMessage(){
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/MessageModel.java // public class MessageModel implements Messenger { // // @Override // public String getHelloFormat() { // return "Hello %s!"; // } // // @Override // public String getByeFormat() { // return "Bye %s!!"; // } // // @Override // public String getFibInitMessage() { // return "Plz input a number."; // } // // @Override // public String getCalcText() { // return "Calculating..."; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // } // Path: app/src/androidTest/java/com/newegg/tr/dagger2prac/model/MessageModelTest.java import com.newegg.tr.dagger2prac.model.message.MessageModel; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase; package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/3. */ public class MessageModelTest extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); } public void testHelloMessage(){
Messenger m = new MessageModel();
showang/dagger2Example
app/src/androidTest/java/com/newegg/tr/dagger2prac/model/MessageModelTest.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/MessageModel.java // public class MessageModel implements Messenger { // // @Override // public String getHelloFormat() { // return "Hello %s!"; // } // // @Override // public String getByeFormat() { // return "Bye %s!!"; // } // // @Override // public String getFibInitMessage() { // return "Plz input a number."; // } // // @Override // public String getCalcText() { // return "Calculating..."; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // }
import com.newegg.tr.dagger2prac.model.message.MessageModel; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase;
package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/3. */ public class MessageModelTest extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); } public void testHelloMessage(){
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/MessageModel.java // public class MessageModel implements Messenger { // // @Override // public String getHelloFormat() { // return "Hello %s!"; // } // // @Override // public String getByeFormat() { // return "Bye %s!!"; // } // // @Override // public String getFibInitMessage() { // return "Plz input a number."; // } // // @Override // public String getCalcText() { // return "Calculating..."; // } // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/model/message/Messenger.java // public interface Messenger { // // public String getHelloFormat(); // // public String getByeFormat(); // // public String getFibInitMessage(); // // public String getCalcText(); // } // Path: app/src/androidTest/java/com/newegg/tr/dagger2prac/model/MessageModelTest.java import com.newegg.tr.dagger2prac.model.message.MessageModel; import com.newegg.tr.dagger2prac.model.message.Messenger; import junit.framework.TestCase; package com.newegg.tr.dagger2prac.model; /** * Created by william on 15/2/3. */ public class MessageModelTest extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); } public void testHelloMessage(){
Messenger m = new MessageModel();
showang/dagger2Example
app/src/androidTest/java/com/newegg/tr/dagger2prac/ui/MainActivityTest.java
// Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java // @Singleton // @Component( // modules = TestMainModule.class // ) // public interface MainComponent { // // void inject(MainActivity activity); // // void inject(MainTestCase testCase); // // public class Initializer { // // public static MainComponent mInstance; // // public static MainComponent init(Application app, MainPageView view) { // // MainComponent component = Dagger_MainComponent.builder() // .testMainModule(new TestMainModule(view)) // .build(); // mInstance = component; // return component; // } // } // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/MainTestCase.java // public class MainTestCase extends ActivityInstrumentationTestCase2<MainActivity> { // // @Inject // protected Action mMockAction; // // public MainTestCase() { // super(MainActivity.class); // } // // // }
import android.test.suitebuilder.annotation.LargeTest; import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.view.component.MainComponent; import com.newegg.tr.dagger2prac.view.MainTestCase; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu; import static android.support.test.espresso.action.ViewActions.clearText; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.ui; /** * Created by william on 15/2/3. */ @LargeTest public class MainActivityTest extends MainTestCase { @Override protected void setUp() throws Exception { super.setUp(); getActivity();
// Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/MainComponent.java // @Singleton // @Component( // modules = TestMainModule.class // ) // public interface MainComponent { // // void inject(MainActivity activity); // // void inject(MainTestCase testCase); // // public class Initializer { // // public static MainComponent mInstance; // // public static MainComponent init(Application app, MainPageView view) { // // MainComponent component = Dagger_MainComponent.builder() // .testMainModule(new TestMainModule(view)) // .build(); // mInstance = component; // return component; // } // } // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/MainTestCase.java // public class MainTestCase extends ActivityInstrumentationTestCase2<MainActivity> { // // @Inject // protected Action mMockAction; // // public MainTestCase() { // super(MainActivity.class); // } // // // } // Path: app/src/androidTest/java/com/newegg/tr/dagger2prac/ui/MainActivityTest.java import android.test.suitebuilder.annotation.LargeTest; import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.view.component.MainComponent; import com.newegg.tr.dagger2prac.view.MainTestCase; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu; import static android.support.test.espresso.action.ViewActions.clearText; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.ui; /** * Created by william on 15/2/3. */ @LargeTest public class MainActivityTest extends MainTestCase { @Override protected void setUp() throws Exception { super.setUp(); getActivity();
MainComponent.Initializer.mInstance.inject(this);
showang/dagger2Example
app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // }
import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.view.SettingView; import javax.inject.Inject;
package com.newegg.tr.dagger2prac.presenter.internal; /** * Created by william on 15/2/3. */ public class SettingPresenterImpl implements SettingPresenter { SettingView mView;
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/config/Config.java // public interface Config { // // public String getUserName(); // // public void setUserName(String userName); // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/SettingPresenter.java // public interface SettingPresenter { // // public String getUserName(); // // public void setUserName(String name); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/SettingView.java // public interface SettingView { // // public void updateUserName(String userName); // // } // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/SettingPresenterImpl.java import com.newegg.tr.dagger2prac.model.config.Config; import com.newegg.tr.dagger2prac.presenter.SettingPresenter; import com.newegg.tr.dagger2prac.view.SettingView; import javax.inject.Inject; package com.newegg.tr.dagger2prac.presenter.internal; /** * Created by william on 15/2/3. */ public class SettingPresenterImpl implements SettingPresenter { SettingView mView;
Config mConfig;
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java // public class MainPresenterImpl implements MainPresenter { // // private final static ActionType DEFAULT_ACTION = ActionType.HELLO; // // MainPageView mView; // Action mModel; // // ActionType currentAction = DEFAULT_ACTION; // // @Inject // public MainPresenterImpl(MainPageView view, Action model) { // mModel = model; // mView = view; // } // // @Override // public void onActionSelected(ActionType type) { // String result = "Error"; // boolean isShowInputMethod = false; // currentAction = type; // switch (type){ // case HELLO: // result = mModel.hello(); // isShowInputMethod = false; // break; // case BYE: // result = mModel.bye(); // isShowInputMethod = false; // break; // case FIBONACCI: // result = mModel.fibonacci(); // isShowInputMethod = true; // break; // } // Log.e("MainPresenterImpl", "onActionSelected: " + result); // mView.showInputMethodView(isShowInputMethod); // mView.showActionResultText(result); // } // // @Override // public void calcFib(final int fibNumber) { // Log.e("MainPresenterImpl", "calcFib: " + fibNumber); // mView.showLoading(); // // new AsyncTask<Void, Void, Integer>(){ // // @Override // protected Integer doInBackground(Void... params) { // return mModel.calcFibNumber(fibNumber); // } // // @Override // protected void onPostExecute(Integer result) { // super.onPostExecute(result); // // if(result == -1) { // mView.onActionError(); // }else { // mView.showActionResultText(result.toString()); // } // mView.hideLoading(); // } // }.execute(); // } // // // // @Override // public void updateUser() { // onActionSelected(currentAction); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // }
import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.presenter.internal.MainPresenterImpl; import com.newegg.tr.dagger2prac.view.MainPageView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/17. */ @Module public class TestMainModule {
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java // public class MainPresenterImpl implements MainPresenter { // // private final static ActionType DEFAULT_ACTION = ActionType.HELLO; // // MainPageView mView; // Action mModel; // // ActionType currentAction = DEFAULT_ACTION; // // @Inject // public MainPresenterImpl(MainPageView view, Action model) { // mModel = model; // mView = view; // } // // @Override // public void onActionSelected(ActionType type) { // String result = "Error"; // boolean isShowInputMethod = false; // currentAction = type; // switch (type){ // case HELLO: // result = mModel.hello(); // isShowInputMethod = false; // break; // case BYE: // result = mModel.bye(); // isShowInputMethod = false; // break; // case FIBONACCI: // result = mModel.fibonacci(); // isShowInputMethod = true; // break; // } // Log.e("MainPresenterImpl", "onActionSelected: " + result); // mView.showInputMethodView(isShowInputMethod); // mView.showActionResultText(result); // } // // @Override // public void calcFib(final int fibNumber) { // Log.e("MainPresenterImpl", "calcFib: " + fibNumber); // mView.showLoading(); // // new AsyncTask<Void, Void, Integer>(){ // // @Override // protected Integer doInBackground(Void... params) { // return mModel.calcFibNumber(fibNumber); // } // // @Override // protected void onPostExecute(Integer result) { // super.onPostExecute(result); // // if(result == -1) { // mView.onActionError(); // }else { // mView.showActionResultText(result.toString()); // } // mView.hideLoading(); // } // }.execute(); // } // // // // @Override // public void updateUser() { // onActionSelected(currentAction); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.presenter.internal.MainPresenterImpl; import com.newegg.tr.dagger2prac.view.MainPageView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/17. */ @Module public class TestMainModule {
MainPageView mView;
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java // public class MainPresenterImpl implements MainPresenter { // // private final static ActionType DEFAULT_ACTION = ActionType.HELLO; // // MainPageView mView; // Action mModel; // // ActionType currentAction = DEFAULT_ACTION; // // @Inject // public MainPresenterImpl(MainPageView view, Action model) { // mModel = model; // mView = view; // } // // @Override // public void onActionSelected(ActionType type) { // String result = "Error"; // boolean isShowInputMethod = false; // currentAction = type; // switch (type){ // case HELLO: // result = mModel.hello(); // isShowInputMethod = false; // break; // case BYE: // result = mModel.bye(); // isShowInputMethod = false; // break; // case FIBONACCI: // result = mModel.fibonacci(); // isShowInputMethod = true; // break; // } // Log.e("MainPresenterImpl", "onActionSelected: " + result); // mView.showInputMethodView(isShowInputMethod); // mView.showActionResultText(result); // } // // @Override // public void calcFib(final int fibNumber) { // Log.e("MainPresenterImpl", "calcFib: " + fibNumber); // mView.showLoading(); // // new AsyncTask<Void, Void, Integer>(){ // // @Override // protected Integer doInBackground(Void... params) { // return mModel.calcFibNumber(fibNumber); // } // // @Override // protected void onPostExecute(Integer result) { // super.onPostExecute(result); // // if(result == -1) { // mView.onActionError(); // }else { // mView.showActionResultText(result.toString()); // } // mView.hideLoading(); // } // }.execute(); // } // // // // @Override // public void updateUser() { // onActionSelected(currentAction); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // }
import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.presenter.internal.MainPresenterImpl; import com.newegg.tr.dagger2prac.view.MainPageView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/17. */ @Module public class TestMainModule { MainPageView mView; @Mock
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java // public class MainPresenterImpl implements MainPresenter { // // private final static ActionType DEFAULT_ACTION = ActionType.HELLO; // // MainPageView mView; // Action mModel; // // ActionType currentAction = DEFAULT_ACTION; // // @Inject // public MainPresenterImpl(MainPageView view, Action model) { // mModel = model; // mView = view; // } // // @Override // public void onActionSelected(ActionType type) { // String result = "Error"; // boolean isShowInputMethod = false; // currentAction = type; // switch (type){ // case HELLO: // result = mModel.hello(); // isShowInputMethod = false; // break; // case BYE: // result = mModel.bye(); // isShowInputMethod = false; // break; // case FIBONACCI: // result = mModel.fibonacci(); // isShowInputMethod = true; // break; // } // Log.e("MainPresenterImpl", "onActionSelected: " + result); // mView.showInputMethodView(isShowInputMethod); // mView.showActionResultText(result); // } // // @Override // public void calcFib(final int fibNumber) { // Log.e("MainPresenterImpl", "calcFib: " + fibNumber); // mView.showLoading(); // // new AsyncTask<Void, Void, Integer>(){ // // @Override // protected Integer doInBackground(Void... params) { // return mModel.calcFibNumber(fibNumber); // } // // @Override // protected void onPostExecute(Integer result) { // super.onPostExecute(result); // // if(result == -1) { // mView.onActionError(); // }else { // mView.showActionResultText(result.toString()); // } // mView.hideLoading(); // } // }.execute(); // } // // // // @Override // public void updateUser() { // onActionSelected(currentAction); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.presenter.internal.MainPresenterImpl; import com.newegg.tr.dagger2prac.view.MainPageView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/17. */ @Module public class TestMainModule { MainPageView mView; @Mock
Action mActionModel;
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java // public class MainPresenterImpl implements MainPresenter { // // private final static ActionType DEFAULT_ACTION = ActionType.HELLO; // // MainPageView mView; // Action mModel; // // ActionType currentAction = DEFAULT_ACTION; // // @Inject // public MainPresenterImpl(MainPageView view, Action model) { // mModel = model; // mView = view; // } // // @Override // public void onActionSelected(ActionType type) { // String result = "Error"; // boolean isShowInputMethod = false; // currentAction = type; // switch (type){ // case HELLO: // result = mModel.hello(); // isShowInputMethod = false; // break; // case BYE: // result = mModel.bye(); // isShowInputMethod = false; // break; // case FIBONACCI: // result = mModel.fibonacci(); // isShowInputMethod = true; // break; // } // Log.e("MainPresenterImpl", "onActionSelected: " + result); // mView.showInputMethodView(isShowInputMethod); // mView.showActionResultText(result); // } // // @Override // public void calcFib(final int fibNumber) { // Log.e("MainPresenterImpl", "calcFib: " + fibNumber); // mView.showLoading(); // // new AsyncTask<Void, Void, Integer>(){ // // @Override // protected Integer doInBackground(Void... params) { // return mModel.calcFibNumber(fibNumber); // } // // @Override // protected void onPostExecute(Integer result) { // super.onPostExecute(result); // // if(result == -1) { // mView.onActionError(); // }else { // mView.showActionResultText(result.toString()); // } // mView.hideLoading(); // } // }.execute(); // } // // // // @Override // public void updateUser() { // onActionSelected(currentAction); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // }
import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.presenter.internal.MainPresenterImpl; import com.newegg.tr.dagger2prac.view.MainPageView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/17. */ @Module public class TestMainModule { MainPageView mView; @Mock Action mActionModel; public TestMainModule(MainPageView view) { mView = view; MockitoAnnotations.initMocks(this); } @Provides @Singleton
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java // public class MainPresenterImpl implements MainPresenter { // // private final static ActionType DEFAULT_ACTION = ActionType.HELLO; // // MainPageView mView; // Action mModel; // // ActionType currentAction = DEFAULT_ACTION; // // @Inject // public MainPresenterImpl(MainPageView view, Action model) { // mModel = model; // mView = view; // } // // @Override // public void onActionSelected(ActionType type) { // String result = "Error"; // boolean isShowInputMethod = false; // currentAction = type; // switch (type){ // case HELLO: // result = mModel.hello(); // isShowInputMethod = false; // break; // case BYE: // result = mModel.bye(); // isShowInputMethod = false; // break; // case FIBONACCI: // result = mModel.fibonacci(); // isShowInputMethod = true; // break; // } // Log.e("MainPresenterImpl", "onActionSelected: " + result); // mView.showInputMethodView(isShowInputMethod); // mView.showActionResultText(result); // } // // @Override // public void calcFib(final int fibNumber) { // Log.e("MainPresenterImpl", "calcFib: " + fibNumber); // mView.showLoading(); // // new AsyncTask<Void, Void, Integer>(){ // // @Override // protected Integer doInBackground(Void... params) { // return mModel.calcFibNumber(fibNumber); // } // // @Override // protected void onPostExecute(Integer result) { // super.onPostExecute(result); // // if(result == -1) { // mView.onActionError(); // }else { // mView.showActionResultText(result.toString()); // } // mView.hideLoading(); // } // }.execute(); // } // // // // @Override // public void updateUser() { // onActionSelected(currentAction); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.presenter.internal.MainPresenterImpl; import com.newegg.tr.dagger2prac.view.MainPageView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/17. */ @Module public class TestMainModule { MainPageView mView; @Mock Action mActionModel; public TestMainModule(MainPageView view) { mView = view; MockitoAnnotations.initMocks(this); } @Provides @Singleton
public MainPresenter getPresenter(Action action) {
showang/dagger2Example
app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java // public class MainPresenterImpl implements MainPresenter { // // private final static ActionType DEFAULT_ACTION = ActionType.HELLO; // // MainPageView mView; // Action mModel; // // ActionType currentAction = DEFAULT_ACTION; // // @Inject // public MainPresenterImpl(MainPageView view, Action model) { // mModel = model; // mView = view; // } // // @Override // public void onActionSelected(ActionType type) { // String result = "Error"; // boolean isShowInputMethod = false; // currentAction = type; // switch (type){ // case HELLO: // result = mModel.hello(); // isShowInputMethod = false; // break; // case BYE: // result = mModel.bye(); // isShowInputMethod = false; // break; // case FIBONACCI: // result = mModel.fibonacci(); // isShowInputMethod = true; // break; // } // Log.e("MainPresenterImpl", "onActionSelected: " + result); // mView.showInputMethodView(isShowInputMethod); // mView.showActionResultText(result); // } // // @Override // public void calcFib(final int fibNumber) { // Log.e("MainPresenterImpl", "calcFib: " + fibNumber); // mView.showLoading(); // // new AsyncTask<Void, Void, Integer>(){ // // @Override // protected Integer doInBackground(Void... params) { // return mModel.calcFibNumber(fibNumber); // } // // @Override // protected void onPostExecute(Integer result) { // super.onPostExecute(result); // // if(result == -1) { // mView.onActionError(); // }else { // mView.showActionResultText(result.toString()); // } // mView.hideLoading(); // } // }.execute(); // } // // // // @Override // public void updateUser() { // onActionSelected(currentAction); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // }
import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.presenter.internal.MainPresenterImpl; import com.newegg.tr.dagger2prac.view.MainPageView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/17. */ @Module public class TestMainModule { MainPageView mView; @Mock Action mActionModel; public TestMainModule(MainPageView view) { mView = view; MockitoAnnotations.initMocks(this); } @Provides @Singleton public MainPresenter getPresenter(Action action) {
// Path: app/src/main/java/com/newegg/tr/dagger2prac/model/action/Action.java // public interface Action { // // public String hello(); // // public String bye(); // // public String fibonacci(); // // public int calcFibNumber(int input); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/MainPresenter.java // public interface MainPresenter { // // public void onActionSelected(ActionType type); // // public void calcFib(int fibNumber); // // public void updateUser(); // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/presenter/internal/MainPresenterImpl.java // public class MainPresenterImpl implements MainPresenter { // // private final static ActionType DEFAULT_ACTION = ActionType.HELLO; // // MainPageView mView; // Action mModel; // // ActionType currentAction = DEFAULT_ACTION; // // @Inject // public MainPresenterImpl(MainPageView view, Action model) { // mModel = model; // mView = view; // } // // @Override // public void onActionSelected(ActionType type) { // String result = "Error"; // boolean isShowInputMethod = false; // currentAction = type; // switch (type){ // case HELLO: // result = mModel.hello(); // isShowInputMethod = false; // break; // case BYE: // result = mModel.bye(); // isShowInputMethod = false; // break; // case FIBONACCI: // result = mModel.fibonacci(); // isShowInputMethod = true; // break; // } // Log.e("MainPresenterImpl", "onActionSelected: " + result); // mView.showInputMethodView(isShowInputMethod); // mView.showActionResultText(result); // } // // @Override // public void calcFib(final int fibNumber) { // Log.e("MainPresenterImpl", "calcFib: " + fibNumber); // mView.showLoading(); // // new AsyncTask<Void, Void, Integer>(){ // // @Override // protected Integer doInBackground(Void... params) { // return mModel.calcFibNumber(fibNumber); // } // // @Override // protected void onPostExecute(Integer result) { // super.onPostExecute(result); // // if(result == -1) { // mView.onActionError(); // }else { // mView.showActionResultText(result.toString()); // } // mView.hideLoading(); // } // }.execute(); // } // // // // @Override // public void updateUser() { // onActionSelected(currentAction); // } // // } // // Path: app/src/main/java/com/newegg/tr/dagger2prac/view/MainPageView.java // public interface MainPageView { // // public void showActionResultText(String resultText); // // public void showInputMethodView(boolean isShow); // // public void showLoading(); // // public void hideLoading(); // // public void onActionError(); // } // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestMainModule.java import com.newegg.tr.dagger2prac.model.action.Action; import com.newegg.tr.dagger2prac.presenter.MainPresenter; import com.newegg.tr.dagger2prac.presenter.internal.MainPresenterImpl; import com.newegg.tr.dagger2prac.view.MainPageView; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.newegg.tr.dagger2prac.view.module; /** * Created by william on 15/2/17. */ @Module public class TestMainModule { MainPageView mView; @Mock Action mActionModel; public TestMainModule(MainPageView view) { mView = view; MockitoAnnotations.initMocks(this); } @Provides @Singleton public MainPresenter getPresenter(Action action) {
return new MainPresenterImpl(mView, action);
showang/dagger2Example
app/src/androidTest/java/com/newegg/tr/dagger2prac/ui/SettingActivityTest.java
// Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java // @Singleton // @Component( // modules = TestSettingModule.class // ) // public interface SettingComponent { // // void inject(SettingActivity activity); // // void inject(SettingTestCase testSetting); // // Config getConfig(); // // public class Initializer { // public static SettingComponent mInstance; // // public static SettingComponent init(Application app, SettingView view) { // // SettingComponent component = Dagger_SettingComponent.builder() // .testSettingModule(new TestSettingModule(view, ((Dagger2pracApp) app).MOCK_MODE)).build(); // // mInstance = component; // return component; // } // // } // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // }
import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.view.component.SettingComponent; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.clearText; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.ui; /** * Created by william on 15/2/13. */ public class SettingActivityTest extends SettingTestCase { String changedName = "William"; @Override protected void setUp() throws Exception { super.setUp(); getActivity();
// Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java // @Singleton // @Component( // modules = TestSettingModule.class // ) // public interface SettingComponent { // // void inject(SettingActivity activity); // // void inject(SettingTestCase testSetting); // // Config getConfig(); // // public class Initializer { // public static SettingComponent mInstance; // // public static SettingComponent init(Application app, SettingView view) { // // SettingComponent component = Dagger_SettingComponent.builder() // .testSettingModule(new TestSettingModule(view, ((Dagger2pracApp) app).MOCK_MODE)).build(); // // mInstance = component; // return component; // } // // } // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // } // Path: app/src/androidTest/java/com/newegg/tr/dagger2prac/ui/SettingActivityTest.java import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.view.component.SettingComponent; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.clearText; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.ui; /** * Created by william on 15/2/13. */ public class SettingActivityTest extends SettingTestCase { String changedName = "William"; @Override protected void setUp() throws Exception { super.setUp(); getActivity();
SettingComponent.Initializer.mInstance.inject(this);
showang/dagger2Example
app/src/androidTest/java/com/newegg/tr/dagger2prac/ui/SettingActivityTest.java
// Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java // @Singleton // @Component( // modules = TestSettingModule.class // ) // public interface SettingComponent { // // void inject(SettingActivity activity); // // void inject(SettingTestCase testSetting); // // Config getConfig(); // // public class Initializer { // public static SettingComponent mInstance; // // public static SettingComponent init(Application app, SettingView view) { // // SettingComponent component = Dagger_SettingComponent.builder() // .testSettingModule(new TestSettingModule(view, ((Dagger2pracApp) app).MOCK_MODE)).build(); // // mInstance = component; // return component; // } // // } // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // }
import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.view.component.SettingComponent; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.clearText; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.mockito.Mockito.when;
package com.newegg.tr.dagger2prac.ui; /** * Created by william on 15/2/13. */ public class SettingActivityTest extends SettingTestCase { String changedName = "William"; @Override protected void setUp() throws Exception { super.setUp(); getActivity(); SettingComponent.Initializer.mInstance.inject(this); } public void testChangeName() {
// Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/component/SettingComponent.java // @Singleton // @Component( // modules = TestSettingModule.class // ) // public interface SettingComponent { // // void inject(SettingActivity activity); // // void inject(SettingTestCase testSetting); // // Config getConfig(); // // public class Initializer { // public static SettingComponent mInstance; // // public static SettingComponent init(Application app, SettingView view) { // // SettingComponent component = Dagger_SettingComponent.builder() // .testSettingModule(new TestSettingModule(view, ((Dagger2pracApp) app).MOCK_MODE)).build(); // // mInstance = component; // return component; // } // // } // // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/SettingTestCase.java // public class SettingTestCase extends ActivityInstrumentationTestCase2<SettingActivity> { // // @Inject // protected Config mMockConfig; // // public SettingTestCase() { // super(SettingActivity.class); // } // } // // Path: app/src/debug/java/com/newegg/tr/dagger2prac/view/module/TestSettingModule.java // @Module // public class TestSettingModule { // // // public final static String INIT_NAME = "大中天"; // SettingView mView; // @Mock // Config mMockConfig; // private boolean mIsMock; // // public TestSettingModule(SettingView view, boolean isMock) { // mView = view; // mIsMock = isMock; // MockitoAnnotations.initMocks(this); // when(mMockConfig.getUserName()).thenReturn(INIT_NAME); // } // // @Singleton // @Provides // public SettingPresenter provideSettingPresenter(Config config) { // return new SettingPresenterImpl(mView, config); // } // // @Singleton // @Provides // public Config provideConfig() { // return (mIsMock) ? mMockConfig : new ConfigManager(); // } // // } // Path: app/src/androidTest/java/com/newegg/tr/dagger2prac/ui/SettingActivityTest.java import com.newegg.tr.dagger2prac.R; import com.newegg.tr.dagger2prac.view.component.SettingComponent; import com.newegg.tr.dagger2prac.view.SettingTestCase; import com.newegg.tr.dagger2prac.view.module.TestSettingModule; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.clearText; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.mockito.Mockito.when; package com.newegg.tr.dagger2prac.ui; /** * Created by william on 15/2/13. */ public class SettingActivityTest extends SettingTestCase { String changedName = "William"; @Override protected void setUp() throws Exception { super.setUp(); getActivity(); SettingComponent.Initializer.mInstance.inject(this); } public void testChangeName() {
onView(withId(R.id.settingPage_userNameTextView)).check(matches(withText(TestSettingModule.INIT_NAME)));
uservoice/uservoice-android-sdk
UserVoiceSDK/src/com/uservoice/uservoicesdk/model/Article.java
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/rest/RestTask.java // public class RestTask extends AsyncTask<String, String, RestResult> { // private String urlPath; // private RestMethod method; // private Map<String, String> params; // private RestTaskCallback callback; // private Context context; // // public RestTask(Context context, RestMethod method, String urlPath, Map<String, String> params, RestTaskCallback callback) { // this.context = context.getApplicationContext(); // this.method = method; // this.urlPath = urlPath; // this.callback = callback; // this.params = params; // } // // @Override // protected RestResult doInBackground(String... args) { // try { // Request request = createRequest(); // if (isCancelled()) // throw new InterruptedException(); // OkHttpClient client = new OkHttpClient(); // OAuthConsumer consumer = Session.getInstance().getOAuthConsumer(context); // if (consumer != null) { // AccessToken accessToken = Session.getInstance().getAccessToken(); // if (accessToken != null) { // consumer.setTokenWithSecret(accessToken.getKey(), accessToken.getSecret()); // } // request = (Request) consumer.sign(request).unwrap(); // } // Log.d("UV", urlPath); // if (isCancelled()) // throw new InterruptedException(); // // TODO it would be nice to find a way to abort the request on cancellation // Response response = client.newCall(request).execute(); // if (isCancelled()) // throw new InterruptedException(); // int statusCode = response.code(); // String body = response.body().string(); // if (statusCode >= 400) { // Log.d("UV", body); // } // if (isCancelled()) // throw new InterruptedException(); // return new RestResult(statusCode, new JSONObject(body)); // } catch (Exception e) { // return new RestResult(e); // } // } // // private Request createRequest() throws URISyntaxException, UnsupportedEncodingException { // Request.Builder builder = new Request.Builder() // .addHeader("Accept-Language", Locale.getDefault().getLanguage()) // .addHeader("API-Client", String.format("uservoice-android-%s", UserVoice.getVersion())) // .addHeader("User-Agent", String.format("uservoice-android-%s", UserVoice.getVersion())); // // String host = Session.getInstance().getConfig(context).getSite(); // Uri.Builder uriBuilder = new Uri.Builder(); // uriBuilder.scheme(host.contains(".us.com") ? "http" : "https"); // uriBuilder.encodedAuthority(host); // uriBuilder.path(urlPath); // // if (method == RestMethod.GET || method == RestMethod.DELETE) { // builder.method(method.toString(), null); // addParamsToQueryString(builder, uriBuilder); // } else { // builder.url(uriBuilder.build().toString()); // addParamsToBody(builder); // } // return builder.build(); // } // // @Override // protected void onPostExecute(RestResult result) { // if (result.isError()) { // callback.onError(result); // } else { // try { // callback.onComplete(result.getObject()); // } catch (JSONException e) { // callback.onError(new RestResult(e, result.getStatusCode(), result.getObject())); // } // } // super.onPostExecute(result); // } // // private void addParamsToQueryString(Request.Builder builder, Uri.Builder uriBuilder) throws URISyntaxException { // if (params != null) { // for (Map.Entry<String,String> param : params.entrySet()) { // uriBuilder.appendQueryParameter(param.getKey(), param.getValue()); // } // } // builder.url(uriBuilder.build().toString()); // } // // private void addParamsToBody(Request.Builder builder) throws UnsupportedEncodingException, URISyntaxException { // if (params != null) { // FormBody.Builder paramsBuilder = new FormBody.Builder(); // for (Map.Entry<String,String> param : params.entrySet()) { // if (param.getValue() != null) { // paramsBuilder.add(param.getKey(), param.getValue()); // } // } // builder.method(method.toString(), paramsBuilder.build()); // } // } // // }
import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.uservoice.uservoicesdk.rest.Callback; import com.uservoice.uservoicesdk.rest.RestTask; import com.uservoice.uservoicesdk.rest.RestTaskCallback;
public Article() {} public static void loadPage(Context context, int page, final Callback<List<Article>> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("sort", "ordered"); params.put("filter", "published"); params.put("per_page", "50"); params.put("page", String.valueOf(page)); doGet(context, apiPath("/articles.json"), params, new RestTaskCallback(callback) { @Override public void onComplete(JSONObject result) throws JSONException { callback.onModel(deserializeList(result, "articles", Article.class)); } }); } public static void loadPageForTopic(Context context, int topicId, int page, final Callback<List<Article>> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("sort", "ordered"); params.put("filter", "published"); params.put("per_page", "50"); params.put("page", String.valueOf(page)); doGet(context, apiPath("/topics/%d/articles.json", topicId), params, new RestTaskCallback(callback) { @Override public void onComplete(JSONObject result) throws JSONException { callback.onModel(deserializeList(result, "articles", Article.class)); } }); }
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/rest/RestTask.java // public class RestTask extends AsyncTask<String, String, RestResult> { // private String urlPath; // private RestMethod method; // private Map<String, String> params; // private RestTaskCallback callback; // private Context context; // // public RestTask(Context context, RestMethod method, String urlPath, Map<String, String> params, RestTaskCallback callback) { // this.context = context.getApplicationContext(); // this.method = method; // this.urlPath = urlPath; // this.callback = callback; // this.params = params; // } // // @Override // protected RestResult doInBackground(String... args) { // try { // Request request = createRequest(); // if (isCancelled()) // throw new InterruptedException(); // OkHttpClient client = new OkHttpClient(); // OAuthConsumer consumer = Session.getInstance().getOAuthConsumer(context); // if (consumer != null) { // AccessToken accessToken = Session.getInstance().getAccessToken(); // if (accessToken != null) { // consumer.setTokenWithSecret(accessToken.getKey(), accessToken.getSecret()); // } // request = (Request) consumer.sign(request).unwrap(); // } // Log.d("UV", urlPath); // if (isCancelled()) // throw new InterruptedException(); // // TODO it would be nice to find a way to abort the request on cancellation // Response response = client.newCall(request).execute(); // if (isCancelled()) // throw new InterruptedException(); // int statusCode = response.code(); // String body = response.body().string(); // if (statusCode >= 400) { // Log.d("UV", body); // } // if (isCancelled()) // throw new InterruptedException(); // return new RestResult(statusCode, new JSONObject(body)); // } catch (Exception e) { // return new RestResult(e); // } // } // // private Request createRequest() throws URISyntaxException, UnsupportedEncodingException { // Request.Builder builder = new Request.Builder() // .addHeader("Accept-Language", Locale.getDefault().getLanguage()) // .addHeader("API-Client", String.format("uservoice-android-%s", UserVoice.getVersion())) // .addHeader("User-Agent", String.format("uservoice-android-%s", UserVoice.getVersion())); // // String host = Session.getInstance().getConfig(context).getSite(); // Uri.Builder uriBuilder = new Uri.Builder(); // uriBuilder.scheme(host.contains(".us.com") ? "http" : "https"); // uriBuilder.encodedAuthority(host); // uriBuilder.path(urlPath); // // if (method == RestMethod.GET || method == RestMethod.DELETE) { // builder.method(method.toString(), null); // addParamsToQueryString(builder, uriBuilder); // } else { // builder.url(uriBuilder.build().toString()); // addParamsToBody(builder); // } // return builder.build(); // } // // @Override // protected void onPostExecute(RestResult result) { // if (result.isError()) { // callback.onError(result); // } else { // try { // callback.onComplete(result.getObject()); // } catch (JSONException e) { // callback.onError(new RestResult(e, result.getStatusCode(), result.getObject())); // } // } // super.onPostExecute(result); // } // // private void addParamsToQueryString(Request.Builder builder, Uri.Builder uriBuilder) throws URISyntaxException { // if (params != null) { // for (Map.Entry<String,String> param : params.entrySet()) { // uriBuilder.appendQueryParameter(param.getKey(), param.getValue()); // } // } // builder.url(uriBuilder.build().toString()); // } // // private void addParamsToBody(Request.Builder builder) throws UnsupportedEncodingException, URISyntaxException { // if (params != null) { // FormBody.Builder paramsBuilder = new FormBody.Builder(); // for (Map.Entry<String,String> param : params.entrySet()) { // if (param.getValue() != null) { // paramsBuilder.add(param.getKey(), param.getValue()); // } // } // builder.method(method.toString(), paramsBuilder.build()); // } // } // // } // Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/model/Article.java import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.uservoice.uservoicesdk.rest.Callback; import com.uservoice.uservoicesdk.rest.RestTask; import com.uservoice.uservoicesdk.rest.RestTaskCallback; public Article() {} public static void loadPage(Context context, int page, final Callback<List<Article>> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("sort", "ordered"); params.put("filter", "published"); params.put("per_page", "50"); params.put("page", String.valueOf(page)); doGet(context, apiPath("/articles.json"), params, new RestTaskCallback(callback) { @Override public void onComplete(JSONObject result) throws JSONException { callback.onModel(deserializeList(result, "articles", Article.class)); } }); } public static void loadPageForTopic(Context context, int topicId, int page, final Callback<List<Article>> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("sort", "ordered"); params.put("filter", "published"); params.put("per_page", "50"); params.put("page", String.valueOf(page)); doGet(context, apiPath("/topics/%d/articles.json", topicId), params, new RestTaskCallback(callback) { @Override public void onComplete(JSONObject result) throws JSONException { callback.onModel(deserializeList(result, "articles", Article.class)); } }); }
public static RestTask loadInstantAnswers(Context context, String query, final Callback<List<BaseModel>> callback) {
uservoice/uservoice-android-sdk
UserVoiceSDK/src/com/uservoice/uservoicesdk/ui/SearchExpandListener.java
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/activity/SearchActivity.java // @SuppressLint("NewApi") // public abstract class SearchActivity extends FragmentListActivity { // private int originalNavigationMode = -1; // // public SearchAdapter<?> getSearchAdapter() { // return searchAdapter; // } // // public void updateScopedSearch(int results, int articleResults, int ideaResults) { // if (hasActionBar()) { // allTab.setText(String.format("%s (%d)", getString(R.string.uv_all_results_filter), results)); // articlesTab.setText(String.format("%s (%d)", getString(R.string.uv_articles_filter), articleResults)); // ideasTab.setText(String.format("%s (%d)", getString(R.string.uv_ideas_filter), ideaResults)); // } // } // // public void showSearch() { // ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.uv_view_flipper); // viewFlipper.setDisplayedChild(1); // if (hasActionBar()) { // if (originalNavigationMode == -1) // originalNavigationMode = actionBar.getNavigationMode(); // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // } // } // // public void hideSearch() { // ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.uv_view_flipper); // viewFlipper.setDisplayedChild(0); // if (hasActionBar()) { // actionBar.setNavigationMode(originalNavigationMode == -1 ? ActionBar.NAVIGATION_MODE_STANDARD : originalNavigationMode); // } // } // // protected void setupScopedSearch(Menu menu) { // MenuItem searchItem = menu.findItem(R.id.uv_action_search); // if (hasActionBar()) { // MenuItemCompat.setOnActionExpandListener(searchItem, new SearchExpandListener(this)); // SearchView search = (SearchView) MenuItemCompat.getActionView(searchItem); // search.setOnQueryTextListener(new SearchQueryListener(this)); // searchAdapter = new MixedSearchAdapter(this); // ListView searchView = new ListView(this); // searchView.setAdapter(searchAdapter); // searchView.setOnItemClickListener(searchAdapter); // // // ensure that the viewflipper is set up // getListView(); // // ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.uv_view_flipper); // viewFlipper.addView(searchView, 1); // // ActionBar.TabListener listener = new ActionBar.TabListener() { // @Override // public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { // } // // @Override // public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { // searchAdapter.setScope((Integer) tab.getTag()); // } // // @Override // public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { // } // }; // allTab = actionBar.newTab().setText(getString(R.string.uv_all_results_filter)).setTabListener(listener).setTag(PortalAdapter.SCOPE_ALL); // actionBar.addTab(allTab); // articlesTab = actionBar.newTab().setText(getString(R.string.uv_articles_filter)).setTabListener(listener).setTag(PortalAdapter.SCOPE_ARTICLES); // actionBar.addTab(articlesTab); // ideasTab = actionBar.newTab().setText(getString(R.string.uv_ideas_filter)).setTabListener(listener).setTag(PortalAdapter.SCOPE_IDEAS); // actionBar.addTab(ideasTab); // } else { // searchItem.setVisible(false); // } // } // }
import android.annotation.SuppressLint; import android.support.v4.view.MenuItemCompat; import android.view.MenuItem; import com.uservoice.uservoicesdk.activity.SearchActivity;
package com.uservoice.uservoicesdk.ui; @SuppressLint("NewApi") public class SearchExpandListener implements MenuItemCompat.OnActionExpandListener {
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/activity/SearchActivity.java // @SuppressLint("NewApi") // public abstract class SearchActivity extends FragmentListActivity { // private int originalNavigationMode = -1; // // public SearchAdapter<?> getSearchAdapter() { // return searchAdapter; // } // // public void updateScopedSearch(int results, int articleResults, int ideaResults) { // if (hasActionBar()) { // allTab.setText(String.format("%s (%d)", getString(R.string.uv_all_results_filter), results)); // articlesTab.setText(String.format("%s (%d)", getString(R.string.uv_articles_filter), articleResults)); // ideasTab.setText(String.format("%s (%d)", getString(R.string.uv_ideas_filter), ideaResults)); // } // } // // public void showSearch() { // ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.uv_view_flipper); // viewFlipper.setDisplayedChild(1); // if (hasActionBar()) { // if (originalNavigationMode == -1) // originalNavigationMode = actionBar.getNavigationMode(); // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // } // } // // public void hideSearch() { // ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.uv_view_flipper); // viewFlipper.setDisplayedChild(0); // if (hasActionBar()) { // actionBar.setNavigationMode(originalNavigationMode == -1 ? ActionBar.NAVIGATION_MODE_STANDARD : originalNavigationMode); // } // } // // protected void setupScopedSearch(Menu menu) { // MenuItem searchItem = menu.findItem(R.id.uv_action_search); // if (hasActionBar()) { // MenuItemCompat.setOnActionExpandListener(searchItem, new SearchExpandListener(this)); // SearchView search = (SearchView) MenuItemCompat.getActionView(searchItem); // search.setOnQueryTextListener(new SearchQueryListener(this)); // searchAdapter = new MixedSearchAdapter(this); // ListView searchView = new ListView(this); // searchView.setAdapter(searchAdapter); // searchView.setOnItemClickListener(searchAdapter); // // // ensure that the viewflipper is set up // getListView(); // // ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.uv_view_flipper); // viewFlipper.addView(searchView, 1); // // ActionBar.TabListener listener = new ActionBar.TabListener() { // @Override // public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { // } // // @Override // public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { // searchAdapter.setScope((Integer) tab.getTag()); // } // // @Override // public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { // } // }; // allTab = actionBar.newTab().setText(getString(R.string.uv_all_results_filter)).setTabListener(listener).setTag(PortalAdapter.SCOPE_ALL); // actionBar.addTab(allTab); // articlesTab = actionBar.newTab().setText(getString(R.string.uv_articles_filter)).setTabListener(listener).setTag(PortalAdapter.SCOPE_ARTICLES); // actionBar.addTab(articlesTab); // ideasTab = actionBar.newTab().setText(getString(R.string.uv_ideas_filter)).setTabListener(listener).setTag(PortalAdapter.SCOPE_IDEAS); // actionBar.addTab(ideasTab); // } else { // searchItem.setVisible(false); // } // } // } // Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/ui/SearchExpandListener.java import android.annotation.SuppressLint; import android.support.v4.view.MenuItemCompat; import android.view.MenuItem; import com.uservoice.uservoicesdk.activity.SearchActivity; package com.uservoice.uservoicesdk.ui; @SuppressLint("NewApi") public class SearchExpandListener implements MenuItemCompat.OnActionExpandListener {
private final SearchActivity searchActivity;
uservoice/uservoice-android-sdk
UserVoiceSDK/src/com/uservoice/uservoicesdk/model/AccessToken.java
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/Session.java // public class Session { // // private static Session instance; // // public static synchronized Session getInstance() { // if (instance == null) { // instance = new Session(); // } // return instance; // } // // public static void reset() { // instance = null; // } // // private Session() { // } // // private Config config; // private OAuthConsumer oauthConsumer; // private RequestToken requestToken; // private AccessToken accessToken; // private User user; // private ClientConfig clientConfig; // private Forum forum; // private List<Topic> topics; // private Map<String, String> externalIds = new HashMap<>(); // private Runnable signinListener; // // public Config getConfig(Context context) { // if (config == null && context != null) { // config = Config.load(getSharedPreferences(context), "config", "config", Config.class); // } // return config; // } // // public void init(Context context, Config config) { // this.config = config; // persistIdentity(context, config.getName(), config.getEmail()); // config.persist(getSharedPreferences(context), "config", "config"); // persistSite(context); // } // // public void persistIdentity(Context context, String name, String email) { // Editor edit = getSharedPreferences(context).edit(); // edit.putString("user_name", name); // if (SigninManager.isValidEmail(email)) { // edit.putString("user_email", email); // } // edit.commit(); // } // // public String getName(Context context) { // if (user != null) // return user.getName(); // return getSharedPreferences(context).getString("user_name", null); // } // // public String getEmail(Context context) { // if (user != null) // return user.getEmail(); // return getSharedPreferences(context).getString("user_email", null); // } // // public RequestToken getRequestToken() { // return requestToken; // } // // public void setRequestToken(RequestToken requestToken) { // this.requestToken = requestToken; // } // // public OAuthConsumer getOAuthConsumer(Context context) { // if (oauthConsumer == null) { // if (getConfig(context).getKey() != null) // oauthConsumer = new OkOAuthConsumer(getConfig(context).getKey(), getConfig(context).getSecret()); // else if (clientConfig != null) // oauthConsumer = new OkOAuthConsumer(clientConfig.getKey(), clientConfig.getSecret()); // } // return oauthConsumer; // } // // public AccessToken getAccessToken() { // return accessToken; // } // // public void setAccessToken(Context context, AccessToken accessToken) { // this.accessToken = accessToken; // accessToken.persist(getSharedPreferences(context), "access_token", "access_token"); // if (signinListener != null) // signinListener.run(); // } // // protected void persistSite(Context context) { // Editor edit = context.getSharedPreferences("uv_site", 0).edit(); // edit.putString("site", config.getSite()); // edit.commit(); // } // // public SharedPreferences getSharedPreferences(Context context) { // String site; // if (config != null) { // site = config.getSite(); // } else { // site = context.getSharedPreferences("uv_site", 0).getString("site", null); // } // // TODO It is possible the site could be null. // // We should have a checked UserVoiceCouldNotBeInitializedException that will inform the controller to dismiss itself // return context.getSharedPreferences("uv_" + site.replaceAll("\\W", "_"), 0); // } // // public void setAccessToken(AccessToken accessToken) { // this.accessToken = accessToken; // } // // public User getUser() { // return user; // } // // public void setUser(Context context, User user) { // this.user = user; // persistIdentity(context, user.getName(), user.getEmail()); // } // // public ClientConfig getClientConfig() { // return clientConfig; // } // // public void setClientConfig(ClientConfig clientConfig) { // this.clientConfig = clientConfig; // } // // public void setExternalId(String scope, String id) { // externalIds.put(scope, id); // } // // public Map<String, String> getExternalIds() { // return externalIds; // } // // public Forum getForum() { // return forum; // } // // public void setForum(Forum forum) { // this.forum = forum; // } // // public void setTopics(List<Topic> topics) { // this.topics = topics; // } // // public List<Topic> getTopics() { // return topics; // } // // public void setSignInListener(Runnable runnable) { // signinListener = runnable; // } // }
import android.content.Context; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.uservoice.uservoicesdk.Session; import com.uservoice.uservoicesdk.rest.Callback; import com.uservoice.uservoicesdk.rest.RestTaskCallback;
package com.uservoice.uservoicesdk.model; public class AccessToken extends BaseModel { private String key; private String secret; public static void authorize(Context context, String email, String password, final Callback<AccessToken> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("email", email); params.put("password", password);
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/Session.java // public class Session { // // private static Session instance; // // public static synchronized Session getInstance() { // if (instance == null) { // instance = new Session(); // } // return instance; // } // // public static void reset() { // instance = null; // } // // private Session() { // } // // private Config config; // private OAuthConsumer oauthConsumer; // private RequestToken requestToken; // private AccessToken accessToken; // private User user; // private ClientConfig clientConfig; // private Forum forum; // private List<Topic> topics; // private Map<String, String> externalIds = new HashMap<>(); // private Runnable signinListener; // // public Config getConfig(Context context) { // if (config == null && context != null) { // config = Config.load(getSharedPreferences(context), "config", "config", Config.class); // } // return config; // } // // public void init(Context context, Config config) { // this.config = config; // persistIdentity(context, config.getName(), config.getEmail()); // config.persist(getSharedPreferences(context), "config", "config"); // persistSite(context); // } // // public void persistIdentity(Context context, String name, String email) { // Editor edit = getSharedPreferences(context).edit(); // edit.putString("user_name", name); // if (SigninManager.isValidEmail(email)) { // edit.putString("user_email", email); // } // edit.commit(); // } // // public String getName(Context context) { // if (user != null) // return user.getName(); // return getSharedPreferences(context).getString("user_name", null); // } // // public String getEmail(Context context) { // if (user != null) // return user.getEmail(); // return getSharedPreferences(context).getString("user_email", null); // } // // public RequestToken getRequestToken() { // return requestToken; // } // // public void setRequestToken(RequestToken requestToken) { // this.requestToken = requestToken; // } // // public OAuthConsumer getOAuthConsumer(Context context) { // if (oauthConsumer == null) { // if (getConfig(context).getKey() != null) // oauthConsumer = new OkOAuthConsumer(getConfig(context).getKey(), getConfig(context).getSecret()); // else if (clientConfig != null) // oauthConsumer = new OkOAuthConsumer(clientConfig.getKey(), clientConfig.getSecret()); // } // return oauthConsumer; // } // // public AccessToken getAccessToken() { // return accessToken; // } // // public void setAccessToken(Context context, AccessToken accessToken) { // this.accessToken = accessToken; // accessToken.persist(getSharedPreferences(context), "access_token", "access_token"); // if (signinListener != null) // signinListener.run(); // } // // protected void persistSite(Context context) { // Editor edit = context.getSharedPreferences("uv_site", 0).edit(); // edit.putString("site", config.getSite()); // edit.commit(); // } // // public SharedPreferences getSharedPreferences(Context context) { // String site; // if (config != null) { // site = config.getSite(); // } else { // site = context.getSharedPreferences("uv_site", 0).getString("site", null); // } // // TODO It is possible the site could be null. // // We should have a checked UserVoiceCouldNotBeInitializedException that will inform the controller to dismiss itself // return context.getSharedPreferences("uv_" + site.replaceAll("\\W", "_"), 0); // } // // public void setAccessToken(AccessToken accessToken) { // this.accessToken = accessToken; // } // // public User getUser() { // return user; // } // // public void setUser(Context context, User user) { // this.user = user; // persistIdentity(context, user.getName(), user.getEmail()); // } // // public ClientConfig getClientConfig() { // return clientConfig; // } // // public void setClientConfig(ClientConfig clientConfig) { // this.clientConfig = clientConfig; // } // // public void setExternalId(String scope, String id) { // externalIds.put(scope, id); // } // // public Map<String, String> getExternalIds() { // return externalIds; // } // // public Forum getForum() { // return forum; // } // // public void setForum(Forum forum) { // this.forum = forum; // } // // public void setTopics(List<Topic> topics) { // this.topics = topics; // } // // public List<Topic> getTopics() { // return topics; // } // // public void setSignInListener(Runnable runnable) { // signinListener = runnable; // } // } // Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/model/AccessToken.java import android.content.Context; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.uservoice.uservoicesdk.Session; import com.uservoice.uservoicesdk.rest.Callback; import com.uservoice.uservoicesdk.rest.RestTaskCallback; package com.uservoice.uservoicesdk.model; public class AccessToken extends BaseModel { private String key; private String secret; public static void authorize(Context context, String email, String password, final Callback<AccessToken> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("email", email); params.put("password", password);
params.put("request_token", Session.getInstance().getRequestToken().getKey());
uservoice/uservoice-android-sdk
UserVoiceSDK/src/com/uservoice/uservoicesdk/model/Ticket.java
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/babayaga/Babayaga.java // public class Babayaga { // // static String DOMAIN = "by.uservoice.com"; // public static String CHANNEL = "d"; // public static String EXTERNAL_CHANNEL = "x"; // // private static class Track { // public String event; // public Map<String, Object> eventProps; // // public Track(String event, Map<String, Object> eventProps) { // this.event = event; // this.eventProps = eventProps; // } // } // // private static String uvts; // private static SharedPreferences prefs; // // public enum Event { // VIEW_APP("g"), // VIEW_FORUM("m"), // VIEW_TOPIC("c"), // VIEW_KB("k"), // VIEW_CHANNEL("o"), // VIEW_IDEA("i"), // VIEW_ARTICLE("f"), // AUTHENTICATE("u"), // SEARCH_IDEAS("s"), // SEARCH_ARTICLES("r"), // VOTE_IDEA("v"), // VOTE_ARTICLE("z"), // SUBMIT_TICKET("t"), // SUBMIT_IDEA("d"), // SUBSCRIBE_IDEA("b"), // IDENTIFY("y"), // COMMENT_IDEA("h"); // // private final String code; // // private Event(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // } // // public static void setUvts(String uvts) { // Babayaga.uvts = uvts; // Editor edit = prefs.edit(); // edit.putString("uvts", uvts); // edit.commit(); // } // // public static void track(Context context, Event event) { // track(context, event, null); // } // // public static void track(Context context, Event event, String searchText, List<? extends BaseModel> results) { // Map<String, Object> props = new HashMap<String, Object>(); // List<Integer> ids = new ArrayList<Integer>(results.size()); // for (BaseModel model : results) { // ids.add(model.getId()); // } // props.put("ids", ids); // props.put("text", searchText); // track(context, event, props); // } // // public static void track(Context context, Event event, int id) { // Map<String, Object> props = new HashMap<String, Object>(); // props.put("id", id); // track(context, event, props); // } // // public static void track(Context context, Event event, Map<String, Object> eventProps) { // track(context, event.getCode(), eventProps); // } // // public static void track(Context context, String event, Map<String, Object> eventProps) { // // Log.d("UV", "BY flushing: " + event); // new BabayagaTask(context, event, uvts, eventProps).execute(); // } // // public static void init(Context context) { // prefs = context.getSharedPreferences("uv", 0); // if (prefs.contains("uvts")) { // uvts = prefs.getString("uvts", null); // } // track(context, Event.VIEW_APP); // } // // public static String getUvts() { // return uvts; // } // // }
import android.content.Context; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.uservoice.uservoicesdk.rest.Callback; import com.uservoice.uservoicesdk.rest.RestTaskCallback; import com.uservoice.uservoicesdk.babayaga.Babayaga;
package com.uservoice.uservoicesdk.model; public class Ticket extends BaseModel { public static void createTicket(Context context, String message, Map<String, String> customFields, final Callback<Ticket> callback) { createTicket(context, message, null, null, customFields, callback); } public static void createTicket(Context context, String message, String email, String name, Map<String, String> customFields, final Callback<Ticket> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("ticket[message]", message); if (email != null) params.put("email", email); if (name != null) params.put("display_name", name);
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/babayaga/Babayaga.java // public class Babayaga { // // static String DOMAIN = "by.uservoice.com"; // public static String CHANNEL = "d"; // public static String EXTERNAL_CHANNEL = "x"; // // private static class Track { // public String event; // public Map<String, Object> eventProps; // // public Track(String event, Map<String, Object> eventProps) { // this.event = event; // this.eventProps = eventProps; // } // } // // private static String uvts; // private static SharedPreferences prefs; // // public enum Event { // VIEW_APP("g"), // VIEW_FORUM("m"), // VIEW_TOPIC("c"), // VIEW_KB("k"), // VIEW_CHANNEL("o"), // VIEW_IDEA("i"), // VIEW_ARTICLE("f"), // AUTHENTICATE("u"), // SEARCH_IDEAS("s"), // SEARCH_ARTICLES("r"), // VOTE_IDEA("v"), // VOTE_ARTICLE("z"), // SUBMIT_TICKET("t"), // SUBMIT_IDEA("d"), // SUBSCRIBE_IDEA("b"), // IDENTIFY("y"), // COMMENT_IDEA("h"); // // private final String code; // // private Event(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // } // // public static void setUvts(String uvts) { // Babayaga.uvts = uvts; // Editor edit = prefs.edit(); // edit.putString("uvts", uvts); // edit.commit(); // } // // public static void track(Context context, Event event) { // track(context, event, null); // } // // public static void track(Context context, Event event, String searchText, List<? extends BaseModel> results) { // Map<String, Object> props = new HashMap<String, Object>(); // List<Integer> ids = new ArrayList<Integer>(results.size()); // for (BaseModel model : results) { // ids.add(model.getId()); // } // props.put("ids", ids); // props.put("text", searchText); // track(context, event, props); // } // // public static void track(Context context, Event event, int id) { // Map<String, Object> props = new HashMap<String, Object>(); // props.put("id", id); // track(context, event, props); // } // // public static void track(Context context, Event event, Map<String, Object> eventProps) { // track(context, event.getCode(), eventProps); // } // // public static void track(Context context, String event, Map<String, Object> eventProps) { // // Log.d("UV", "BY flushing: " + event); // new BabayagaTask(context, event, uvts, eventProps).execute(); // } // // public static void init(Context context) { // prefs = context.getSharedPreferences("uv", 0); // if (prefs.contains("uvts")) { // uvts = prefs.getString("uvts", null); // } // track(context, Event.VIEW_APP); // } // // public static String getUvts() { // return uvts; // } // // } // Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/model/Ticket.java import android.content.Context; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.uservoice.uservoicesdk.rest.Callback; import com.uservoice.uservoicesdk.rest.RestTaskCallback; import com.uservoice.uservoicesdk.babayaga.Babayaga; package com.uservoice.uservoicesdk.model; public class Ticket extends BaseModel { public static void createTicket(Context context, String message, Map<String, String> customFields, final Callback<Ticket> callback) { createTicket(context, message, null, null, customFields, callback); } public static void createTicket(Context context, String message, String email, String name, Map<String, String> customFields, final Callback<Ticket> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("ticket[message]", message); if (email != null) params.put("email", email); if (name != null) params.put("display_name", name);
if (Babayaga.getUvts() != null)
uservoice/uservoice-android-sdk
UserVoiceSDK/src/com/uservoice/uservoicesdk/ui/SearchAdapter.java
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/rest/RestTask.java // public class RestTask extends AsyncTask<String, String, RestResult> { // private String urlPath; // private RestMethod method; // private Map<String, String> params; // private RestTaskCallback callback; // private Context context; // // public RestTask(Context context, RestMethod method, String urlPath, Map<String, String> params, RestTaskCallback callback) { // this.context = context.getApplicationContext(); // this.method = method; // this.urlPath = urlPath; // this.callback = callback; // this.params = params; // } // // @Override // protected RestResult doInBackground(String... args) { // try { // Request request = createRequest(); // if (isCancelled()) // throw new InterruptedException(); // OkHttpClient client = new OkHttpClient(); // OAuthConsumer consumer = Session.getInstance().getOAuthConsumer(context); // if (consumer != null) { // AccessToken accessToken = Session.getInstance().getAccessToken(); // if (accessToken != null) { // consumer.setTokenWithSecret(accessToken.getKey(), accessToken.getSecret()); // } // request = (Request) consumer.sign(request).unwrap(); // } // Log.d("UV", urlPath); // if (isCancelled()) // throw new InterruptedException(); // // TODO it would be nice to find a way to abort the request on cancellation // Response response = client.newCall(request).execute(); // if (isCancelled()) // throw new InterruptedException(); // int statusCode = response.code(); // String body = response.body().string(); // if (statusCode >= 400) { // Log.d("UV", body); // } // if (isCancelled()) // throw new InterruptedException(); // return new RestResult(statusCode, new JSONObject(body)); // } catch (Exception e) { // return new RestResult(e); // } // } // // private Request createRequest() throws URISyntaxException, UnsupportedEncodingException { // Request.Builder builder = new Request.Builder() // .addHeader("Accept-Language", Locale.getDefault().getLanguage()) // .addHeader("API-Client", String.format("uservoice-android-%s", UserVoice.getVersion())) // .addHeader("User-Agent", String.format("uservoice-android-%s", UserVoice.getVersion())); // // String host = Session.getInstance().getConfig(context).getSite(); // Uri.Builder uriBuilder = new Uri.Builder(); // uriBuilder.scheme(host.contains(".us.com") ? "http" : "https"); // uriBuilder.encodedAuthority(host); // uriBuilder.path(urlPath); // // if (method == RestMethod.GET || method == RestMethod.DELETE) { // builder.method(method.toString(), null); // addParamsToQueryString(builder, uriBuilder); // } else { // builder.url(uriBuilder.build().toString()); // addParamsToBody(builder); // } // return builder.build(); // } // // @Override // protected void onPostExecute(RestResult result) { // if (result.isError()) { // callback.onError(result); // } else { // try { // callback.onComplete(result.getObject()); // } catch (JSONException e) { // callback.onError(new RestResult(e, result.getStatusCode(), result.getObject())); // } // } // super.onPostExecute(result); // } // // private void addParamsToQueryString(Request.Builder builder, Uri.Builder uriBuilder) throws URISyntaxException { // if (params != null) { // for (Map.Entry<String,String> param : params.entrySet()) { // uriBuilder.appendQueryParameter(param.getKey(), param.getValue()); // } // } // builder.url(uriBuilder.build().toString()); // } // // private void addParamsToBody(Request.Builder builder) throws UnsupportedEncodingException, URISyntaxException { // if (params != null) { // FormBody.Builder paramsBuilder = new FormBody.Builder(); // for (Map.Entry<String,String> param : params.entrySet()) { // if (param.getValue() != null) { // paramsBuilder.add(param.getKey(), param.getValue()); // } // } // builder.method(method.toString(), paramsBuilder.build()); // } // } // // }
import java.util.ArrayList; import java.util.List; import java.util.TimerTask; import android.content.Context; import android.widget.BaseAdapter; import com.uservoice.uservoicesdk.rest.Callback; import com.uservoice.uservoicesdk.rest.RestTask;
protected String pendingQuery; protected int scope; protected SearchTask currentSearch; public void performSearch(String query) { pendingQuery = query; if (query.length() == 0) { searchResults = new ArrayList<T>(); loading = false; notifyDataSetChanged(); } else { loading = true; notifyDataSetChanged(); if (currentSearch != null) { currentSearch.cancel(); } currentSearch = new SearchTask(query); currentSearch.run(); } } public void setSearchActive(boolean searchActive) { this.searchActive = searchActive; loading = false; notifyDataSetChanged(); } private class SearchTask extends TimerTask { private final String query; private boolean stop;
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/rest/RestTask.java // public class RestTask extends AsyncTask<String, String, RestResult> { // private String urlPath; // private RestMethod method; // private Map<String, String> params; // private RestTaskCallback callback; // private Context context; // // public RestTask(Context context, RestMethod method, String urlPath, Map<String, String> params, RestTaskCallback callback) { // this.context = context.getApplicationContext(); // this.method = method; // this.urlPath = urlPath; // this.callback = callback; // this.params = params; // } // // @Override // protected RestResult doInBackground(String... args) { // try { // Request request = createRequest(); // if (isCancelled()) // throw new InterruptedException(); // OkHttpClient client = new OkHttpClient(); // OAuthConsumer consumer = Session.getInstance().getOAuthConsumer(context); // if (consumer != null) { // AccessToken accessToken = Session.getInstance().getAccessToken(); // if (accessToken != null) { // consumer.setTokenWithSecret(accessToken.getKey(), accessToken.getSecret()); // } // request = (Request) consumer.sign(request).unwrap(); // } // Log.d("UV", urlPath); // if (isCancelled()) // throw new InterruptedException(); // // TODO it would be nice to find a way to abort the request on cancellation // Response response = client.newCall(request).execute(); // if (isCancelled()) // throw new InterruptedException(); // int statusCode = response.code(); // String body = response.body().string(); // if (statusCode >= 400) { // Log.d("UV", body); // } // if (isCancelled()) // throw new InterruptedException(); // return new RestResult(statusCode, new JSONObject(body)); // } catch (Exception e) { // return new RestResult(e); // } // } // // private Request createRequest() throws URISyntaxException, UnsupportedEncodingException { // Request.Builder builder = new Request.Builder() // .addHeader("Accept-Language", Locale.getDefault().getLanguage()) // .addHeader("API-Client", String.format("uservoice-android-%s", UserVoice.getVersion())) // .addHeader("User-Agent", String.format("uservoice-android-%s", UserVoice.getVersion())); // // String host = Session.getInstance().getConfig(context).getSite(); // Uri.Builder uriBuilder = new Uri.Builder(); // uriBuilder.scheme(host.contains(".us.com") ? "http" : "https"); // uriBuilder.encodedAuthority(host); // uriBuilder.path(urlPath); // // if (method == RestMethod.GET || method == RestMethod.DELETE) { // builder.method(method.toString(), null); // addParamsToQueryString(builder, uriBuilder); // } else { // builder.url(uriBuilder.build().toString()); // addParamsToBody(builder); // } // return builder.build(); // } // // @Override // protected void onPostExecute(RestResult result) { // if (result.isError()) { // callback.onError(result); // } else { // try { // callback.onComplete(result.getObject()); // } catch (JSONException e) { // callback.onError(new RestResult(e, result.getStatusCode(), result.getObject())); // } // } // super.onPostExecute(result); // } // // private void addParamsToQueryString(Request.Builder builder, Uri.Builder uriBuilder) throws URISyntaxException { // if (params != null) { // for (Map.Entry<String,String> param : params.entrySet()) { // uriBuilder.appendQueryParameter(param.getKey(), param.getValue()); // } // } // builder.url(uriBuilder.build().toString()); // } // // private void addParamsToBody(Request.Builder builder) throws UnsupportedEncodingException, URISyntaxException { // if (params != null) { // FormBody.Builder paramsBuilder = new FormBody.Builder(); // for (Map.Entry<String,String> param : params.entrySet()) { // if (param.getValue() != null) { // paramsBuilder.add(param.getKey(), param.getValue()); // } // } // builder.method(method.toString(), paramsBuilder.build()); // } // } // // } // Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/ui/SearchAdapter.java import java.util.ArrayList; import java.util.List; import java.util.TimerTask; import android.content.Context; import android.widget.BaseAdapter; import com.uservoice.uservoicesdk.rest.Callback; import com.uservoice.uservoicesdk.rest.RestTask; protected String pendingQuery; protected int scope; protected SearchTask currentSearch; public void performSearch(String query) { pendingQuery = query; if (query.length() == 0) { searchResults = new ArrayList<T>(); loading = false; notifyDataSetChanged(); } else { loading = true; notifyDataSetChanged(); if (currentSearch != null) { currentSearch.cancel(); } currentSearch = new SearchTask(query); currentSearch.run(); } } public void setSearchActive(boolean searchActive) { this.searchActive = searchActive; loading = false; notifyDataSetChanged(); } private class SearchTask extends TimerTask { private final String query; private boolean stop;
private RestTask task;
uservoice/uservoice-android-sdk
UserVoiceSDK/src/com/uservoice/uservoicesdk/model/Comment.java
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/babayaga/Babayaga.java // public class Babayaga { // // static String DOMAIN = "by.uservoice.com"; // public static String CHANNEL = "d"; // public static String EXTERNAL_CHANNEL = "x"; // // private static class Track { // public String event; // public Map<String, Object> eventProps; // // public Track(String event, Map<String, Object> eventProps) { // this.event = event; // this.eventProps = eventProps; // } // } // // private static String uvts; // private static SharedPreferences prefs; // // public enum Event { // VIEW_APP("g"), // VIEW_FORUM("m"), // VIEW_TOPIC("c"), // VIEW_KB("k"), // VIEW_CHANNEL("o"), // VIEW_IDEA("i"), // VIEW_ARTICLE("f"), // AUTHENTICATE("u"), // SEARCH_IDEAS("s"), // SEARCH_ARTICLES("r"), // VOTE_IDEA("v"), // VOTE_ARTICLE("z"), // SUBMIT_TICKET("t"), // SUBMIT_IDEA("d"), // SUBSCRIBE_IDEA("b"), // IDENTIFY("y"), // COMMENT_IDEA("h"); // // private final String code; // // private Event(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // } // // public static void setUvts(String uvts) { // Babayaga.uvts = uvts; // Editor edit = prefs.edit(); // edit.putString("uvts", uvts); // edit.commit(); // } // // public static void track(Context context, Event event) { // track(context, event, null); // } // // public static void track(Context context, Event event, String searchText, List<? extends BaseModel> results) { // Map<String, Object> props = new HashMap<String, Object>(); // List<Integer> ids = new ArrayList<Integer>(results.size()); // for (BaseModel model : results) { // ids.add(model.getId()); // } // props.put("ids", ids); // props.put("text", searchText); // track(context, event, props); // } // // public static void track(Context context, Event event, int id) { // Map<String, Object> props = new HashMap<String, Object>(); // props.put("id", id); // track(context, event, props); // } // // public static void track(Context context, Event event, Map<String, Object> eventProps) { // track(context, event.getCode(), eventProps); // } // // public static void track(Context context, String event, Map<String, Object> eventProps) { // // Log.d("UV", "BY flushing: " + event); // new BabayagaTask(context, event, uvts, eventProps).execute(); // } // // public static void init(Context context) { // prefs = context.getSharedPreferences("uv", 0); // if (prefs.contains("uvts")) { // uvts = prefs.getString("uvts", null); // } // track(context, Event.VIEW_APP); // } // // public static String getUvts() { // return uvts; // } // // }
import android.content.Context; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.uservoice.uservoicesdk.babayaga.Babayaga; import com.uservoice.uservoicesdk.rest.Callback; import com.uservoice.uservoicesdk.rest.RestTaskCallback;
package com.uservoice.uservoicesdk.model; public class Comment extends BaseModel { private String text; private String userName; private String avatarUrl; private Date createdAt; public static void loadComments(Context context, Suggestion suggestion, int page, final Callback<List<Comment>> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("page", String.valueOf(page)); doGet(context, apiPath("/forums/%d/suggestions/%d/comments.json", suggestion.getForumId(), suggestion.getId()), params, new RestTaskCallback(callback) { @Override public void onComplete(JSONObject object) throws JSONException { callback.onModel(deserializeList(object, "comments", Comment.class)); } }); } public static void createComment(final Context context, final Suggestion suggestion, String text, final Callback<Comment> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("comment[text]", text); doPost(context, apiPath("/forums/%d/suggestions/%d/comments.json", suggestion.getForumId(), suggestion.getId()), params, new RestTaskCallback(callback) { @Override public void onComplete(JSONObject object) throws JSONException {
// Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/babayaga/Babayaga.java // public class Babayaga { // // static String DOMAIN = "by.uservoice.com"; // public static String CHANNEL = "d"; // public static String EXTERNAL_CHANNEL = "x"; // // private static class Track { // public String event; // public Map<String, Object> eventProps; // // public Track(String event, Map<String, Object> eventProps) { // this.event = event; // this.eventProps = eventProps; // } // } // // private static String uvts; // private static SharedPreferences prefs; // // public enum Event { // VIEW_APP("g"), // VIEW_FORUM("m"), // VIEW_TOPIC("c"), // VIEW_KB("k"), // VIEW_CHANNEL("o"), // VIEW_IDEA("i"), // VIEW_ARTICLE("f"), // AUTHENTICATE("u"), // SEARCH_IDEAS("s"), // SEARCH_ARTICLES("r"), // VOTE_IDEA("v"), // VOTE_ARTICLE("z"), // SUBMIT_TICKET("t"), // SUBMIT_IDEA("d"), // SUBSCRIBE_IDEA("b"), // IDENTIFY("y"), // COMMENT_IDEA("h"); // // private final String code; // // private Event(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // } // // public static void setUvts(String uvts) { // Babayaga.uvts = uvts; // Editor edit = prefs.edit(); // edit.putString("uvts", uvts); // edit.commit(); // } // // public static void track(Context context, Event event) { // track(context, event, null); // } // // public static void track(Context context, Event event, String searchText, List<? extends BaseModel> results) { // Map<String, Object> props = new HashMap<String, Object>(); // List<Integer> ids = new ArrayList<Integer>(results.size()); // for (BaseModel model : results) { // ids.add(model.getId()); // } // props.put("ids", ids); // props.put("text", searchText); // track(context, event, props); // } // // public static void track(Context context, Event event, int id) { // Map<String, Object> props = new HashMap<String, Object>(); // props.put("id", id); // track(context, event, props); // } // // public static void track(Context context, Event event, Map<String, Object> eventProps) { // track(context, event.getCode(), eventProps); // } // // public static void track(Context context, String event, Map<String, Object> eventProps) { // // Log.d("UV", "BY flushing: " + event); // new BabayagaTask(context, event, uvts, eventProps).execute(); // } // // public static void init(Context context) { // prefs = context.getSharedPreferences("uv", 0); // if (prefs.contains("uvts")) { // uvts = prefs.getString("uvts", null); // } // track(context, Event.VIEW_APP); // } // // public static String getUvts() { // return uvts; // } // // } // Path: UserVoiceSDK/src/com/uservoice/uservoicesdk/model/Comment.java import android.content.Context; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.uservoice.uservoicesdk.babayaga.Babayaga; import com.uservoice.uservoicesdk.rest.Callback; import com.uservoice.uservoicesdk.rest.RestTaskCallback; package com.uservoice.uservoicesdk.model; public class Comment extends BaseModel { private String text; private String userName; private String avatarUrl; private Date createdAt; public static void loadComments(Context context, Suggestion suggestion, int page, final Callback<List<Comment>> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("page", String.valueOf(page)); doGet(context, apiPath("/forums/%d/suggestions/%d/comments.json", suggestion.getForumId(), suggestion.getId()), params, new RestTaskCallback(callback) { @Override public void onComplete(JSONObject object) throws JSONException { callback.onModel(deserializeList(object, "comments", Comment.class)); } }); } public static void createComment(final Context context, final Suggestion suggestion, String text, final Callback<Comment> callback) { Map<String, String> params = new HashMap<String, String>(); params.put("comment[text]", text); doPost(context, apiPath("/forums/%d/suggestions/%d/comments.json", suggestion.getForumId(), suggestion.getId()), params, new RestTaskCallback(callback) { @Override public void onComplete(JSONObject object) throws JSONException {
Babayaga.track(context, Babayaga.Event.COMMENT_IDEA, suggestion.getId());
FedericoPecora/coordination_oru
src/main/java/se/oru/coordination/coordination_oru/util/BrowserVisualization.java
// Path: src/main/java/se/oru/coordination/coordination_oru/RobotReport.java // public class RobotReport { // // private Pose pose = null; // private int pathIndex = -1; // private double velocity = 0.0; // private double distanceTraveled = 0.0; // private int criticalPoint = -1; // private int robotID = -1; // // /** // * Create a {@link RobotReport} with given current state of the robot. // * @param pose The current pose of the robot. // * @param pathIndex The index of the last pose passed by the robot. // * @param velocity The current speed of the robot. // * @param distanceTraveled The distance traveled so far along the current current path. // * @param criticalPoint The current active critical point of the robot (-1 if no critical point). // */ // public RobotReport(int robotID, Pose pose, int pathIndex, double velocity, double distanceTraveled, int criticalPoint) { // this.robotID = robotID; // this.pose = pose; // this.velocity = velocity; // this.pathIndex = pathIndex; // this.distanceTraveled = distanceTraveled; // this.criticalPoint = criticalPoint; // } // // /** // * Get the ID of the robot to which this report refers to. // * @return The ID of the robot. // */ // public int getRobotID() { // return this.robotID; // } // // /** // * Get the current pose of the robot. // * @return The current pose of the robot. // */ // public Pose getPose() { // return pose; // } // // /** // * Get the index of the last pose passed by the robot. // * @return The index of the last pose passed by the robot. // */ // public int getPathIndex() { // return pathIndex; // } // // /** // * Get the current speed of the robot. // * @return The current speed of the robot. // */ // public double getVelocity() { // return velocity; // } // // /** // * Get the distance traveled so far along the current current path. // * @return The distance traveled so far along the current current path. // */ // public double getDistanceTraveled() { // return distanceTraveled; // } // // /** // * Get the current active critical point of the robot (-1 if no critical point). // * @return The current active critical point of the robot (-1 if no critical point). // */ // public int getCriticalPoint() { // return criticalPoint; // } // // @Override // public String toString() { // return "Distance: " + MetaCSPLogging.printDouble(this.distanceTraveled,4) + " Pose: " + this.pose + " Index: " + this.pathIndex + " Velocity: " + MetaCSPLogging.printDouble(velocity,4); // } // // }
import java.awt.Desktop; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import javax.imageio.ImageIO; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.websocket.api.RemoteEndpoint; import org.metacsp.multi.spatial.DE9IM.GeometricShapeDomain; import org.metacsp.multi.spatioTemporal.paths.Pose; import org.metacsp.multi.spatioTemporal.paths.TrajectoryEnvelope; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.geom.util.AffineTransformation; import se.oru.coordination.coordination_oru.RobotReport;
this.msgQueue.add(message); } } } private void sendMessages() { if (BrowserVisualizationSocket.ENDPOINTS != null && BrowserVisualizationSocket.ENDPOINTS.size() > 0) { synchronized (BrowserVisualizationSocket.ENDPOINTS) { for (String message : this.msgQueue) { sendMessage(message); } msgQueue.clear(); updateOverlayText(); sendUpdate(); } } } private void sendMessage(String text) { if (BrowserVisualizationSocket.ENDPOINTS != null) { for (RemoteEndpoint rep : BrowserVisualizationSocket.ENDPOINTS) { try { rep.sendString(text); } catch(IOException e) { e.printStackTrace(); } } } } @Override
// Path: src/main/java/se/oru/coordination/coordination_oru/RobotReport.java // public class RobotReport { // // private Pose pose = null; // private int pathIndex = -1; // private double velocity = 0.0; // private double distanceTraveled = 0.0; // private int criticalPoint = -1; // private int robotID = -1; // // /** // * Create a {@link RobotReport} with given current state of the robot. // * @param pose The current pose of the robot. // * @param pathIndex The index of the last pose passed by the robot. // * @param velocity The current speed of the robot. // * @param distanceTraveled The distance traveled so far along the current current path. // * @param criticalPoint The current active critical point of the robot (-1 if no critical point). // */ // public RobotReport(int robotID, Pose pose, int pathIndex, double velocity, double distanceTraveled, int criticalPoint) { // this.robotID = robotID; // this.pose = pose; // this.velocity = velocity; // this.pathIndex = pathIndex; // this.distanceTraveled = distanceTraveled; // this.criticalPoint = criticalPoint; // } // // /** // * Get the ID of the robot to which this report refers to. // * @return The ID of the robot. // */ // public int getRobotID() { // return this.robotID; // } // // /** // * Get the current pose of the robot. // * @return The current pose of the robot. // */ // public Pose getPose() { // return pose; // } // // /** // * Get the index of the last pose passed by the robot. // * @return The index of the last pose passed by the robot. // */ // public int getPathIndex() { // return pathIndex; // } // // /** // * Get the current speed of the robot. // * @return The current speed of the robot. // */ // public double getVelocity() { // return velocity; // } // // /** // * Get the distance traveled so far along the current current path. // * @return The distance traveled so far along the current current path. // */ // public double getDistanceTraveled() { // return distanceTraveled; // } // // /** // * Get the current active critical point of the robot (-1 if no critical point). // * @return The current active critical point of the robot (-1 if no critical point). // */ // public int getCriticalPoint() { // return criticalPoint; // } // // @Override // public String toString() { // return "Distance: " + MetaCSPLogging.printDouble(this.distanceTraveled,4) + " Pose: " + this.pose + " Index: " + this.pathIndex + " Velocity: " + MetaCSPLogging.printDouble(velocity,4); // } // // } // Path: src/main/java/se/oru/coordination/coordination_oru/util/BrowserVisualization.java import java.awt.Desktop; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import javax.imageio.ImageIO; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.websocket.api.RemoteEndpoint; import org.metacsp.multi.spatial.DE9IM.GeometricShapeDomain; import org.metacsp.multi.spatioTemporal.paths.Pose; import org.metacsp.multi.spatioTemporal.paths.TrajectoryEnvelope; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.geom.util.AffineTransformation; import se.oru.coordination.coordination_oru.RobotReport; this.msgQueue.add(message); } } } private void sendMessages() { if (BrowserVisualizationSocket.ENDPOINTS != null && BrowserVisualizationSocket.ENDPOINTS.size() > 0) { synchronized (BrowserVisualizationSocket.ENDPOINTS) { for (String message : this.msgQueue) { sendMessage(message); } msgQueue.clear(); updateOverlayText(); sendUpdate(); } } } private void sendMessage(String text) { if (BrowserVisualizationSocket.ENDPOINTS != null) { for (RemoteEndpoint rep : BrowserVisualizationSocket.ENDPOINTS) { try { rep.sendString(text); } catch(IOException e) { e.printStackTrace(); } } } } @Override
public void displayRobotState(TrajectoryEnvelope te, RobotReport rr, String... extraStatusInfo) {
OpenNTF/DomSQL
domsql/eclipse/plugins/com.ibm.domino.domsql.sqlite/src/com/ibm/domino/domsql/sqlite/driver/Context.java
// Path: domsql/eclipse/plugins/com.ibm.domino.domsql.sqlite/src/com/ibm/domino/domsql/sqlite/DomSQLException.java // public class DomSQLException { // // public static SQLException create(Throwable t, String message) { // SQLException e = new SQLException(message); // if(t!=null) { // e.initCause(t); // } // return e; // } // // public static SQLException create(Throwable t, String message, Object... params) { // SQLException e = new SQLException(StringUtil.format(message, params)); // if(t!=null) { // e.initCause(t); // } // return e; // } // // public static void setSqliteCode(SQLException exception, int sqliteCode) { // //this.sqliteCode = sqliteCode; // } // } // // Path: domsql/eclipse/plugins/com.ibm.domino.domsql.sqlite/src/com/ibm/domino/domsql/sqlite/driver/jni/NotesAPI.java // public class NotesAPI { // // public static final int READ_MASK_NOTEID = 0x00000001; // public static final int READ_MASK_NOTEUNID = 0x00000002; // public static final int READ_MASK_NOTECLASS = 0x00000004; // public static final int READ_MASK_INDEXSIBLINGS = 0x00000008; // public static final int READ_MASK_INDEXCHILDREN = 0x00000010; // public static final int READ_MASK_INDEXDESCENDANTS = 0x00000020; // public static final int READ_MASK_INDEXANYUNREAD = 0x00000040; // public static final int READ_MASK_INDENTLEVELS = 0x00000080; // public static final int READ_MASK_SCORE = 0x00000200; // public static final int READ_MASK_INDEXUNREAD = 0x00000400; // public static final int READ_MASK_COLLECTIONSTATS = 0x00000100; // public static final int READ_MASK_INDEXPOSITION = 0x00004000; // public static final int READ_MASK_SUMMARYVALUES = 0x00002000; // public static final int READ_MASK_SUMMARY = 0x00008000; // // // /////////////////////////////////////////////////////////// // // Notes initialization routines // // For standalone apps // /////////////////////////////////////////////////////////// // public static native void NotesInit() throws SQLException; // public static native void NotesTerm() throws SQLException; // public static native void NotesInitThread() throws SQLException; // public static native void NotesTermThread() throws SQLException; // // /////////////////////////////////////////////////////////// // // Access to notes.ini // /////////////////////////////////////////////////////////// // public static final native int OSGetEnvironmentInt(String name) throws SQLException; // public static final native long OSGetEnvironmentLong(String name) throws SQLException; // public static final native String OSGetEnvironmentString(String name) throws SQLException; // public static final native void OSSetEnvironmentInt(String name, int value) throws SQLException; // public static final native void OSSetEnvironmentVariable(String name, String value) throws SQLException; // // // /////////////////////////////////////////////////////////// // // Database routines // /////////////////////////////////////////////////////////// // public static native long NSFDBOpen(String dbPath) throws SQLException; // public static native long NSFDBOpenEx(String dbPath, long hNames) throws SQLException; // public static native void NSFDBClose(long hDb) throws SQLException; // public static native long NSFDbNonDataModifiedTime(long hDb) throws SQLException; // // /////////////////////////////////////////////////////////// // // Note routines // /////////////////////////////////////////////////////////// // public static native long NSFNoteOpen(long hDb, int noteID, int flags) throws SQLException; // public static native void NSFNoteClose(long hNote) throws SQLException; // // /////////////////////////////////////////////////////////// // // View routines // /////////////////////////////////////////////////////////// // public static native int NIFFindView(long hDb, String viewName) throws SQLException; // // /////////////////////////////////////////////////////////// // // KFM // /////////////////////////////////////////////////////////// // public static native String SECKFMGetUserName() throws SQLException; // }
import java.sql.SQLException; import java.util.HashMap; import com.ibm.domino.domsql.sqlite.DomSQLException; import com.ibm.domino.domsql.sqlite.driver.jni.NotesAPI;
Context c = contexts.get(); if(c!=null) { return c; } for(ContextFinder f=contextFinder; f!=null; f=f.next) { c = f.find(); if(c!=null) { return c; } } throw new IllegalStateException("No current DomSQL context set"); } public static void push(Context context) { contexts.set(context); } public static void pop() { contexts.remove(); } private HashMap<String, Long> handles = new HashMap<String, Long>(); public Context() { } public synchronized void close() { for(Long hDb: handles.values()) { try { if(shouldClose(hDb)) {
// Path: domsql/eclipse/plugins/com.ibm.domino.domsql.sqlite/src/com/ibm/domino/domsql/sqlite/DomSQLException.java // public class DomSQLException { // // public static SQLException create(Throwable t, String message) { // SQLException e = new SQLException(message); // if(t!=null) { // e.initCause(t); // } // return e; // } // // public static SQLException create(Throwable t, String message, Object... params) { // SQLException e = new SQLException(StringUtil.format(message, params)); // if(t!=null) { // e.initCause(t); // } // return e; // } // // public static void setSqliteCode(SQLException exception, int sqliteCode) { // //this.sqliteCode = sqliteCode; // } // } // // Path: domsql/eclipse/plugins/com.ibm.domino.domsql.sqlite/src/com/ibm/domino/domsql/sqlite/driver/jni/NotesAPI.java // public class NotesAPI { // // public static final int READ_MASK_NOTEID = 0x00000001; // public static final int READ_MASK_NOTEUNID = 0x00000002; // public static final int READ_MASK_NOTECLASS = 0x00000004; // public static final int READ_MASK_INDEXSIBLINGS = 0x00000008; // public static final int READ_MASK_INDEXCHILDREN = 0x00000010; // public static final int READ_MASK_INDEXDESCENDANTS = 0x00000020; // public static final int READ_MASK_INDEXANYUNREAD = 0x00000040; // public static final int READ_MASK_INDENTLEVELS = 0x00000080; // public static final int READ_MASK_SCORE = 0x00000200; // public static final int READ_MASK_INDEXUNREAD = 0x00000400; // public static final int READ_MASK_COLLECTIONSTATS = 0x00000100; // public static final int READ_MASK_INDEXPOSITION = 0x00004000; // public static final int READ_MASK_SUMMARYVALUES = 0x00002000; // public static final int READ_MASK_SUMMARY = 0x00008000; // // // /////////////////////////////////////////////////////////// // // Notes initialization routines // // For standalone apps // /////////////////////////////////////////////////////////// // public static native void NotesInit() throws SQLException; // public static native void NotesTerm() throws SQLException; // public static native void NotesInitThread() throws SQLException; // public static native void NotesTermThread() throws SQLException; // // /////////////////////////////////////////////////////////// // // Access to notes.ini // /////////////////////////////////////////////////////////// // public static final native int OSGetEnvironmentInt(String name) throws SQLException; // public static final native long OSGetEnvironmentLong(String name) throws SQLException; // public static final native String OSGetEnvironmentString(String name) throws SQLException; // public static final native void OSSetEnvironmentInt(String name, int value) throws SQLException; // public static final native void OSSetEnvironmentVariable(String name, String value) throws SQLException; // // // /////////////////////////////////////////////////////////// // // Database routines // /////////////////////////////////////////////////////////// // public static native long NSFDBOpen(String dbPath) throws SQLException; // public static native long NSFDBOpenEx(String dbPath, long hNames) throws SQLException; // public static native void NSFDBClose(long hDb) throws SQLException; // public static native long NSFDbNonDataModifiedTime(long hDb) throws SQLException; // // /////////////////////////////////////////////////////////// // // Note routines // /////////////////////////////////////////////////////////// // public static native long NSFNoteOpen(long hDb, int noteID, int flags) throws SQLException; // public static native void NSFNoteClose(long hNote) throws SQLException; // // /////////////////////////////////////////////////////////// // // View routines // /////////////////////////////////////////////////////////// // public static native int NIFFindView(long hDb, String viewName) throws SQLException; // // /////////////////////////////////////////////////////////// // // KFM // /////////////////////////////////////////////////////////// // public static native String SECKFMGetUserName() throws SQLException; // } // Path: domsql/eclipse/plugins/com.ibm.domino.domsql.sqlite/src/com/ibm/domino/domsql/sqlite/driver/Context.java import java.sql.SQLException; import java.util.HashMap; import com.ibm.domino.domsql.sqlite.DomSQLException; import com.ibm.domino.domsql.sqlite.driver.jni.NotesAPI; Context c = contexts.get(); if(c!=null) { return c; } for(ContextFinder f=contextFinder; f!=null; f=f.next) { c = f.find(); if(c!=null) { return c; } } throw new IllegalStateException("No current DomSQL context set"); } public static void push(Context context) { contexts.set(context); } public static void pop() { contexts.remove(); } private HashMap<String, Long> handles = new HashMap<String, Long>(); public Context() { } public synchronized void close() { for(Long hDb: handles.values()) { try { if(shouldClose(hDb)) {
NotesAPI.NSFDBClose(hDb);