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
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/logging/ExceptionLogger.java
// Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // }
import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.slf4j.Logger; import static com.github.mkopylec.errorest.logging.LoggingLevel.DEBUG; import static com.github.mkopylec.errorest.logging.LoggingLevel.ERROR; import static com.github.mkopylec.errorest.logging.LoggingLevel.INFO; import static com.github.mkopylec.errorest.logging.LoggingLevel.TRACE; import static com.github.mkopylec.errorest.logging.LoggingLevel.WARN; import static org.slf4j.LoggerFactory.getLogger;
package com.github.mkopylec.errorest.logging; public class ExceptionLogger { private static final Logger log = getLogger(ExceptionLogger.class);
// Path: src/main/java/com/github/mkopylec/errorest/handling/errordata/ErrorData.java // public class ErrorData { // // public static final int ERRORS_ID_LENGTH = 10; // // protected final String id; // protected final LoggingLevel loggingLevel; // protected final String requestMethod; // protected final String requestUri; // protected final HttpStatus responseStatus; // protected final List<Error> errors; // protected final Throwable throwable; // // protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) { // this.id = id; // this.loggingLevel = loggingLevel; // this.requestMethod = requestMethod; // this.requestUri = requestUri; // this.responseStatus = responseStatus; // this.errors = errors; // this.throwable = throwable; // } // // public String getId() { // return id; // } // // public LoggingLevel getLoggingLevel() { // return loggingLevel; // } // // public boolean hasLoggingLevel(LoggingLevel level) { // return loggingLevel == level; // } // // public String getRequestMethod() { // return requestMethod; // } // // public String getRequestUri() { // return requestUri; // } // // public HttpStatus getResponseStatus() { // return responseStatus; // } // // public List<Error> getErrors() { // return errors; // } // // public Throwable getThrowable() { // return throwable; // } // // public static final class ErrorDataBuilder { // // protected String id; // protected LoggingLevel loggingLevel; // protected String requestMethod; // protected String requestUri; // protected HttpStatus responseStatus; // protected List<Error> errors = new ErrorsLoggingList(); // protected Throwable throwable; // // private ErrorDataBuilder() { // id = randomAlphanumeric(ERRORS_ID_LENGTH).toLowerCase(); // } // // public static ErrorDataBuilder newErrorData() { // return new ErrorDataBuilder(); // } // // public ErrorDataBuilder withLoggingLevel(LoggingLevel loggingLevel) { // this.loggingLevel = loggingLevel; // return this; // } // // public ErrorDataBuilder withRequestMethod(String requestMethod) { // this.requestMethod = requestMethod; // return this; // } // // public ErrorDataBuilder withRequestUri(String requestUri) { // this.requestUri = requestUri; // return this; // } // // public ErrorDataBuilder withResponseStatus(HttpStatus responseStatus) { // this.responseStatus = responseStatus; // return this; // } // // public ErrorDataBuilder addError(Error error) { // errors.add(error); // return this; // } // // public ErrorDataBuilder withThrowable(Throwable throwable) { // this.throwable = throwable; // return this; // } // // public ErrorData build() { // return new ErrorData(id, loggingLevel, requestMethod, requestUri, responseStatus, errors, throwable); // } // } // } // Path: src/main/java/com/github/mkopylec/errorest/logging/ExceptionLogger.java import com.github.mkopylec.errorest.handling.errordata.ErrorData; import org.slf4j.Logger; import static com.github.mkopylec.errorest.logging.LoggingLevel.DEBUG; import static com.github.mkopylec.errorest.logging.LoggingLevel.ERROR; import static com.github.mkopylec.errorest.logging.LoggingLevel.INFO; import static com.github.mkopylec.errorest.logging.LoggingLevel.TRACE; import static com.github.mkopylec.errorest.logging.LoggingLevel.WARN; import static org.slf4j.LoggerFactory.getLogger; package com.github.mkopylec.errorest.logging; public class ExceptionLogger { private static final Logger log = getLogger(ExceptionLogger.class);
public void log(ErrorData errorData) {
brenthub/brent-pusher
brent-pusher-core/src/main/java/cn/brent/pusher/plugin/CleanUpPlugin.java
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/IPlugin.java // public interface IPlugin { // // void start(); // // void stop(); // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/IPusherClient.java // public interface IPusherClient { // // /** // * 正常关闭 // */ // public static final int NORMAL = 1000; // // /** // * 服务器拒绝 // */ // public static final int REFUSE = 1003; // // // /** // * 关闭连接 // * @param code 状态码 // * @param reason 原因 // */ // void close(int code,String reason); // // /** // * 获取属性值 // * @param key // * @return // */ // Object getAttr(String key); // // /** // * 新增属性值 // * @param key // * @param val // */ // void addAttr(String key, Object val); // // /** // * 移除属性值 // * @param key // */ // void removeAttr(String key); // // /** // * 获取key // * @return // */ // String getKey(); // // /** // * 获取Topic // * @return // */ // String getTopic(); // // /** // * 保存key // * @param key // */ // void setKey(String key); // // /** // * 保存Topic // * @param topic // */ // void setTopic(String topic); // // /** // * 获取创建时间 // * @return // */ // long getCreateTime(); // // /** // * 发送消息 // * @param message // */ // void send(String message); // // /** // * 发送消息 // * @param message // * @param close 发送成功后是否关闭连接 // */ // void send(String message,boolean close); // // // /** // * 获取超时时间 // * @return // */ // Long getTimeOut(); // // /** // * 设置超时时间 // */ // void setTimeOut(Long timeout); // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/session/ISessionManager.java // public interface ISessionManager { // // /** 连接队列 */ // final List<IPusherClient> clientQueue = new CopyOnWriteArrayList<IPusherClient>(); // // /** // * 保存client // * @param client // */ // void saveConnect(IPusherClient client); // // /** // * 移除client // * @param client // */ // void removeConnect(IPusherClient client); // // /** // * 根据业务编码和key获取Session // * @param topic // * @param key // * @return // */ // Session getSession(String topic, String key); // // /** // * 移除Session // * @param topic // * @param key // */ // void removeSession(String topic, String key); // // /** // * 移除Session // * @param Session // */ // void removeSession(Session session); // // }
import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.brent.pusher.IPlugin; import cn.brent.pusher.core.IPusherClient; import cn.brent.pusher.session.ISessionManager;
package cn.brent.pusher.plugin; public class CleanUpPlugin implements IPlugin { protected Logger logger = LoggerFactory.getLogger(this.getClass()); protected Thread cleanUpThead; /** 超时时间 毫秒 为空时永不超时*/ protected final Long timeout; /** 检查间隔 毫秒 */ protected final long checkInterval; public CleanUpPlugin(Long timeout, long checkInterval) { this.timeout = timeout; this.checkInterval = checkInterval; } /** * 清扫任务 * * @param timeout * @param checkInterval * @param handler */ protected void cleanUp() { logger.debug("start cleanUp..."); long startTime = System.currentTimeMillis();
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/IPlugin.java // public interface IPlugin { // // void start(); // // void stop(); // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/IPusherClient.java // public interface IPusherClient { // // /** // * 正常关闭 // */ // public static final int NORMAL = 1000; // // /** // * 服务器拒绝 // */ // public static final int REFUSE = 1003; // // // /** // * 关闭连接 // * @param code 状态码 // * @param reason 原因 // */ // void close(int code,String reason); // // /** // * 获取属性值 // * @param key // * @return // */ // Object getAttr(String key); // // /** // * 新增属性值 // * @param key // * @param val // */ // void addAttr(String key, Object val); // // /** // * 移除属性值 // * @param key // */ // void removeAttr(String key); // // /** // * 获取key // * @return // */ // String getKey(); // // /** // * 获取Topic // * @return // */ // String getTopic(); // // /** // * 保存key // * @param key // */ // void setKey(String key); // // /** // * 保存Topic // * @param topic // */ // void setTopic(String topic); // // /** // * 获取创建时间 // * @return // */ // long getCreateTime(); // // /** // * 发送消息 // * @param message // */ // void send(String message); // // /** // * 发送消息 // * @param message // * @param close 发送成功后是否关闭连接 // */ // void send(String message,boolean close); // // // /** // * 获取超时时间 // * @return // */ // Long getTimeOut(); // // /** // * 设置超时时间 // */ // void setTimeOut(Long timeout); // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/session/ISessionManager.java // public interface ISessionManager { // // /** 连接队列 */ // final List<IPusherClient> clientQueue = new CopyOnWriteArrayList<IPusherClient>(); // // /** // * 保存client // * @param client // */ // void saveConnect(IPusherClient client); // // /** // * 移除client // * @param client // */ // void removeConnect(IPusherClient client); // // /** // * 根据业务编码和key获取Session // * @param topic // * @param key // * @return // */ // Session getSession(String topic, String key); // // /** // * 移除Session // * @param topic // * @param key // */ // void removeSession(String topic, String key); // // /** // * 移除Session // * @param Session // */ // void removeSession(Session session); // // } // Path: brent-pusher-core/src/main/java/cn/brent/pusher/plugin/CleanUpPlugin.java import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.brent.pusher.IPlugin; import cn.brent.pusher.core.IPusherClient; import cn.brent.pusher.session.ISessionManager; package cn.brent.pusher.plugin; public class CleanUpPlugin implements IPlugin { protected Logger logger = LoggerFactory.getLogger(this.getClass()); protected Thread cleanUpThead; /** 超时时间 毫秒 为空时永不超时*/ protected final Long timeout; /** 检查间隔 毫秒 */ protected final long checkInterval; public CleanUpPlugin(Long timeout, long checkInterval) { this.timeout = timeout; this.checkInterval = checkInterval; } /** * 清扫任务 * * @param timeout * @param checkInterval * @param handler */ protected void cleanUp() { logger.debug("start cleanUp..."); long startTime = System.currentTimeMillis();
Iterator<IPusherClient> it = ISessionManager.clientQueue.iterator();
brenthub/brent-pusher
brent-pusher-core/src/main/java/cn/brent/pusher/plugin/CleanUpPlugin.java
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/IPlugin.java // public interface IPlugin { // // void start(); // // void stop(); // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/IPusherClient.java // public interface IPusherClient { // // /** // * 正常关闭 // */ // public static final int NORMAL = 1000; // // /** // * 服务器拒绝 // */ // public static final int REFUSE = 1003; // // // /** // * 关闭连接 // * @param code 状态码 // * @param reason 原因 // */ // void close(int code,String reason); // // /** // * 获取属性值 // * @param key // * @return // */ // Object getAttr(String key); // // /** // * 新增属性值 // * @param key // * @param val // */ // void addAttr(String key, Object val); // // /** // * 移除属性值 // * @param key // */ // void removeAttr(String key); // // /** // * 获取key // * @return // */ // String getKey(); // // /** // * 获取Topic // * @return // */ // String getTopic(); // // /** // * 保存key // * @param key // */ // void setKey(String key); // // /** // * 保存Topic // * @param topic // */ // void setTopic(String topic); // // /** // * 获取创建时间 // * @return // */ // long getCreateTime(); // // /** // * 发送消息 // * @param message // */ // void send(String message); // // /** // * 发送消息 // * @param message // * @param close 发送成功后是否关闭连接 // */ // void send(String message,boolean close); // // // /** // * 获取超时时间 // * @return // */ // Long getTimeOut(); // // /** // * 设置超时时间 // */ // void setTimeOut(Long timeout); // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/session/ISessionManager.java // public interface ISessionManager { // // /** 连接队列 */ // final List<IPusherClient> clientQueue = new CopyOnWriteArrayList<IPusherClient>(); // // /** // * 保存client // * @param client // */ // void saveConnect(IPusherClient client); // // /** // * 移除client // * @param client // */ // void removeConnect(IPusherClient client); // // /** // * 根据业务编码和key获取Session // * @param topic // * @param key // * @return // */ // Session getSession(String topic, String key); // // /** // * 移除Session // * @param topic // * @param key // */ // void removeSession(String topic, String key); // // /** // * 移除Session // * @param Session // */ // void removeSession(Session session); // // }
import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.brent.pusher.IPlugin; import cn.brent.pusher.core.IPusherClient; import cn.brent.pusher.session.ISessionManager;
package cn.brent.pusher.plugin; public class CleanUpPlugin implements IPlugin { protected Logger logger = LoggerFactory.getLogger(this.getClass()); protected Thread cleanUpThead; /** 超时时间 毫秒 为空时永不超时*/ protected final Long timeout; /** 检查间隔 毫秒 */ protected final long checkInterval; public CleanUpPlugin(Long timeout, long checkInterval) { this.timeout = timeout; this.checkInterval = checkInterval; } /** * 清扫任务 * * @param timeout * @param checkInterval * @param handler */ protected void cleanUp() { logger.debug("start cleanUp..."); long startTime = System.currentTimeMillis();
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/IPlugin.java // public interface IPlugin { // // void start(); // // void stop(); // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/IPusherClient.java // public interface IPusherClient { // // /** // * 正常关闭 // */ // public static final int NORMAL = 1000; // // /** // * 服务器拒绝 // */ // public static final int REFUSE = 1003; // // // /** // * 关闭连接 // * @param code 状态码 // * @param reason 原因 // */ // void close(int code,String reason); // // /** // * 获取属性值 // * @param key // * @return // */ // Object getAttr(String key); // // /** // * 新增属性值 // * @param key // * @param val // */ // void addAttr(String key, Object val); // // /** // * 移除属性值 // * @param key // */ // void removeAttr(String key); // // /** // * 获取key // * @return // */ // String getKey(); // // /** // * 获取Topic // * @return // */ // String getTopic(); // // /** // * 保存key // * @param key // */ // void setKey(String key); // // /** // * 保存Topic // * @param topic // */ // void setTopic(String topic); // // /** // * 获取创建时间 // * @return // */ // long getCreateTime(); // // /** // * 发送消息 // * @param message // */ // void send(String message); // // /** // * 发送消息 // * @param message // * @param close 发送成功后是否关闭连接 // */ // void send(String message,boolean close); // // // /** // * 获取超时时间 // * @return // */ // Long getTimeOut(); // // /** // * 设置超时时间 // */ // void setTimeOut(Long timeout); // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/session/ISessionManager.java // public interface ISessionManager { // // /** 连接队列 */ // final List<IPusherClient> clientQueue = new CopyOnWriteArrayList<IPusherClient>(); // // /** // * 保存client // * @param client // */ // void saveConnect(IPusherClient client); // // /** // * 移除client // * @param client // */ // void removeConnect(IPusherClient client); // // /** // * 根据业务编码和key获取Session // * @param topic // * @param key // * @return // */ // Session getSession(String topic, String key); // // /** // * 移除Session // * @param topic // * @param key // */ // void removeSession(String topic, String key); // // /** // * 移除Session // * @param Session // */ // void removeSession(Session session); // // } // Path: brent-pusher-core/src/main/java/cn/brent/pusher/plugin/CleanUpPlugin.java import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.brent.pusher.IPlugin; import cn.brent.pusher.core.IPusherClient; import cn.brent.pusher.session.ISessionManager; package cn.brent.pusher.plugin; public class CleanUpPlugin implements IPlugin { protected Logger logger = LoggerFactory.getLogger(this.getClass()); protected Thread cleanUpThead; /** 超时时间 毫秒 为空时永不超时*/ protected final Long timeout; /** 检查间隔 毫秒 */ protected final long checkInterval; public CleanUpPlugin(Long timeout, long checkInterval) { this.timeout = timeout; this.checkInterval = checkInterval; } /** * 清扫任务 * * @param timeout * @param checkInterval * @param handler */ protected void cleanUp() { logger.debug("start cleanUp..."); long startTime = System.currentTimeMillis();
Iterator<IPusherClient> it = ISessionManager.clientQueue.iterator();
brenthub/brent-pusher
brent-pusher-core/src/main/java/cn/brent/pusher/verifier/SignVerifier.java
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/IVerifier.java // public interface IVerifier { // // /** // * 认证 成功true // * @param path // * @return // */ // boolean verify(PathDesc path,Session session); // // /** // * 当认证失败返回的异常信息 // * @return // */ // String failMsg(PathDesc path); // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/PathDesc.java // public class PathDesc { // // private String topic; // // private String key; // // private String sign; // // /** 超时时间,超时间为空时,为默认超时时间 */ // private Long timeOut; // // private PathDesc() { // } // // public static PathDesc parse(String pathDesc) { // try { // PathDesc desc = new PathDesc(); // String t[] = pathDesc.split("\\?"); // String path = t[0]; // desc.key = path.substring(path.lastIndexOf("/") + 1); // desc.topic = path.substring(1, path.lastIndexOf("/")); // // if(t.length==1){ // return desc; // } // String params = t[1]; // String param[] = params.split("&"); // for (String pa : param) { // if (pa.startsWith("sign=")) { // desc.sign = pa.substring(pa.indexOf("=") + 1); // continue; // } // if (pa.startsWith("timeout=")) { // desc.timeOut = Long.parseLong(pa.substring(pa.indexOf("=") + 1)); // continue; // } // } // return desc; // } catch (Exception e) { // e.printStackTrace(); // throw new RuntimeException("request path illegal"); // } // } // // public static void main(String[] args) { // PathDesc pd = PathDesc.parse("/order/2343423234?timeout=23&sign=34"); // System.out.println(pd.toString()); // } // // public String getTopic() { // return topic; // } // // public String getKey() { // return key; // } // // public String getSign() { // return sign; // } // // public Long getTimeOut() { // return timeOut; // } // // public void setTimeOut(Long timeOut) { // this.timeOut = timeOut; // } // // @Override // public String toString() { // return JSON.toJSON(this).toString(); // } // // }
import cn.brent.pusher.IVerifier; import cn.brent.pusher.core.PathDesc;
package cn.brent.pusher.verifier; public abstract class SignVerifier implements IVerifier { @Override
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/IVerifier.java // public interface IVerifier { // // /** // * 认证 成功true // * @param path // * @return // */ // boolean verify(PathDesc path,Session session); // // /** // * 当认证失败返回的异常信息 // * @return // */ // String failMsg(PathDesc path); // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/PathDesc.java // public class PathDesc { // // private String topic; // // private String key; // // private String sign; // // /** 超时时间,超时间为空时,为默认超时时间 */ // private Long timeOut; // // private PathDesc() { // } // // public static PathDesc parse(String pathDesc) { // try { // PathDesc desc = new PathDesc(); // String t[] = pathDesc.split("\\?"); // String path = t[0]; // desc.key = path.substring(path.lastIndexOf("/") + 1); // desc.topic = path.substring(1, path.lastIndexOf("/")); // // if(t.length==1){ // return desc; // } // String params = t[1]; // String param[] = params.split("&"); // for (String pa : param) { // if (pa.startsWith("sign=")) { // desc.sign = pa.substring(pa.indexOf("=") + 1); // continue; // } // if (pa.startsWith("timeout=")) { // desc.timeOut = Long.parseLong(pa.substring(pa.indexOf("=") + 1)); // continue; // } // } // return desc; // } catch (Exception e) { // e.printStackTrace(); // throw new RuntimeException("request path illegal"); // } // } // // public static void main(String[] args) { // PathDesc pd = PathDesc.parse("/order/2343423234?timeout=23&sign=34"); // System.out.println(pd.toString()); // } // // public String getTopic() { // return topic; // } // // public String getKey() { // return key; // } // // public String getSign() { // return sign; // } // // public Long getTimeOut() { // return timeOut; // } // // public void setTimeOut(Long timeOut) { // this.timeOut = timeOut; // } // // @Override // public String toString() { // return JSON.toJSON(this).toString(); // } // // } // Path: brent-pusher-core/src/main/java/cn/brent/pusher/verifier/SignVerifier.java import cn.brent.pusher.IVerifier; import cn.brent.pusher.core.PathDesc; package cn.brent.pusher.verifier; public abstract class SignVerifier implements IVerifier { @Override
public String failMsg(PathDesc path) {
brenthub/brent-pusher
brent-pusher-core/src/main/java/cn/brent/pusher/plugin/MonitorPlugin.java
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/IPlugin.java // public interface IPlugin { // // void start(); // // void stop(); // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/session/ISessionManager.java // public interface ISessionManager { // // /** 连接队列 */ // final List<IPusherClient> clientQueue = new CopyOnWriteArrayList<IPusherClient>(); // // /** // * 保存client // * @param client // */ // void saveConnect(IPusherClient client); // // /** // * 移除client // * @param client // */ // void removeConnect(IPusherClient client); // // /** // * 根据业务编码和key获取Session // * @param topic // * @param key // * @return // */ // Session getSession(String topic, String key); // // /** // * 移除Session // * @param topic // * @param key // */ // void removeSession(String topic, String key); // // /** // * 移除Session // * @param Session // */ // void removeSession(Session session); // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.brent.pusher.IPlugin; import cn.brent.pusher.session.ISessionManager;
package cn.brent.pusher.plugin; public class MonitorPlugin implements IPlugin { protected Logger logger = LoggerFactory.getLogger("monitor"); protected Thread monitorThread; /** 监控扫描间隔 单位毫秒 默认5分钟 */ protected long monitorInterval = 5 * 60 * 1000; public MonitorPlugin(long monitorInterval) { this.monitorInterval = monitorInterval; } protected void log() {
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/IPlugin.java // public interface IPlugin { // // void start(); // // void stop(); // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/session/ISessionManager.java // public interface ISessionManager { // // /** 连接队列 */ // final List<IPusherClient> clientQueue = new CopyOnWriteArrayList<IPusherClient>(); // // /** // * 保存client // * @param client // */ // void saveConnect(IPusherClient client); // // /** // * 移除client // * @param client // */ // void removeConnect(IPusherClient client); // // /** // * 根据业务编码和key获取Session // * @param topic // * @param key // * @return // */ // Session getSession(String topic, String key); // // /** // * 移除Session // * @param topic // * @param key // */ // void removeSession(String topic, String key); // // /** // * 移除Session // * @param Session // */ // void removeSession(Session session); // // } // Path: brent-pusher-core/src/main/java/cn/brent/pusher/plugin/MonitorPlugin.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.brent.pusher.IPlugin; import cn.brent.pusher.session.ISessionManager; package cn.brent.pusher.plugin; public class MonitorPlugin implements IPlugin { protected Logger logger = LoggerFactory.getLogger("monitor"); protected Thread monitorThread; /** 监控扫描间隔 单位毫秒 默认5分钟 */ protected long monitorInterval = 5 * 60 * 1000; public MonitorPlugin(long monitorInterval) { this.monitorInterval = monitorInterval; } protected void log() {
logger.info(ISessionManager.clientQueue.size()+"");
brenthub/brent-pusher
brent-pusher-core/src/main/java/cn/brent/pusher/core/Config.java
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Constants.java // final public class Constants { // // /** 连接保存者 */ // protected ISessionManager sessionManager=new MapSessionManager(); // // protected int port=8887; // // public ISessionManager getSessionManager() { // return sessionManager; // } // // public void setSessionManager(ISessionManager sessionManager) { // this.sessionManager = sessionManager; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Plugins.java // final public class Plugins { // // private final List<IPlugin> list = new ArrayList<IPlugin>(); // // /** // * 新增插件 // * @param verifier // * @return // */ // public Plugins add(IPlugin verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IPlugin[] getAll() { // return list.toArray(new IPlugin[list.size()]); // } // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java // public abstract class PusherConfig { // // /** // * Config constant // */ // public abstract void configConstant(Constants me); // // /** // * Config IVerifier // */ // public abstract void configVerifier(Verifiers me); // // /** // * Config Plugin // */ // public abstract void configPlugin(Plugins me); // // /** // * Call back after start // */ // public void afterStart(){}; // // /** // * Call back before stop // */ // public void beforeStop(){}; // // /** // * Call back after Connect Success // */ // public void afterConnectSuccess(IPusherClient socket){}; // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Verifiers.java // final public class Verifiers { // // private final List<IVerifier> list = new ArrayList<IVerifier>(); // // /** // * 新增认证器 // * @param verifier // * @return // */ // public Verifiers add(IVerifier verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IVerifier[] getAll() { // return list.toArray(new IVerifier[list.size()]); // } // // }
import cn.brent.pusher.config.Constants; import cn.brent.pusher.config.Plugins; import cn.brent.pusher.config.PusherConfig; import cn.brent.pusher.config.Verifiers;
package cn.brent.pusher.core; public class Config { private static Constants constants = new Constants();
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Constants.java // final public class Constants { // // /** 连接保存者 */ // protected ISessionManager sessionManager=new MapSessionManager(); // // protected int port=8887; // // public ISessionManager getSessionManager() { // return sessionManager; // } // // public void setSessionManager(ISessionManager sessionManager) { // this.sessionManager = sessionManager; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Plugins.java // final public class Plugins { // // private final List<IPlugin> list = new ArrayList<IPlugin>(); // // /** // * 新增插件 // * @param verifier // * @return // */ // public Plugins add(IPlugin verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IPlugin[] getAll() { // return list.toArray(new IPlugin[list.size()]); // } // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java // public abstract class PusherConfig { // // /** // * Config constant // */ // public abstract void configConstant(Constants me); // // /** // * Config IVerifier // */ // public abstract void configVerifier(Verifiers me); // // /** // * Config Plugin // */ // public abstract void configPlugin(Plugins me); // // /** // * Call back after start // */ // public void afterStart(){}; // // /** // * Call back before stop // */ // public void beforeStop(){}; // // /** // * Call back after Connect Success // */ // public void afterConnectSuccess(IPusherClient socket){}; // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Verifiers.java // final public class Verifiers { // // private final List<IVerifier> list = new ArrayList<IVerifier>(); // // /** // * 新增认证器 // * @param verifier // * @return // */ // public Verifiers add(IVerifier verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IVerifier[] getAll() { // return list.toArray(new IVerifier[list.size()]); // } // // } // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/Config.java import cn.brent.pusher.config.Constants; import cn.brent.pusher.config.Plugins; import cn.brent.pusher.config.PusherConfig; import cn.brent.pusher.config.Verifiers; package cn.brent.pusher.core; public class Config { private static Constants constants = new Constants();
private static Verifiers verifiers = new Verifiers();
brenthub/brent-pusher
brent-pusher-core/src/main/java/cn/brent/pusher/core/Config.java
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Constants.java // final public class Constants { // // /** 连接保存者 */ // protected ISessionManager sessionManager=new MapSessionManager(); // // protected int port=8887; // // public ISessionManager getSessionManager() { // return sessionManager; // } // // public void setSessionManager(ISessionManager sessionManager) { // this.sessionManager = sessionManager; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Plugins.java // final public class Plugins { // // private final List<IPlugin> list = new ArrayList<IPlugin>(); // // /** // * 新增插件 // * @param verifier // * @return // */ // public Plugins add(IPlugin verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IPlugin[] getAll() { // return list.toArray(new IPlugin[list.size()]); // } // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java // public abstract class PusherConfig { // // /** // * Config constant // */ // public abstract void configConstant(Constants me); // // /** // * Config IVerifier // */ // public abstract void configVerifier(Verifiers me); // // /** // * Config Plugin // */ // public abstract void configPlugin(Plugins me); // // /** // * Call back after start // */ // public void afterStart(){}; // // /** // * Call back before stop // */ // public void beforeStop(){}; // // /** // * Call back after Connect Success // */ // public void afterConnectSuccess(IPusherClient socket){}; // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Verifiers.java // final public class Verifiers { // // private final List<IVerifier> list = new ArrayList<IVerifier>(); // // /** // * 新增认证器 // * @param verifier // * @return // */ // public Verifiers add(IVerifier verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IVerifier[] getAll() { // return list.toArray(new IVerifier[list.size()]); // } // // }
import cn.brent.pusher.config.Constants; import cn.brent.pusher.config.Plugins; import cn.brent.pusher.config.PusherConfig; import cn.brent.pusher.config.Verifiers;
package cn.brent.pusher.core; public class Config { private static Constants constants = new Constants(); private static Verifiers verifiers = new Verifiers();
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Constants.java // final public class Constants { // // /** 连接保存者 */ // protected ISessionManager sessionManager=new MapSessionManager(); // // protected int port=8887; // // public ISessionManager getSessionManager() { // return sessionManager; // } // // public void setSessionManager(ISessionManager sessionManager) { // this.sessionManager = sessionManager; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Plugins.java // final public class Plugins { // // private final List<IPlugin> list = new ArrayList<IPlugin>(); // // /** // * 新增插件 // * @param verifier // * @return // */ // public Plugins add(IPlugin verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IPlugin[] getAll() { // return list.toArray(new IPlugin[list.size()]); // } // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java // public abstract class PusherConfig { // // /** // * Config constant // */ // public abstract void configConstant(Constants me); // // /** // * Config IVerifier // */ // public abstract void configVerifier(Verifiers me); // // /** // * Config Plugin // */ // public abstract void configPlugin(Plugins me); // // /** // * Call back after start // */ // public void afterStart(){}; // // /** // * Call back before stop // */ // public void beforeStop(){}; // // /** // * Call back after Connect Success // */ // public void afterConnectSuccess(IPusherClient socket){}; // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Verifiers.java // final public class Verifiers { // // private final List<IVerifier> list = new ArrayList<IVerifier>(); // // /** // * 新增认证器 // * @param verifier // * @return // */ // public Verifiers add(IVerifier verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IVerifier[] getAll() { // return list.toArray(new IVerifier[list.size()]); // } // // } // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/Config.java import cn.brent.pusher.config.Constants; import cn.brent.pusher.config.Plugins; import cn.brent.pusher.config.PusherConfig; import cn.brent.pusher.config.Verifiers; package cn.brent.pusher.core; public class Config { private static Constants constants = new Constants(); private static Verifiers verifiers = new Verifiers();
private static Plugins plugins = new Plugins();
brenthub/brent-pusher
brent-pusher-core/src/main/java/cn/brent/pusher/core/Config.java
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Constants.java // final public class Constants { // // /** 连接保存者 */ // protected ISessionManager sessionManager=new MapSessionManager(); // // protected int port=8887; // // public ISessionManager getSessionManager() { // return sessionManager; // } // // public void setSessionManager(ISessionManager sessionManager) { // this.sessionManager = sessionManager; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Plugins.java // final public class Plugins { // // private final List<IPlugin> list = new ArrayList<IPlugin>(); // // /** // * 新增插件 // * @param verifier // * @return // */ // public Plugins add(IPlugin verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IPlugin[] getAll() { // return list.toArray(new IPlugin[list.size()]); // } // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java // public abstract class PusherConfig { // // /** // * Config constant // */ // public abstract void configConstant(Constants me); // // /** // * Config IVerifier // */ // public abstract void configVerifier(Verifiers me); // // /** // * Config Plugin // */ // public abstract void configPlugin(Plugins me); // // /** // * Call back after start // */ // public void afterStart(){}; // // /** // * Call back before stop // */ // public void beforeStop(){}; // // /** // * Call back after Connect Success // */ // public void afterConnectSuccess(IPusherClient socket){}; // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Verifiers.java // final public class Verifiers { // // private final List<IVerifier> list = new ArrayList<IVerifier>(); // // /** // * 新增认证器 // * @param verifier // * @return // */ // public Verifiers add(IVerifier verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IVerifier[] getAll() { // return list.toArray(new IVerifier[list.size()]); // } // // }
import cn.brent.pusher.config.Constants; import cn.brent.pusher.config.Plugins; import cn.brent.pusher.config.PusherConfig; import cn.brent.pusher.config.Verifiers;
package cn.brent.pusher.core; public class Config { private static Constants constants = new Constants(); private static Verifiers verifiers = new Verifiers(); private static Plugins plugins = new Plugins();
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Constants.java // final public class Constants { // // /** 连接保存者 */ // protected ISessionManager sessionManager=new MapSessionManager(); // // protected int port=8887; // // public ISessionManager getSessionManager() { // return sessionManager; // } // // public void setSessionManager(ISessionManager sessionManager) { // this.sessionManager = sessionManager; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Plugins.java // final public class Plugins { // // private final List<IPlugin> list = new ArrayList<IPlugin>(); // // /** // * 新增插件 // * @param verifier // * @return // */ // public Plugins add(IPlugin verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IPlugin[] getAll() { // return list.toArray(new IPlugin[list.size()]); // } // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java // public abstract class PusherConfig { // // /** // * Config constant // */ // public abstract void configConstant(Constants me); // // /** // * Config IVerifier // */ // public abstract void configVerifier(Verifiers me); // // /** // * Config Plugin // */ // public abstract void configPlugin(Plugins me); // // /** // * Call back after start // */ // public void afterStart(){}; // // /** // * Call back before stop // */ // public void beforeStop(){}; // // /** // * Call back after Connect Success // */ // public void afterConnectSuccess(IPusherClient socket){}; // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/Verifiers.java // final public class Verifiers { // // private final List<IVerifier> list = new ArrayList<IVerifier>(); // // /** // * 新增认证器 // * @param verifier // * @return // */ // public Verifiers add(IVerifier verifier) { // if (verifier != null) // this.list.add(verifier); // return this; // } // // public IVerifier[] getAll() { // return list.toArray(new IVerifier[list.size()]); // } // // } // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/Config.java import cn.brent.pusher.config.Constants; import cn.brent.pusher.config.Plugins; import cn.brent.pusher.config.PusherConfig; import cn.brent.pusher.config.Verifiers; package cn.brent.pusher.core; public class Config { private static Constants constants = new Constants(); private static Verifiers verifiers = new Verifiers(); private static Plugins plugins = new Plugins();
protected static void configPusher(PusherConfig pushConfig) {
brenthub/brent-pusher
brent-pusher-core/src/main/java/cn/brent/pusher/ServerRunner.java
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java // public abstract class PusherConfig { // // /** // * Config constant // */ // public abstract void configConstant(Constants me); // // /** // * Config IVerifier // */ // public abstract void configVerifier(Verifiers me); // // /** // * Config Plugin // */ // public abstract void configPlugin(Plugins me); // // /** // * Call back after start // */ // public void afterStart(){}; // // /** // * Call back before stop // */ // public void beforeStop(){}; // // /** // * Call back after Connect Success // */ // public void afterConnectSuccess(IPusherClient socket){}; // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/PusherServer.java // public abstract class PusherServer { // // protected static Logger logger = LoggerFactory.getLogger(PusherServer.class); // // /** 个性化配置 */ // protected PusherConfig pushConfig; // // /** 会话管理 */ // protected ISessionManager sessionManager; // // /** 认证器 */ // protected IVerifier[] verifiers; // // /** 插件 */ // protected IPlugin[] plugins; // // /** 端口 */ // protected int port; // // public PusherServer(PusherConfig pushConfig) { // this.pushConfig=pushConfig; // Config.configPusher(pushConfig); // port=Config.getConstants().getPort(); // sessionManager=Config.getConstants().getSessionManager(); // verifiers=Config.getVerifiers().getAll(); // plugins=Config.getPlugins().getAll(); // } // // protected void onOpen(IPusherClient conn, String uri) { // PathDesc path; // try { // try { // path = PathDesc.parse(uri); // } catch (Exception e) { // throw new RuntimeException("Unsupported msg format"); // } // // Session session=sessionManager.getSession(path.getTopic(), path.getKey()); // // for(IVerifier verifier:verifiers){ // if(!verifier.verify(path,session)){ // throw new RuntimeException(verifier.failMsg(path)); // } // } // // conn.setTopic(path.getTopic()); // conn.setKey(path.getKey()); // conn.setTimeOut(path.getTimeOut()); // // //保存会话信息 // sessionManager.saveConnect(conn); // // //连接成功后的回调 // pushConfig.afterConnectSuccess(conn); // // logger.debug("new connection: " + uri + "," + conn + " connected!"); // // } catch (Exception e) { // conn.close(IPusherClient.REFUSE, "rejected connection, "+e.getMessage()); // } // } // // protected void onClose(IPusherClient conn, int code, String reason){ // if (code == IPusherClient.REFUSE) {// 被服务器拒绝 // // do nothing // } else { // logger.debug("connect disconnect..."); // sessionManager.removeConnect(conn); // } // } // // public void start() { // startServer(); // for(IPlugin p:plugins){ // p.start(); // } // pushConfig.afterStart(); // logger.info("PushServer started on port:" + this.getPort()); // } // // public void stop() { // pushConfig.beforeStop(); // for(IPlugin p:plugins){ // p.stop(); // } // this.stopServer(); // } // // public int getPort() { // return port; // } // // /** // * 停止服务 // */ // protected abstract void stopServer(); // // /** // * 开启服务 // */ // protected abstract void startServer(); // // // // }
import java.io.IOException; import java.util.Properties; import cn.brent.pusher.config.PusherConfig; import cn.brent.pusher.core.PusherServer;
package cn.brent.pusher; public class ServerRunner { public static final String configName="/pusher.conf"; public static void main(String[] args) { Properties p=new Properties(); try { p.load(ServerRunner.class.getResourceAsStream(configName)); } catch (IOException e1) { System.out.println("can't find config file "+configName); return; } String serverClass=p.getProperty("serverClass", "cn.brent.pusher.config.BlankPusherConfig"); String configClass=p.getProperty("configClass", "cn.brent.pusher.config.BlankPusherConfig"); Object obj; try { obj = Class.forName(configClass).newInstance(); } catch (Exception e) { e.printStackTrace(); return; }
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java // public abstract class PusherConfig { // // /** // * Config constant // */ // public abstract void configConstant(Constants me); // // /** // * Config IVerifier // */ // public abstract void configVerifier(Verifiers me); // // /** // * Config Plugin // */ // public abstract void configPlugin(Plugins me); // // /** // * Call back after start // */ // public void afterStart(){}; // // /** // * Call back before stop // */ // public void beforeStop(){}; // // /** // * Call back after Connect Success // */ // public void afterConnectSuccess(IPusherClient socket){}; // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/PusherServer.java // public abstract class PusherServer { // // protected static Logger logger = LoggerFactory.getLogger(PusherServer.class); // // /** 个性化配置 */ // protected PusherConfig pushConfig; // // /** 会话管理 */ // protected ISessionManager sessionManager; // // /** 认证器 */ // protected IVerifier[] verifiers; // // /** 插件 */ // protected IPlugin[] plugins; // // /** 端口 */ // protected int port; // // public PusherServer(PusherConfig pushConfig) { // this.pushConfig=pushConfig; // Config.configPusher(pushConfig); // port=Config.getConstants().getPort(); // sessionManager=Config.getConstants().getSessionManager(); // verifiers=Config.getVerifiers().getAll(); // plugins=Config.getPlugins().getAll(); // } // // protected void onOpen(IPusherClient conn, String uri) { // PathDesc path; // try { // try { // path = PathDesc.parse(uri); // } catch (Exception e) { // throw new RuntimeException("Unsupported msg format"); // } // // Session session=sessionManager.getSession(path.getTopic(), path.getKey()); // // for(IVerifier verifier:verifiers){ // if(!verifier.verify(path,session)){ // throw new RuntimeException(verifier.failMsg(path)); // } // } // // conn.setTopic(path.getTopic()); // conn.setKey(path.getKey()); // conn.setTimeOut(path.getTimeOut()); // // //保存会话信息 // sessionManager.saveConnect(conn); // // //连接成功后的回调 // pushConfig.afterConnectSuccess(conn); // // logger.debug("new connection: " + uri + "," + conn + " connected!"); // // } catch (Exception e) { // conn.close(IPusherClient.REFUSE, "rejected connection, "+e.getMessage()); // } // } // // protected void onClose(IPusherClient conn, int code, String reason){ // if (code == IPusherClient.REFUSE) {// 被服务器拒绝 // // do nothing // } else { // logger.debug("connect disconnect..."); // sessionManager.removeConnect(conn); // } // } // // public void start() { // startServer(); // for(IPlugin p:plugins){ // p.start(); // } // pushConfig.afterStart(); // logger.info("PushServer started on port:" + this.getPort()); // } // // public void stop() { // pushConfig.beforeStop(); // for(IPlugin p:plugins){ // p.stop(); // } // this.stopServer(); // } // // public int getPort() { // return port; // } // // /** // * 停止服务 // */ // protected abstract void stopServer(); // // /** // * 开启服务 // */ // protected abstract void startServer(); // // // // } // Path: brent-pusher-core/src/main/java/cn/brent/pusher/ServerRunner.java import java.io.IOException; import java.util.Properties; import cn.brent.pusher.config.PusherConfig; import cn.brent.pusher.core.PusherServer; package cn.brent.pusher; public class ServerRunner { public static final String configName="/pusher.conf"; public static void main(String[] args) { Properties p=new Properties(); try { p.load(ServerRunner.class.getResourceAsStream(configName)); } catch (IOException e1) { System.out.println("can't find config file "+configName); return; } String serverClass=p.getProperty("serverClass", "cn.brent.pusher.config.BlankPusherConfig"); String configClass=p.getProperty("configClass", "cn.brent.pusher.config.BlankPusherConfig"); Object obj; try { obj = Class.forName(configClass).newInstance(); } catch (Exception e) { e.printStackTrace(); return; }
if(obj instanceof PusherConfig){
brenthub/brent-pusher
brent-pusher-core/src/main/java/cn/brent/pusher/ServerRunner.java
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java // public abstract class PusherConfig { // // /** // * Config constant // */ // public abstract void configConstant(Constants me); // // /** // * Config IVerifier // */ // public abstract void configVerifier(Verifiers me); // // /** // * Config Plugin // */ // public abstract void configPlugin(Plugins me); // // /** // * Call back after start // */ // public void afterStart(){}; // // /** // * Call back before stop // */ // public void beforeStop(){}; // // /** // * Call back after Connect Success // */ // public void afterConnectSuccess(IPusherClient socket){}; // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/PusherServer.java // public abstract class PusherServer { // // protected static Logger logger = LoggerFactory.getLogger(PusherServer.class); // // /** 个性化配置 */ // protected PusherConfig pushConfig; // // /** 会话管理 */ // protected ISessionManager sessionManager; // // /** 认证器 */ // protected IVerifier[] verifiers; // // /** 插件 */ // protected IPlugin[] plugins; // // /** 端口 */ // protected int port; // // public PusherServer(PusherConfig pushConfig) { // this.pushConfig=pushConfig; // Config.configPusher(pushConfig); // port=Config.getConstants().getPort(); // sessionManager=Config.getConstants().getSessionManager(); // verifiers=Config.getVerifiers().getAll(); // plugins=Config.getPlugins().getAll(); // } // // protected void onOpen(IPusherClient conn, String uri) { // PathDesc path; // try { // try { // path = PathDesc.parse(uri); // } catch (Exception e) { // throw new RuntimeException("Unsupported msg format"); // } // // Session session=sessionManager.getSession(path.getTopic(), path.getKey()); // // for(IVerifier verifier:verifiers){ // if(!verifier.verify(path,session)){ // throw new RuntimeException(verifier.failMsg(path)); // } // } // // conn.setTopic(path.getTopic()); // conn.setKey(path.getKey()); // conn.setTimeOut(path.getTimeOut()); // // //保存会话信息 // sessionManager.saveConnect(conn); // // //连接成功后的回调 // pushConfig.afterConnectSuccess(conn); // // logger.debug("new connection: " + uri + "," + conn + " connected!"); // // } catch (Exception e) { // conn.close(IPusherClient.REFUSE, "rejected connection, "+e.getMessage()); // } // } // // protected void onClose(IPusherClient conn, int code, String reason){ // if (code == IPusherClient.REFUSE) {// 被服务器拒绝 // // do nothing // } else { // logger.debug("connect disconnect..."); // sessionManager.removeConnect(conn); // } // } // // public void start() { // startServer(); // for(IPlugin p:plugins){ // p.start(); // } // pushConfig.afterStart(); // logger.info("PushServer started on port:" + this.getPort()); // } // // public void stop() { // pushConfig.beforeStop(); // for(IPlugin p:plugins){ // p.stop(); // } // this.stopServer(); // } // // public int getPort() { // return port; // } // // /** // * 停止服务 // */ // protected abstract void stopServer(); // // /** // * 开启服务 // */ // protected abstract void startServer(); // // // // }
import java.io.IOException; import java.util.Properties; import cn.brent.pusher.config.PusherConfig; import cn.brent.pusher.core.PusherServer;
package cn.brent.pusher; public class ServerRunner { public static final String configName="/pusher.conf"; public static void main(String[] args) { Properties p=new Properties(); try { p.load(ServerRunner.class.getResourceAsStream(configName)); } catch (IOException e1) { System.out.println("can't find config file "+configName); return; } String serverClass=p.getProperty("serverClass", "cn.brent.pusher.config.BlankPusherConfig"); String configClass=p.getProperty("configClass", "cn.brent.pusher.config.BlankPusherConfig"); Object obj; try { obj = Class.forName(configClass).newInstance(); } catch (Exception e) { e.printStackTrace(); return; } if(obj instanceof PusherConfig){ PusherConfig config=(PusherConfig)obj; Object server; try { server = Class.forName(serverClass).getConstructor(PusherConfig.class).newInstance(config); } catch (Exception e) { e.printStackTrace(); return; }
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java // public abstract class PusherConfig { // // /** // * Config constant // */ // public abstract void configConstant(Constants me); // // /** // * Config IVerifier // */ // public abstract void configVerifier(Verifiers me); // // /** // * Config Plugin // */ // public abstract void configPlugin(Plugins me); // // /** // * Call back after start // */ // public void afterStart(){}; // // /** // * Call back before stop // */ // public void beforeStop(){}; // // /** // * Call back after Connect Success // */ // public void afterConnectSuccess(IPusherClient socket){}; // } // // Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/PusherServer.java // public abstract class PusherServer { // // protected static Logger logger = LoggerFactory.getLogger(PusherServer.class); // // /** 个性化配置 */ // protected PusherConfig pushConfig; // // /** 会话管理 */ // protected ISessionManager sessionManager; // // /** 认证器 */ // protected IVerifier[] verifiers; // // /** 插件 */ // protected IPlugin[] plugins; // // /** 端口 */ // protected int port; // // public PusherServer(PusherConfig pushConfig) { // this.pushConfig=pushConfig; // Config.configPusher(pushConfig); // port=Config.getConstants().getPort(); // sessionManager=Config.getConstants().getSessionManager(); // verifiers=Config.getVerifiers().getAll(); // plugins=Config.getPlugins().getAll(); // } // // protected void onOpen(IPusherClient conn, String uri) { // PathDesc path; // try { // try { // path = PathDesc.parse(uri); // } catch (Exception e) { // throw new RuntimeException("Unsupported msg format"); // } // // Session session=sessionManager.getSession(path.getTopic(), path.getKey()); // // for(IVerifier verifier:verifiers){ // if(!verifier.verify(path,session)){ // throw new RuntimeException(verifier.failMsg(path)); // } // } // // conn.setTopic(path.getTopic()); // conn.setKey(path.getKey()); // conn.setTimeOut(path.getTimeOut()); // // //保存会话信息 // sessionManager.saveConnect(conn); // // //连接成功后的回调 // pushConfig.afterConnectSuccess(conn); // // logger.debug("new connection: " + uri + "," + conn + " connected!"); // // } catch (Exception e) { // conn.close(IPusherClient.REFUSE, "rejected connection, "+e.getMessage()); // } // } // // protected void onClose(IPusherClient conn, int code, String reason){ // if (code == IPusherClient.REFUSE) {// 被服务器拒绝 // // do nothing // } else { // logger.debug("connect disconnect..."); // sessionManager.removeConnect(conn); // } // } // // public void start() { // startServer(); // for(IPlugin p:plugins){ // p.start(); // } // pushConfig.afterStart(); // logger.info("PushServer started on port:" + this.getPort()); // } // // public void stop() { // pushConfig.beforeStop(); // for(IPlugin p:plugins){ // p.stop(); // } // this.stopServer(); // } // // public int getPort() { // return port; // } // // /** // * 停止服务 // */ // protected abstract void stopServer(); // // /** // * 开启服务 // */ // protected abstract void startServer(); // // // // } // Path: brent-pusher-core/src/main/java/cn/brent/pusher/ServerRunner.java import java.io.IOException; import java.util.Properties; import cn.brent.pusher.config.PusherConfig; import cn.brent.pusher.core.PusherServer; package cn.brent.pusher; public class ServerRunner { public static final String configName="/pusher.conf"; public static void main(String[] args) { Properties p=new Properties(); try { p.load(ServerRunner.class.getResourceAsStream(configName)); } catch (IOException e1) { System.out.println("can't find config file "+configName); return; } String serverClass=p.getProperty("serverClass", "cn.brent.pusher.config.BlankPusherConfig"); String configClass=p.getProperty("configClass", "cn.brent.pusher.config.BlankPusherConfig"); Object obj; try { obj = Class.forName(configClass).newInstance(); } catch (Exception e) { e.printStackTrace(); return; } if(obj instanceof PusherConfig){ PusherConfig config=(PusherConfig)obj; Object server; try { server = Class.forName(serverClass).getConstructor(PusherConfig.class).newInstance(config); } catch (Exception e) { e.printStackTrace(); return; }
PusherServer sv=(PusherServer)server;
brenthub/brent-pusher
brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/IPusherClient.java // public interface IPusherClient { // // /** // * 正常关闭 // */ // public static final int NORMAL = 1000; // // /** // * 服务器拒绝 // */ // public static final int REFUSE = 1003; // // // /** // * 关闭连接 // * @param code 状态码 // * @param reason 原因 // */ // void close(int code,String reason); // // /** // * 获取属性值 // * @param key // * @return // */ // Object getAttr(String key); // // /** // * 新增属性值 // * @param key // * @param val // */ // void addAttr(String key, Object val); // // /** // * 移除属性值 // * @param key // */ // void removeAttr(String key); // // /** // * 获取key // * @return // */ // String getKey(); // // /** // * 获取Topic // * @return // */ // String getTopic(); // // /** // * 保存key // * @param key // */ // void setKey(String key); // // /** // * 保存Topic // * @param topic // */ // void setTopic(String topic); // // /** // * 获取创建时间 // * @return // */ // long getCreateTime(); // // /** // * 发送消息 // * @param message // */ // void send(String message); // // /** // * 发送消息 // * @param message // * @param close 发送成功后是否关闭连接 // */ // void send(String message,boolean close); // // // /** // * 获取超时时间 // * @return // */ // Long getTimeOut(); // // /** // * 设置超时时间 // */ // void setTimeOut(Long timeout); // // }
import cn.brent.pusher.core.IPusherClient;
package cn.brent.pusher.config; /** * 配置管理 */ public abstract class PusherConfig { /** * Config constant */ public abstract void configConstant(Constants me); /** * Config IVerifier */ public abstract void configVerifier(Verifiers me); /** * Config Plugin */ public abstract void configPlugin(Plugins me); /** * Call back after start */ public void afterStart(){}; /** * Call back before stop */ public void beforeStop(){}; /** * Call back after Connect Success */
// Path: brent-pusher-core/src/main/java/cn/brent/pusher/core/IPusherClient.java // public interface IPusherClient { // // /** // * 正常关闭 // */ // public static final int NORMAL = 1000; // // /** // * 服务器拒绝 // */ // public static final int REFUSE = 1003; // // // /** // * 关闭连接 // * @param code 状态码 // * @param reason 原因 // */ // void close(int code,String reason); // // /** // * 获取属性值 // * @param key // * @return // */ // Object getAttr(String key); // // /** // * 新增属性值 // * @param key // * @param val // */ // void addAttr(String key, Object val); // // /** // * 移除属性值 // * @param key // */ // void removeAttr(String key); // // /** // * 获取key // * @return // */ // String getKey(); // // /** // * 获取Topic // * @return // */ // String getTopic(); // // /** // * 保存key // * @param key // */ // void setKey(String key); // // /** // * 保存Topic // * @param topic // */ // void setTopic(String topic); // // /** // * 获取创建时间 // * @return // */ // long getCreateTime(); // // /** // * 发送消息 // * @param message // */ // void send(String message); // // /** // * 发送消息 // * @param message // * @param close 发送成功后是否关闭连接 // */ // void send(String message,boolean close); // // // /** // * 获取超时时间 // * @return // */ // Long getTimeOut(); // // /** // * 设置超时时间 // */ // void setTimeOut(Long timeout); // // } // Path: brent-pusher-core/src/main/java/cn/brent/pusher/config/PusherConfig.java import cn.brent.pusher.core.IPusherClient; package cn.brent.pusher.config; /** * 配置管理 */ public abstract class PusherConfig { /** * Config constant */ public abstract void configConstant(Constants me); /** * Config IVerifier */ public abstract void configVerifier(Verifiers me); /** * Config Plugin */ public abstract void configPlugin(Plugins me); /** * Call back after start */ public void afterStart(){}; /** * Call back before stop */ public void beforeStop(){}; /** * Call back after Connect Success */
public void afterConnectSuccess(IPusherClient socket){};
garfieldon757/video_management_system
src/com/adp/dao/AlgorithmDAO.java
// Path: src/com/adp/model/Algorithm.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "Algorithm")//声明在数据库中自动生成的表名为User // public class Algorithm { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmID; // // private String algorithmName; // private String executeInstraction; // private String fileUrl; // private String sampleExecInstraction; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="userID") // private User user; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="algorithmCategoryID") // private AlgorithmCategory algorithmCategory; // // @OneToMany(mappedBy = "algorithm", cascade=CascadeType.MERGE , fetch=FetchType.EAGER) // @JsonIgnore // private List<ProcessLog> processLogList = new ArrayList<ProcessLog>(); // // // public Integer getAlgorithmID() { // return algorithmID; // } // // public void setAlgorithmID(Integer algorithmID) { // this.algorithmID = algorithmID; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public AlgorithmCategory getAlgorithmCategory() { // return algorithmCategory; // } // // public void setAlgorithmCategory(AlgorithmCategory algorithmCategory) { // this.algorithmCategory = algorithmCategory; // } // // public String getAlgorithmName() { // return algorithmName; // } // // public void setAlgorithmName(String algorithmName) { // this.algorithmName = algorithmName; // } // // public String getExecuteInstraction() { // return executeInstraction; // } // // public void setExecuteInstraction(String executeInstraction) { // this.executeInstraction = executeInstraction; // } // // public String getFileUrl() { // return fileUrl; // } // // public void setFileUrl(String fileUrl) { // this.fileUrl = fileUrl; // } // // public String getSampleExecInstraction() { // return sampleExecInstraction; // } // // public void setSampleExecInstraction(String sampleExecInstraction) { // this.sampleExecInstraction = sampleExecInstraction; // } // // public List<ProcessLog> getProcessLogList() { // return processLogList; // } // // public void setProcessLogList(List<ProcessLog> processLogList) { // this.processLogList = processLogList; // } // // // // // // // // } // // Path: src/com/adp/model/AlgorithmCategory.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "AlgorithmCategory")//声明在数据库中自动生成的表名为User // public class AlgorithmCategory { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmCategoryID; // // private String algorithmCategoryName; // // @OneToMany(mappedBy = "algorithmCategory", cascade=CascadeType.MERGE, fetch=FetchType.LAZY) // @JsonIgnore // private List<Algorithm> algorithmList = new ArrayList<Algorithm>(); // // public Integer getAlgorithmCategoryID() { // return algorithmCategoryID; // } // // public void setAlgorithmCategoryID(Integer algorithmCategoryID) { // this.algorithmCategoryID = algorithmCategoryID; // } // public String getAlgorithmCategoryName() { // return algorithmCategoryName; // } // public void setAlgorithmCategoryName(String algorithmCategoryName) { // this.algorithmCategoryName = algorithmCategoryName; // } // // }
import java.util.List; import com.adp.model.Algorithm; import com.adp.model.AlgorithmCategory;
package com.adp.dao; public interface AlgorithmDAO { public AlgorithmCategory getAlgorithmCategoryByAlgorithmCategoryID(int AlgorithmCategoryID);
// Path: src/com/adp/model/Algorithm.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "Algorithm")//声明在数据库中自动生成的表名为User // public class Algorithm { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmID; // // private String algorithmName; // private String executeInstraction; // private String fileUrl; // private String sampleExecInstraction; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="userID") // private User user; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="algorithmCategoryID") // private AlgorithmCategory algorithmCategory; // // @OneToMany(mappedBy = "algorithm", cascade=CascadeType.MERGE , fetch=FetchType.EAGER) // @JsonIgnore // private List<ProcessLog> processLogList = new ArrayList<ProcessLog>(); // // // public Integer getAlgorithmID() { // return algorithmID; // } // // public void setAlgorithmID(Integer algorithmID) { // this.algorithmID = algorithmID; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public AlgorithmCategory getAlgorithmCategory() { // return algorithmCategory; // } // // public void setAlgorithmCategory(AlgorithmCategory algorithmCategory) { // this.algorithmCategory = algorithmCategory; // } // // public String getAlgorithmName() { // return algorithmName; // } // // public void setAlgorithmName(String algorithmName) { // this.algorithmName = algorithmName; // } // // public String getExecuteInstraction() { // return executeInstraction; // } // // public void setExecuteInstraction(String executeInstraction) { // this.executeInstraction = executeInstraction; // } // // public String getFileUrl() { // return fileUrl; // } // // public void setFileUrl(String fileUrl) { // this.fileUrl = fileUrl; // } // // public String getSampleExecInstraction() { // return sampleExecInstraction; // } // // public void setSampleExecInstraction(String sampleExecInstraction) { // this.sampleExecInstraction = sampleExecInstraction; // } // // public List<ProcessLog> getProcessLogList() { // return processLogList; // } // // public void setProcessLogList(List<ProcessLog> processLogList) { // this.processLogList = processLogList; // } // // // // // // // // } // // Path: src/com/adp/model/AlgorithmCategory.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "AlgorithmCategory")//声明在数据库中自动生成的表名为User // public class AlgorithmCategory { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmCategoryID; // // private String algorithmCategoryName; // // @OneToMany(mappedBy = "algorithmCategory", cascade=CascadeType.MERGE, fetch=FetchType.LAZY) // @JsonIgnore // private List<Algorithm> algorithmList = new ArrayList<Algorithm>(); // // public Integer getAlgorithmCategoryID() { // return algorithmCategoryID; // } // // public void setAlgorithmCategoryID(Integer algorithmCategoryID) { // this.algorithmCategoryID = algorithmCategoryID; // } // public String getAlgorithmCategoryName() { // return algorithmCategoryName; // } // public void setAlgorithmCategoryName(String algorithmCategoryName) { // this.algorithmCategoryName = algorithmCategoryName; // } // // } // Path: src/com/adp/dao/AlgorithmDAO.java import java.util.List; import com.adp.model.Algorithm; import com.adp.model.AlgorithmCategory; package com.adp.dao; public interface AlgorithmDAO { public AlgorithmCategory getAlgorithmCategoryByAlgorithmCategoryID(int AlgorithmCategoryID);
public List<Algorithm> getAlgorithmsByCategory(AlgorithmCategory algorithmCategory);
garfieldon757/video_management_system
src/com/adp/dao/impl/AlgorithmDAOImpl.java
// Path: src/com/adp/dao/AlgorithmDAO.java // public interface AlgorithmDAO { // // public AlgorithmCategory getAlgorithmCategoryByAlgorithmCategoryID(int AlgorithmCategoryID); // public List<Algorithm> getAlgorithmsByCategory(AlgorithmCategory algorithmCategory); // public List<Algorithm> getAllAlgorithm(); // } // // Path: src/com/adp/model/Algorithm.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "Algorithm")//声明在数据库中自动生成的表名为User // public class Algorithm { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmID; // // private String algorithmName; // private String executeInstraction; // private String fileUrl; // private String sampleExecInstraction; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="userID") // private User user; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="algorithmCategoryID") // private AlgorithmCategory algorithmCategory; // // @OneToMany(mappedBy = "algorithm", cascade=CascadeType.MERGE , fetch=FetchType.EAGER) // @JsonIgnore // private List<ProcessLog> processLogList = new ArrayList<ProcessLog>(); // // // public Integer getAlgorithmID() { // return algorithmID; // } // // public void setAlgorithmID(Integer algorithmID) { // this.algorithmID = algorithmID; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public AlgorithmCategory getAlgorithmCategory() { // return algorithmCategory; // } // // public void setAlgorithmCategory(AlgorithmCategory algorithmCategory) { // this.algorithmCategory = algorithmCategory; // } // // public String getAlgorithmName() { // return algorithmName; // } // // public void setAlgorithmName(String algorithmName) { // this.algorithmName = algorithmName; // } // // public String getExecuteInstraction() { // return executeInstraction; // } // // public void setExecuteInstraction(String executeInstraction) { // this.executeInstraction = executeInstraction; // } // // public String getFileUrl() { // return fileUrl; // } // // public void setFileUrl(String fileUrl) { // this.fileUrl = fileUrl; // } // // public String getSampleExecInstraction() { // return sampleExecInstraction; // } // // public void setSampleExecInstraction(String sampleExecInstraction) { // this.sampleExecInstraction = sampleExecInstraction; // } // // public List<ProcessLog> getProcessLogList() { // return processLogList; // } // // public void setProcessLogList(List<ProcessLog> processLogList) { // this.processLogList = processLogList; // } // // // // // // // // } // // Path: src/com/adp/model/AlgorithmCategory.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "AlgorithmCategory")//声明在数据库中自动生成的表名为User // public class AlgorithmCategory { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmCategoryID; // // private String algorithmCategoryName; // // @OneToMany(mappedBy = "algorithmCategory", cascade=CascadeType.MERGE, fetch=FetchType.LAZY) // @JsonIgnore // private List<Algorithm> algorithmList = new ArrayList<Algorithm>(); // // public Integer getAlgorithmCategoryID() { // return algorithmCategoryID; // } // // public void setAlgorithmCategoryID(Integer algorithmCategoryID) { // this.algorithmCategoryID = algorithmCategoryID; // } // public String getAlgorithmCategoryName() { // return algorithmCategoryName; // } // public void setAlgorithmCategoryName(String algorithmCategoryName) { // this.algorithmCategoryName = algorithmCategoryName; // } // // }
import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.adp.dao.AlgorithmDAO; import com.adp.model.Algorithm; import com.adp.model.AlgorithmCategory;
package com.adp.dao.impl; @Repository("ad") @Transactional
// Path: src/com/adp/dao/AlgorithmDAO.java // public interface AlgorithmDAO { // // public AlgorithmCategory getAlgorithmCategoryByAlgorithmCategoryID(int AlgorithmCategoryID); // public List<Algorithm> getAlgorithmsByCategory(AlgorithmCategory algorithmCategory); // public List<Algorithm> getAllAlgorithm(); // } // // Path: src/com/adp/model/Algorithm.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "Algorithm")//声明在数据库中自动生成的表名为User // public class Algorithm { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmID; // // private String algorithmName; // private String executeInstraction; // private String fileUrl; // private String sampleExecInstraction; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="userID") // private User user; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="algorithmCategoryID") // private AlgorithmCategory algorithmCategory; // // @OneToMany(mappedBy = "algorithm", cascade=CascadeType.MERGE , fetch=FetchType.EAGER) // @JsonIgnore // private List<ProcessLog> processLogList = new ArrayList<ProcessLog>(); // // // public Integer getAlgorithmID() { // return algorithmID; // } // // public void setAlgorithmID(Integer algorithmID) { // this.algorithmID = algorithmID; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public AlgorithmCategory getAlgorithmCategory() { // return algorithmCategory; // } // // public void setAlgorithmCategory(AlgorithmCategory algorithmCategory) { // this.algorithmCategory = algorithmCategory; // } // // public String getAlgorithmName() { // return algorithmName; // } // // public void setAlgorithmName(String algorithmName) { // this.algorithmName = algorithmName; // } // // public String getExecuteInstraction() { // return executeInstraction; // } // // public void setExecuteInstraction(String executeInstraction) { // this.executeInstraction = executeInstraction; // } // // public String getFileUrl() { // return fileUrl; // } // // public void setFileUrl(String fileUrl) { // this.fileUrl = fileUrl; // } // // public String getSampleExecInstraction() { // return sampleExecInstraction; // } // // public void setSampleExecInstraction(String sampleExecInstraction) { // this.sampleExecInstraction = sampleExecInstraction; // } // // public List<ProcessLog> getProcessLogList() { // return processLogList; // } // // public void setProcessLogList(List<ProcessLog> processLogList) { // this.processLogList = processLogList; // } // // // // // // // // } // // Path: src/com/adp/model/AlgorithmCategory.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "AlgorithmCategory")//声明在数据库中自动生成的表名为User // public class AlgorithmCategory { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmCategoryID; // // private String algorithmCategoryName; // // @OneToMany(mappedBy = "algorithmCategory", cascade=CascadeType.MERGE, fetch=FetchType.LAZY) // @JsonIgnore // private List<Algorithm> algorithmList = new ArrayList<Algorithm>(); // // public Integer getAlgorithmCategoryID() { // return algorithmCategoryID; // } // // public void setAlgorithmCategoryID(Integer algorithmCategoryID) { // this.algorithmCategoryID = algorithmCategoryID; // } // public String getAlgorithmCategoryName() { // return algorithmCategoryName; // } // public void setAlgorithmCategoryName(String algorithmCategoryName) { // this.algorithmCategoryName = algorithmCategoryName; // } // // } // Path: src/com/adp/dao/impl/AlgorithmDAOImpl.java import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.adp.dao.AlgorithmDAO; import com.adp.model.Algorithm; import com.adp.model.AlgorithmCategory; package com.adp.dao.impl; @Repository("ad") @Transactional
public class AlgorithmDAOImpl implements AlgorithmDAO{
garfieldon757/video_management_system
src/com/adp/dao/impl/AlgorithmDAOImpl.java
// Path: src/com/adp/dao/AlgorithmDAO.java // public interface AlgorithmDAO { // // public AlgorithmCategory getAlgorithmCategoryByAlgorithmCategoryID(int AlgorithmCategoryID); // public List<Algorithm> getAlgorithmsByCategory(AlgorithmCategory algorithmCategory); // public List<Algorithm> getAllAlgorithm(); // } // // Path: src/com/adp/model/Algorithm.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "Algorithm")//声明在数据库中自动生成的表名为User // public class Algorithm { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmID; // // private String algorithmName; // private String executeInstraction; // private String fileUrl; // private String sampleExecInstraction; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="userID") // private User user; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="algorithmCategoryID") // private AlgorithmCategory algorithmCategory; // // @OneToMany(mappedBy = "algorithm", cascade=CascadeType.MERGE , fetch=FetchType.EAGER) // @JsonIgnore // private List<ProcessLog> processLogList = new ArrayList<ProcessLog>(); // // // public Integer getAlgorithmID() { // return algorithmID; // } // // public void setAlgorithmID(Integer algorithmID) { // this.algorithmID = algorithmID; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public AlgorithmCategory getAlgorithmCategory() { // return algorithmCategory; // } // // public void setAlgorithmCategory(AlgorithmCategory algorithmCategory) { // this.algorithmCategory = algorithmCategory; // } // // public String getAlgorithmName() { // return algorithmName; // } // // public void setAlgorithmName(String algorithmName) { // this.algorithmName = algorithmName; // } // // public String getExecuteInstraction() { // return executeInstraction; // } // // public void setExecuteInstraction(String executeInstraction) { // this.executeInstraction = executeInstraction; // } // // public String getFileUrl() { // return fileUrl; // } // // public void setFileUrl(String fileUrl) { // this.fileUrl = fileUrl; // } // // public String getSampleExecInstraction() { // return sampleExecInstraction; // } // // public void setSampleExecInstraction(String sampleExecInstraction) { // this.sampleExecInstraction = sampleExecInstraction; // } // // public List<ProcessLog> getProcessLogList() { // return processLogList; // } // // public void setProcessLogList(List<ProcessLog> processLogList) { // this.processLogList = processLogList; // } // // // // // // // // } // // Path: src/com/adp/model/AlgorithmCategory.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "AlgorithmCategory")//声明在数据库中自动生成的表名为User // public class AlgorithmCategory { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmCategoryID; // // private String algorithmCategoryName; // // @OneToMany(mappedBy = "algorithmCategory", cascade=CascadeType.MERGE, fetch=FetchType.LAZY) // @JsonIgnore // private List<Algorithm> algorithmList = new ArrayList<Algorithm>(); // // public Integer getAlgorithmCategoryID() { // return algorithmCategoryID; // } // // public void setAlgorithmCategoryID(Integer algorithmCategoryID) { // this.algorithmCategoryID = algorithmCategoryID; // } // public String getAlgorithmCategoryName() { // return algorithmCategoryName; // } // public void setAlgorithmCategoryName(String algorithmCategoryName) { // this.algorithmCategoryName = algorithmCategoryName; // } // // }
import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.adp.dao.AlgorithmDAO; import com.adp.model.Algorithm; import com.adp.model.AlgorithmCategory;
package com.adp.dao.impl; @Repository("ad") @Transactional public class AlgorithmDAOImpl implements AlgorithmDAO{ @PersistenceContext(name="un") private EntityManager em ; @Override
// Path: src/com/adp/dao/AlgorithmDAO.java // public interface AlgorithmDAO { // // public AlgorithmCategory getAlgorithmCategoryByAlgorithmCategoryID(int AlgorithmCategoryID); // public List<Algorithm> getAlgorithmsByCategory(AlgorithmCategory algorithmCategory); // public List<Algorithm> getAllAlgorithm(); // } // // Path: src/com/adp/model/Algorithm.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "Algorithm")//声明在数据库中自动生成的表名为User // public class Algorithm { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmID; // // private String algorithmName; // private String executeInstraction; // private String fileUrl; // private String sampleExecInstraction; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="userID") // private User user; // // @ManyToOne(fetch = FetchType.EAGER) // @JoinColumn(name="algorithmCategoryID") // private AlgorithmCategory algorithmCategory; // // @OneToMany(mappedBy = "algorithm", cascade=CascadeType.MERGE , fetch=FetchType.EAGER) // @JsonIgnore // private List<ProcessLog> processLogList = new ArrayList<ProcessLog>(); // // // public Integer getAlgorithmID() { // return algorithmID; // } // // public void setAlgorithmID(Integer algorithmID) { // this.algorithmID = algorithmID; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public AlgorithmCategory getAlgorithmCategory() { // return algorithmCategory; // } // // public void setAlgorithmCategory(AlgorithmCategory algorithmCategory) { // this.algorithmCategory = algorithmCategory; // } // // public String getAlgorithmName() { // return algorithmName; // } // // public void setAlgorithmName(String algorithmName) { // this.algorithmName = algorithmName; // } // // public String getExecuteInstraction() { // return executeInstraction; // } // // public void setExecuteInstraction(String executeInstraction) { // this.executeInstraction = executeInstraction; // } // // public String getFileUrl() { // return fileUrl; // } // // public void setFileUrl(String fileUrl) { // this.fileUrl = fileUrl; // } // // public String getSampleExecInstraction() { // return sampleExecInstraction; // } // // public void setSampleExecInstraction(String sampleExecInstraction) { // this.sampleExecInstraction = sampleExecInstraction; // } // // public List<ProcessLog> getProcessLogList() { // return processLogList; // } // // public void setProcessLogList(List<ProcessLog> processLogList) { // this.processLogList = processLogList; // } // // // // // // // // } // // Path: src/com/adp/model/AlgorithmCategory.java // @Entity//声明当前类为hibernate映射到数据库中的实体�? // @Table(name = "AlgorithmCategory")//声明在数据库中自动生成的表名为User // public class AlgorithmCategory { // // @Id//声明此列为主�? // @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动�?�择合�?�的id生成方案,这里使用mysql,为�?�增�? // private Integer algorithmCategoryID; // // private String algorithmCategoryName; // // @OneToMany(mappedBy = "algorithmCategory", cascade=CascadeType.MERGE, fetch=FetchType.LAZY) // @JsonIgnore // private List<Algorithm> algorithmList = new ArrayList<Algorithm>(); // // public Integer getAlgorithmCategoryID() { // return algorithmCategoryID; // } // // public void setAlgorithmCategoryID(Integer algorithmCategoryID) { // this.algorithmCategoryID = algorithmCategoryID; // } // public String getAlgorithmCategoryName() { // return algorithmCategoryName; // } // public void setAlgorithmCategoryName(String algorithmCategoryName) { // this.algorithmCategoryName = algorithmCategoryName; // } // // } // Path: src/com/adp/dao/impl/AlgorithmDAOImpl.java import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.adp.dao.AlgorithmDAO; import com.adp.model.Algorithm; import com.adp.model.AlgorithmCategory; package com.adp.dao.impl; @Repository("ad") @Transactional public class AlgorithmDAOImpl implements AlgorithmDAO{ @PersistenceContext(name="un") private EntityManager em ; @Override
public AlgorithmCategory getAlgorithmCategoryByAlgorithmCategoryID(int AlgorithmCategoryID) {
lijunyandev/MeetMusic
app/src/main/java/com/lijunyan/blackmusic/util/MyApplication.java
// Path: app/src/main/java/com/lijunyan/blackmusic/service/MusicPlayerService.java // public class MusicPlayerService extends Service { // private static final String TAG = MusicPlayerService.class.getName(); // // public static final String PLAYER_MANAGER_ACTION = "com.lijunyan.blackmusic.service.MusicPlayerService.player.action"; // // private PlayerManagerReceiver mReceiver; // // public MusicPlayerService() { // } // // @Override // public IBinder onBind(Intent intent) { // throw new UnsupportedOperationException("Not yet implemented"); // } // // @Override // public void onCreate() { // super.onCreate(); // Log.e(TAG, "onCreate: "); // register(); // } // // @Override // public void onDestroy() { // super.onDestroy(); // Log.e(TAG, "onDestroy: "); // unRegister(); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // Log.e(TAG, "onStartCommand: "); // return super.onStartCommand(intent, flags, startId); // } // // // private void register() { // mReceiver = new PlayerManagerReceiver(MusicPlayerService.this); // IntentFilter intentFilter = new IntentFilter(); // intentFilter.addAction(PLAYER_MANAGER_ACTION); // registerReceiver(mReceiver, intentFilter); // } // // private void unRegister() { // if (mReceiver != null) { // unregisterReceiver(mReceiver); // } // } // // }
import android.app.Application; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatDelegate; import com.lijunyan.blackmusic.service.MusicPlayerService;
package com.lijunyan.blackmusic.util; /** * Created by lijunyan on 2017/2/8. */ public class MyApplication extends Application{ private static Context context; @Override public void onCreate() { super.onCreate(); context = getApplicationContext();
// Path: app/src/main/java/com/lijunyan/blackmusic/service/MusicPlayerService.java // public class MusicPlayerService extends Service { // private static final String TAG = MusicPlayerService.class.getName(); // // public static final String PLAYER_MANAGER_ACTION = "com.lijunyan.blackmusic.service.MusicPlayerService.player.action"; // // private PlayerManagerReceiver mReceiver; // // public MusicPlayerService() { // } // // @Override // public IBinder onBind(Intent intent) { // throw new UnsupportedOperationException("Not yet implemented"); // } // // @Override // public void onCreate() { // super.onCreate(); // Log.e(TAG, "onCreate: "); // register(); // } // // @Override // public void onDestroy() { // super.onDestroy(); // Log.e(TAG, "onDestroy: "); // unRegister(); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // Log.e(TAG, "onStartCommand: "); // return super.onStartCommand(intent, flags, startId); // } // // // private void register() { // mReceiver = new PlayerManagerReceiver(MusicPlayerService.this); // IntentFilter intentFilter = new IntentFilter(); // intentFilter.addAction(PLAYER_MANAGER_ACTION); // registerReceiver(mReceiver, intentFilter); // } // // private void unRegister() { // if (mReceiver != null) { // unregisterReceiver(mReceiver); // } // } // // } // Path: app/src/main/java/com/lijunyan/blackmusic/util/MyApplication.java import android.app.Application; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatDelegate; import com.lijunyan.blackmusic.service.MusicPlayerService; package com.lijunyan.blackmusic.util; /** * Created by lijunyan on 2017/2/8. */ public class MyApplication extends Application{ private static Context context; @Override public void onCreate() { super.onCreate(); context = getApplicationContext();
Intent startIntent = new Intent(MyApplication.this,MusicPlayerService.class);
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/commands/connect/CacheDevicesConnector.java
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // }
import com.github.e13mort.stf.adapter.filters.InclusionType; import com.github.e13mort.stf.adapter.filters.StringsFilterDescription; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.client.parameters.DevicesParamsImpl; import com.github.e13mort.stf.console.AdbRunner; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Flowable; import io.reactivex.Notification; import org.reactivestreams.Publisher; import java.util.List; import java.util.logging.Logger;
package com.github.e13mort.stf.console.commands.connect; class CacheDevicesConnector extends DeviceConnector { private final List<Integer> devicesIndexesFromCache;
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/commands/connect/CacheDevicesConnector.java import com.github.e13mort.stf.adapter.filters.InclusionType; import com.github.e13mort.stf.adapter.filters.StringsFilterDescription; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.client.parameters.DevicesParamsImpl; import com.github.e13mort.stf.console.AdbRunner; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Flowable; import io.reactivex.Notification; import org.reactivestreams.Publisher; import java.util.List; import java.util.logging.Logger; package com.github.e13mort.stf.console.commands.connect; class CacheDevicesConnector extends DeviceConnector { private final List<Integer> devicesIndexesFromCache;
private final DeviceListCache cache;
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/commands/connect/CacheDevicesConnector.java
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // }
import com.github.e13mort.stf.adapter.filters.InclusionType; import com.github.e13mort.stf.adapter.filters.StringsFilterDescription; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.client.parameters.DevicesParamsImpl; import com.github.e13mort.stf.console.AdbRunner; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Flowable; import io.reactivex.Notification; import org.reactivestreams.Publisher; import java.util.List; import java.util.logging.Logger;
package com.github.e13mort.stf.console.commands.connect; class CacheDevicesConnector extends DeviceConnector { private final List<Integer> devicesIndexesFromCache; private final DeviceListCache cache;
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/commands/connect/CacheDevicesConnector.java import com.github.e13mort.stf.adapter.filters.InclusionType; import com.github.e13mort.stf.adapter.filters.StringsFilterDescription; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.client.parameters.DevicesParamsImpl; import com.github.e13mort.stf.console.AdbRunner; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Flowable; import io.reactivex.Notification; import org.reactivestreams.Publisher; import java.util.List; import java.util.logging.Logger; package com.github.e13mort.stf.console.commands.connect; class CacheDevicesConnector extends DeviceConnector { private final List<Integer> devicesIndexesFromCache; private final DeviceListCache cache;
protected CacheDevicesConnector(FarmClient client, AdbRunner runner, Logger logger, List<Integer> devicesIndexesFromCache, DeviceListCache cache) {
e13mort/stf-console-client
client/src/test/java/com/github/e13mort/stf/console/commands/connect/ConnectCommandTest.java
// Path: client/src/test/java/com/github/e13mort/stf/console/BaseStfCommanderTest.java // public class BaseStfCommanderTest { // protected static final String TEST_DEVICE_REMOTE = "127.0.0.1:15500"; // @Mock // protected FarmClient farmClient; // @Mock // protected AdbRunner adbRunner; // @Mock // protected CommandContainer.Command helpCommand; // @Mock // protected DeviceListCache cache; // @Mock // protected ErrorHandler errorHandler; // @Mock // protected DeviceListCache.CacheTransaction cacheTransaction; // @Mock // private HelpCommandCreator helpCommandCreator; // @Mock // protected OutputStream outputStream; // @Mock // protected Logger logger; // @Mock // private Device myDevice; // // @BeforeEach // protected void setUp() throws IOException { // MockitoAnnotations.initMocks(this); // when(farmClient.getDevices(any(DevicesParams.class))).thenReturn(Flowable.empty()); // when(farmClient.connectToDevices(any(DevicesParams.class))).thenReturn(Flowable.empty()); // when(farmClient.disconnectFromAllDevices()).thenReturn(Flowable.empty()); // when(helpCommand.execute()).thenReturn(Completable.complete()); // when(helpCommandCreator.createHelpCommand(any(JCommander.class))).thenReturn(helpCommand); // when(farmClient.getMyDevices()).thenReturn(Flowable.fromArray(myDevice)); // when(myDevice.getRemoteConnectUrl()).thenReturn(TEST_DEVICE_REMOTE); // when(cache.beginTransaction()).thenReturn(cacheTransaction); // when(cache.getCachedFiles()).thenReturn(Collections.emptyList()); // } // // protected DevicesParams runDeviceParamsTest(DeviceParamsProducingCommand source, String params) throws IOException, UnknownCommandException { // ArgumentCaptor<DevicesParams> objectArgumentCaptor = ArgumentCaptor.forClass(DevicesParams.class); // createCommander(source.name().toLowerCase() + " " + params).execute(); // if (source == DeviceParamsProducingCommand.DEVICES) { // verify(farmClient).getDevices(objectArgumentCaptor.capture()); // } else { // verify(farmClient).connectToDevices(objectArgumentCaptor.capture()); // } // return objectArgumentCaptor.getValue(); // } // // protected Executable test(final DeviceParamsProducingCommand source, final String str) { // return () -> runDeviceParamsTest(source, str); // } // // protected StfCommander createCommander(String str) throws IOException { // return StfCommander.create(new StfCommanderContext(farmClient, adbRunner, cache, outputStream, logger), helpCommandCreator, errorHandler, str.split(" ")); // } // // enum DeviceParamsProducingCommand {DEVICES, CONNECT} // }
import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.BaseStfCommanderTest; import com.github.e13mort.stf.model.device.Device; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import io.reactivex.Flowable; import io.reactivex.Notification; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package com.github.e13mort.stf.console.commands.connect; @SuppressWarnings("unused") @DisplayName("Detailed \"connect\" command cases")
// Path: client/src/test/java/com/github/e13mort/stf/console/BaseStfCommanderTest.java // public class BaseStfCommanderTest { // protected static final String TEST_DEVICE_REMOTE = "127.0.0.1:15500"; // @Mock // protected FarmClient farmClient; // @Mock // protected AdbRunner adbRunner; // @Mock // protected CommandContainer.Command helpCommand; // @Mock // protected DeviceListCache cache; // @Mock // protected ErrorHandler errorHandler; // @Mock // protected DeviceListCache.CacheTransaction cacheTransaction; // @Mock // private HelpCommandCreator helpCommandCreator; // @Mock // protected OutputStream outputStream; // @Mock // protected Logger logger; // @Mock // private Device myDevice; // // @BeforeEach // protected void setUp() throws IOException { // MockitoAnnotations.initMocks(this); // when(farmClient.getDevices(any(DevicesParams.class))).thenReturn(Flowable.empty()); // when(farmClient.connectToDevices(any(DevicesParams.class))).thenReturn(Flowable.empty()); // when(farmClient.disconnectFromAllDevices()).thenReturn(Flowable.empty()); // when(helpCommand.execute()).thenReturn(Completable.complete()); // when(helpCommandCreator.createHelpCommand(any(JCommander.class))).thenReturn(helpCommand); // when(farmClient.getMyDevices()).thenReturn(Flowable.fromArray(myDevice)); // when(myDevice.getRemoteConnectUrl()).thenReturn(TEST_DEVICE_REMOTE); // when(cache.beginTransaction()).thenReturn(cacheTransaction); // when(cache.getCachedFiles()).thenReturn(Collections.emptyList()); // } // // protected DevicesParams runDeviceParamsTest(DeviceParamsProducingCommand source, String params) throws IOException, UnknownCommandException { // ArgumentCaptor<DevicesParams> objectArgumentCaptor = ArgumentCaptor.forClass(DevicesParams.class); // createCommander(source.name().toLowerCase() + " " + params).execute(); // if (source == DeviceParamsProducingCommand.DEVICES) { // verify(farmClient).getDevices(objectArgumentCaptor.capture()); // } else { // verify(farmClient).connectToDevices(objectArgumentCaptor.capture()); // } // return objectArgumentCaptor.getValue(); // } // // protected Executable test(final DeviceParamsProducingCommand source, final String str) { // return () -> runDeviceParamsTest(source, str); // } // // protected StfCommander createCommander(String str) throws IOException { // return StfCommander.create(new StfCommanderContext(farmClient, adbRunner, cache, outputStream, logger), helpCommandCreator, errorHandler, str.split(" ")); // } // // enum DeviceParamsProducingCommand {DEVICES, CONNECT} // } // Path: client/src/test/java/com/github/e13mort/stf/console/commands/connect/ConnectCommandTest.java import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.BaseStfCommanderTest; import com.github.e13mort.stf.model.device.Device; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import io.reactivex.Flowable; import io.reactivex.Notification; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package com.github.e13mort.stf.console.commands.connect; @SuppressWarnings("unused") @DisplayName("Detailed \"connect\" command cases")
class ConnectCommandTest extends BaseStfCommanderTest {
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/App.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/EmptyDevicesException.java // public class EmptyDevicesException extends Exception { } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // }
import com.github.e13mort.stf.console.commands.EmptyDevicesException; import com.github.e13mort.stf.console.commands.HelpCommandCreator.HelpCommandCreatorImpl; import com.github.e13mort.stf.console.commands.UnknownCommandException; import java.io.IOException; import java.util.logging.*;
package com.github.e13mort.stf.console; public class App { private static ErrorHandler errorHandler = throwable -> {}; public static void main(String... args) throws IOException { final Logger logger = createLogger(); errorHandler = new StfErrorHandler(logger); StfCommanderContext.create(logger)
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/EmptyDevicesException.java // public class EmptyDevicesException extends Exception { } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/App.java import com.github.e13mort.stf.console.commands.EmptyDevicesException; import com.github.e13mort.stf.console.commands.HelpCommandCreator.HelpCommandCreatorImpl; import com.github.e13mort.stf.console.commands.UnknownCommandException; import java.io.IOException; import java.util.logging.*; package com.github.e13mort.stf.console; public class App { private static ErrorHandler errorHandler = throwable -> {}; public static void main(String... args) throws IOException { final Logger logger = createLogger(); errorHandler = new StfErrorHandler(logger); StfCommanderContext.create(logger)
.map(context -> StfCommander.create(context, new HelpCommandCreatorImpl(), errorHandler, args))
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/App.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/EmptyDevicesException.java // public class EmptyDevicesException extends Exception { } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // }
import com.github.e13mort.stf.console.commands.EmptyDevicesException; import com.github.e13mort.stf.console.commands.HelpCommandCreator.HelpCommandCreatorImpl; import com.github.e13mort.stf.console.commands.UnknownCommandException; import java.io.IOException; import java.util.logging.*;
package com.github.e13mort.stf.console; public class App { private static ErrorHandler errorHandler = throwable -> {}; public static void main(String... args) throws IOException { final Logger logger = createLogger(); errorHandler = new StfErrorHandler(logger); StfCommanderContext.create(logger) .map(context -> StfCommander.create(context, new HelpCommandCreatorImpl(), errorHandler, args)) .subscribe(StfCommander::execute, errorHandler::handle); } static class StfErrorHandler implements ErrorHandler { private final Logger logger; StfErrorHandler(Logger logger) { this.logger = logger; } @Override public void handle(Throwable throwable) {
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/EmptyDevicesException.java // public class EmptyDevicesException extends Exception { } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/App.java import com.github.e13mort.stf.console.commands.EmptyDevicesException; import com.github.e13mort.stf.console.commands.HelpCommandCreator.HelpCommandCreatorImpl; import com.github.e13mort.stf.console.commands.UnknownCommandException; import java.io.IOException; import java.util.logging.*; package com.github.e13mort.stf.console; public class App { private static ErrorHandler errorHandler = throwable -> {}; public static void main(String... args) throws IOException { final Logger logger = createLogger(); errorHandler = new StfErrorHandler(logger); StfCommanderContext.create(logger) .map(context -> StfCommander.create(context, new HelpCommandCreatorImpl(), errorHandler, args)) .subscribe(StfCommander::execute, errorHandler::handle); } static class StfErrorHandler implements ErrorHandler { private final Logger logger; StfErrorHandler(Logger logger) { this.logger = logger; } @Override public void handle(Throwable throwable) {
if (throwable instanceof EmptyDevicesException) {
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/App.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/EmptyDevicesException.java // public class EmptyDevicesException extends Exception { } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // }
import com.github.e13mort.stf.console.commands.EmptyDevicesException; import com.github.e13mort.stf.console.commands.HelpCommandCreator.HelpCommandCreatorImpl; import com.github.e13mort.stf.console.commands.UnknownCommandException; import java.io.IOException; import java.util.logging.*;
package com.github.e13mort.stf.console; public class App { private static ErrorHandler errorHandler = throwable -> {}; public static void main(String... args) throws IOException { final Logger logger = createLogger(); errorHandler = new StfErrorHandler(logger); StfCommanderContext.create(logger) .map(context -> StfCommander.create(context, new HelpCommandCreatorImpl(), errorHandler, args)) .subscribe(StfCommander::execute, errorHandler::handle); } static class StfErrorHandler implements ErrorHandler { private final Logger logger; StfErrorHandler(Logger logger) { this.logger = logger; } @Override public void handle(Throwable throwable) { if (throwable instanceof EmptyDevicesException) { logger.log(Level.INFO ,"There's no devices");
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/EmptyDevicesException.java // public class EmptyDevicesException extends Exception { } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/App.java import com.github.e13mort.stf.console.commands.EmptyDevicesException; import com.github.e13mort.stf.console.commands.HelpCommandCreator.HelpCommandCreatorImpl; import com.github.e13mort.stf.console.commands.UnknownCommandException; import java.io.IOException; import java.util.logging.*; package com.github.e13mort.stf.console; public class App { private static ErrorHandler errorHandler = throwable -> {}; public static void main(String... args) throws IOException { final Logger logger = createLogger(); errorHandler = new StfErrorHandler(logger); StfCommanderContext.create(logger) .map(context -> StfCommander.create(context, new HelpCommandCreatorImpl(), errorHandler, args)) .subscribe(StfCommander::execute, errorHandler::handle); } static class StfErrorHandler implements ErrorHandler { private final Logger logger; StfErrorHandler(Logger logger) { this.logger = logger; } @Override public void handle(Throwable throwable) { if (throwable instanceof EmptyDevicesException) { logger.log(Level.INFO ,"There's no devices");
} else if (throwable instanceof UnknownCommandException) {
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/commands/connect/ParamsConnector.java
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // }
import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.AdbRunner; import io.reactivex.Notification; import org.reactivestreams.Publisher; import java.util.logging.Logger;
package com.github.e13mort.stf.console.commands.connect; class ParamsConnector extends DeviceConnector { private final DevicesParams params;
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/commands/connect/ParamsConnector.java import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.AdbRunner; import io.reactivex.Notification; import org.reactivestreams.Publisher; import java.util.logging.Logger; package com.github.e13mort.stf.console.commands.connect; class ParamsConnector extends DeviceConnector { private final DevicesParams params;
protected ParamsConnector(FarmClient client, AdbRunner runner, Logger logger, DevicesParams params) {
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/StfCommander.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // }
import com.beust.jcommander.JCommander; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import io.reactivex.Completable;
package com.github.e13mort.stf.console; public class StfCommander { private final CommandContainer commandContainer; private final CommandContainer.Command defaultCommand; private final ErrorHandler errorHandler; private String commandName; private StfCommander( String commandName, CommandContainer commandContainer, CommandContainer.Command defaultCommand, ErrorHandler errorHandler) { this.commandName = commandName; this.commandContainer = commandContainer; this.defaultCommand = defaultCommand; this.errorHandler = errorHandler; }
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/StfCommander.java import com.beust.jcommander.JCommander; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import io.reactivex.Completable; package com.github.e13mort.stf.console; public class StfCommander { private final CommandContainer commandContainer; private final CommandContainer.Command defaultCommand; private final ErrorHandler errorHandler; private String commandName; private StfCommander( String commandName, CommandContainer commandContainer, CommandContainer.Command defaultCommand, ErrorHandler errorHandler) { this.commandName = commandName; this.commandContainer = commandContainer; this.defaultCommand = defaultCommand; this.errorHandler = errorHandler; }
static StfCommander create(StfCommanderContext context, HelpCommandCreator commandCreator, ErrorHandler errorHandler, String... args) {
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/StfCommander.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // }
import com.beust.jcommander.JCommander; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import io.reactivex.Completable;
this.commandContainer = commandContainer; this.defaultCommand = defaultCommand; this.errorHandler = errorHandler; } static StfCommander create(StfCommanderContext context, HelpCommandCreator commandCreator, ErrorHandler errorHandler, String... args) { CommandContainer commandContainer = new CommandContainer(context); JCommander commander = createCommander(commandContainer, args); final CommandContainer.Command helpCommand = commandCreator.createHelpCommand(commander); return new StfCommander(commander.getParsedCommand(), commandContainer, helpCommand, errorHandler); } private static JCommander createCommander(CommandContainer commandContainer, String[] args) { JCommander.Builder builder = JCommander.newBuilder(); for (String operation : commandContainer.getAllCommands()) { CommandContainer.Command command = commandContainer.getCommand(operation); builder.addCommand(operation, command); } JCommander commander = builder.build(); commander.setProgramName("stf"); commander.setCaseSensitiveOptions(false); commander.parseWithoutValidation(args); return commander; } void execute() { CommandContainer.Command command = chooseCommand(); if (command != null) { run(command.execute()); } else {
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/StfCommander.java import com.beust.jcommander.JCommander; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import io.reactivex.Completable; this.commandContainer = commandContainer; this.defaultCommand = defaultCommand; this.errorHandler = errorHandler; } static StfCommander create(StfCommanderContext context, HelpCommandCreator commandCreator, ErrorHandler errorHandler, String... args) { CommandContainer commandContainer = new CommandContainer(context); JCommander commander = createCommander(commandContainer, args); final CommandContainer.Command helpCommand = commandCreator.createHelpCommand(commander); return new StfCommander(commander.getParsedCommand(), commandContainer, helpCommand, errorHandler); } private static JCommander createCommander(CommandContainer commandContainer, String[] args) { JCommander.Builder builder = JCommander.newBuilder(); for (String operation : commandContainer.getAllCommands()) { CommandContainer.Command command = commandContainer.getCommand(operation); builder.addCommand(operation, command); } JCommander commander = builder.build(); commander.setProgramName("stf"); commander.setCaseSensitiveOptions(false); commander.parseWithoutValidation(args); return commander; } void execute() { CommandContainer.Command command = chooseCommand(); if (command != null) { run(command.execute()); } else {
errorHandler.handle(new UnknownCommandException(commandName));
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/commands/devices/DocumentsLoader.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // }
import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import io.reactivex.Flowable; import java.util.Collection;
package com.github.e13mort.stf.console.commands.devices; class DocumentsLoader { private final FarmClient client; private final DevicesParams params; private DeviceMapper fieldsReader = DeviceMapper.EMPTY;
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/commands/devices/DocumentsLoader.java import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import io.reactivex.Flowable; import java.util.Collection; package com.github.e13mort.stf.console.commands.devices; class DocumentsLoader { private final FarmClient client; private final DevicesParams params; private DeviceMapper fieldsReader = DeviceMapper.EMPTY;
private DeviceListCache deviceListCache = DeviceListCache.EMPTY;
e13mort/stf-console-client
client/src/test/java/com/github/e13mort/stf/console/StfCommanderTest.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // }
import com.beust.jcommander.ParameterException; import com.github.e13mort.stf.adapter.filters.StringsFilterDescription; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.UnknownCommandException; import io.reactivex.Flowable; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import java.io.IOException; import java.util.Arrays; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertLinesMatch; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
@EnumSource(DeviceParamsProducingCommand.class) void testVoidNameThrowsAnException(DeviceParamsProducingCommand source) { assertThrows(Exception.class, test(source, "-n")); } @DisplayName("Call app without any param will execute the help command") @Test void testEmptyCommandParamsWillExecuteHelp() throws Exception { createCommander("").execute(); verify(helpCommand).execute(); } @DisplayName("Call app without any param will execute the help command") @Test void test() throws Exception { createCommander("unknown").execute(); verify(helpCommand).execute(); } @DisplayName("Provider = p1 is parsed in command") @ParameterizedTest(name = "Command is {0}") @EnumSource(DeviceParamsProducingCommand.class) void testProviderDescriptionNotNullWithParameter(DeviceParamsProducingCommand source) throws Exception { DevicesParams params = runDeviceParamsTest(source, "-provider p1"); assertNotNull(params.getProviderFilterDescription()); } @DisplayName("Serial = serial1,serial2 is parsed in command") @ParameterizedTest(name = "Command is {0}") @EnumSource(DeviceParamsProducingCommand.class)
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // Path: client/src/test/java/com/github/e13mort/stf/console/StfCommanderTest.java import com.beust.jcommander.ParameterException; import com.github.e13mort.stf.adapter.filters.StringsFilterDescription; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.UnknownCommandException; import io.reactivex.Flowable; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import java.io.IOException; import java.util.Arrays; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertLinesMatch; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @EnumSource(DeviceParamsProducingCommand.class) void testVoidNameThrowsAnException(DeviceParamsProducingCommand source) { assertThrows(Exception.class, test(source, "-n")); } @DisplayName("Call app without any param will execute the help command") @Test void testEmptyCommandParamsWillExecuteHelp() throws Exception { createCommander("").execute(); verify(helpCommand).execute(); } @DisplayName("Call app without any param will execute the help command") @Test void test() throws Exception { createCommander("unknown").execute(); verify(helpCommand).execute(); } @DisplayName("Provider = p1 is parsed in command") @ParameterizedTest(name = "Command is {0}") @EnumSource(DeviceParamsProducingCommand.class) void testProviderDescriptionNotNullWithParameter(DeviceParamsProducingCommand source) throws Exception { DevicesParams params = runDeviceParamsTest(source, "-provider p1"); assertNotNull(params.getProviderFilterDescription()); } @DisplayName("Serial = serial1,serial2 is parsed in command") @ParameterizedTest(name = "Command is {0}") @EnumSource(DeviceParamsProducingCommand.class)
void testSerialNumberDescriptionNotNullWithParameter(DeviceParamsProducingCommand source) throws IOException, UnknownCommandException {
e13mort/stf-console-client
client/src/test/java/com/github/e13mort/stf/console/BaseStfCommanderTest.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // }
import com.beust.jcommander.JCommander; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Completable; import io.reactivex.Flowable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.function.Executable; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.logging.Logger; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package com.github.e13mort.stf.console; public class BaseStfCommanderTest { protected static final String TEST_DEVICE_REMOTE = "127.0.0.1:15500"; @Mock protected FarmClient farmClient; @Mock protected AdbRunner adbRunner; @Mock
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // } // Path: client/src/test/java/com/github/e13mort/stf/console/BaseStfCommanderTest.java import com.beust.jcommander.JCommander; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Completable; import io.reactivex.Flowable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.function.Executable; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.logging.Logger; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package com.github.e13mort.stf.console; public class BaseStfCommanderTest { protected static final String TEST_DEVICE_REMOTE = "127.0.0.1:15500"; @Mock protected FarmClient farmClient; @Mock protected AdbRunner adbRunner; @Mock
protected CommandContainer.Command helpCommand;
e13mort/stf-console-client
client/src/test/java/com/github/e13mort/stf/console/BaseStfCommanderTest.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // }
import com.beust.jcommander.JCommander; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Completable; import io.reactivex.Flowable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.function.Executable; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.logging.Logger; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package com.github.e13mort.stf.console; public class BaseStfCommanderTest { protected static final String TEST_DEVICE_REMOTE = "127.0.0.1:15500"; @Mock protected FarmClient farmClient; @Mock protected AdbRunner adbRunner; @Mock protected CommandContainer.Command helpCommand; @Mock
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // } // Path: client/src/test/java/com/github/e13mort/stf/console/BaseStfCommanderTest.java import com.beust.jcommander.JCommander; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Completable; import io.reactivex.Flowable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.function.Executable; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.logging.Logger; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package com.github.e13mort.stf.console; public class BaseStfCommanderTest { protected static final String TEST_DEVICE_REMOTE = "127.0.0.1:15500"; @Mock protected FarmClient farmClient; @Mock protected AdbRunner adbRunner; @Mock protected CommandContainer.Command helpCommand; @Mock
protected DeviceListCache cache;
e13mort/stf-console-client
client/src/test/java/com/github/e13mort/stf/console/BaseStfCommanderTest.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // }
import com.beust.jcommander.JCommander; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Completable; import io.reactivex.Flowable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.function.Executable; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.logging.Logger; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package com.github.e13mort.stf.console; public class BaseStfCommanderTest { protected static final String TEST_DEVICE_REMOTE = "127.0.0.1:15500"; @Mock protected FarmClient farmClient; @Mock protected AdbRunner adbRunner; @Mock protected CommandContainer.Command helpCommand; @Mock protected DeviceListCache cache; @Mock protected ErrorHandler errorHandler; @Mock protected DeviceListCache.CacheTransaction cacheTransaction; @Mock
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // } // Path: client/src/test/java/com/github/e13mort/stf/console/BaseStfCommanderTest.java import com.beust.jcommander.JCommander; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Completable; import io.reactivex.Flowable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.function.Executable; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.logging.Logger; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package com.github.e13mort.stf.console; public class BaseStfCommanderTest { protected static final String TEST_DEVICE_REMOTE = "127.0.0.1:15500"; @Mock protected FarmClient farmClient; @Mock protected AdbRunner adbRunner; @Mock protected CommandContainer.Command helpCommand; @Mock protected DeviceListCache cache; @Mock protected ErrorHandler errorHandler; @Mock protected DeviceListCache.CacheTransaction cacheTransaction; @Mock
private HelpCommandCreator helpCommandCreator;
e13mort/stf-console-client
client/src/test/java/com/github/e13mort/stf/console/BaseStfCommanderTest.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // }
import com.beust.jcommander.JCommander; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Completable; import io.reactivex.Flowable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.function.Executable; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.logging.Logger; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
protected CommandContainer.Command helpCommand; @Mock protected DeviceListCache cache; @Mock protected ErrorHandler errorHandler; @Mock protected DeviceListCache.CacheTransaction cacheTransaction; @Mock private HelpCommandCreator helpCommandCreator; @Mock protected OutputStream outputStream; @Mock protected Logger logger; @Mock private Device myDevice; @BeforeEach protected void setUp() throws IOException { MockitoAnnotations.initMocks(this); when(farmClient.getDevices(any(DevicesParams.class))).thenReturn(Flowable.empty()); when(farmClient.connectToDevices(any(DevicesParams.class))).thenReturn(Flowable.empty()); when(farmClient.disconnectFromAllDevices()).thenReturn(Flowable.empty()); when(helpCommand.execute()).thenReturn(Completable.complete()); when(helpCommandCreator.createHelpCommand(any(JCommander.class))).thenReturn(helpCommand); when(farmClient.getMyDevices()).thenReturn(Flowable.fromArray(myDevice)); when(myDevice.getRemoteConnectUrl()).thenReturn(TEST_DEVICE_REMOTE); when(cache.beginTransaction()).thenReturn(cacheTransaction); when(cache.getCachedFiles()).thenReturn(Collections.emptyList()); }
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/HelpCommandCreator.java // public interface HelpCommandCreator { // CommandContainer.Command createHelpCommand(JCommander commander); // // class HelpCommandCreatorImpl implements HelpCommandCreator { // @Override // public CommandContainer.Command createHelpCommand(JCommander commander) { // return new HelpCommand(commander); // } // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/UnknownCommandException.java // public class UnknownCommandException extends Exception { // public UnknownCommandException(String message) { // super(message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // } // Path: client/src/test/java/com/github/e13mort/stf/console/BaseStfCommanderTest.java import com.beust.jcommander.JCommander; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.HelpCommandCreator; import com.github.e13mort.stf.console.commands.UnknownCommandException; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import com.github.e13mort.stf.model.device.Device; import io.reactivex.Completable; import io.reactivex.Flowable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.function.Executable; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.logging.Logger; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; protected CommandContainer.Command helpCommand; @Mock protected DeviceListCache cache; @Mock protected ErrorHandler errorHandler; @Mock protected DeviceListCache.CacheTransaction cacheTransaction; @Mock private HelpCommandCreator helpCommandCreator; @Mock protected OutputStream outputStream; @Mock protected Logger logger; @Mock private Device myDevice; @BeforeEach protected void setUp() throws IOException { MockitoAnnotations.initMocks(this); when(farmClient.getDevices(any(DevicesParams.class))).thenReturn(Flowable.empty()); when(farmClient.connectToDevices(any(DevicesParams.class))).thenReturn(Flowable.empty()); when(farmClient.disconnectFromAllDevices()).thenReturn(Flowable.empty()); when(helpCommand.execute()).thenReturn(Completable.complete()); when(helpCommandCreator.createHelpCommand(any(JCommander.class))).thenReturn(helpCommand); when(farmClient.getMyDevices()).thenReturn(Flowable.fromArray(myDevice)); when(myDevice.getRemoteConnectUrl()).thenReturn(TEST_DEVICE_REMOTE); when(cache.beginTransaction()).thenReturn(cacheTransaction); when(cache.getCachedFiles()).thenReturn(Collections.emptyList()); }
protected DevicesParams runDeviceParamsTest(DeviceParamsProducingCommand source, String params) throws IOException, UnknownCommandException {
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/commands/devices/DevicesCommand.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/ConsoleDeviceParamsImpl.java // public class ConsoleDeviceParamsImpl implements DevicesParams { // @Parameter(names = "--all", description = "Show all devices. By default only available devices are returned.") // private boolean allDevices; // @Parameter(names = "-abi", description = "Filter by device abi architecture") // private String abi; // @Parameter(names = "-api", description = "Filter by device api level") // private int apiVersion; // @Parameter(names = "-minApi", description = "Filter by device min api level") // private int minApiVersion; // @Parameter(names = "-maxApi", description = "Filter by device max api level") // private int maxApiVersion; // @Parameter(names = "-count", description = "Filter devices by count") // private int count; // @Parameter(names = "-name", description = "Filter devices by its name", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription nameFilterDescription; // @Parameter(names = "-provider", description = "Filter devices by provider", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription providerFilterDescription; // @Parameter(names = "-serial", description = "Filter devices by serial number", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription serialFilterDescription; // // @Override // public boolean isAllDevices() { // return allDevices; // } // // @Override // public String getAbi() { // return abi; // } // // @Override // public int getApiVersion() { // return apiVersion; // } // // @Override // public int getMinApiVersion() { // return minApiVersion; // } // // @Override // public int getMaxApiVersion() { // return maxApiVersion; // } // // @Override // public int getCount() { // return count; // } // // @Override // public StringsFilterDescription getNameFilterDescription() { // return nameFilterDescription; // } // // @Override // public StringsFilterDescription getProviderFilterDescription() { // return providerFilterDescription; // } // // @Override // public StringsFilterDescription getSerialFilterDescription() { // return serialFilterDescription; // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // }
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.beust.jcommander.ParametersDelegate; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.ConsoleDeviceParamsImpl; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import io.reactivex.Completable; import java.io.OutputStream;
package com.github.e13mort.stf.console.commands.devices; @Parameters(commandDescription = "Print list of available devices") public class DevicesCommand implements CommandContainer.Command { private final FarmClient client; private final OutputStream output; @ParametersDelegate
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/ConsoleDeviceParamsImpl.java // public class ConsoleDeviceParamsImpl implements DevicesParams { // @Parameter(names = "--all", description = "Show all devices. By default only available devices are returned.") // private boolean allDevices; // @Parameter(names = "-abi", description = "Filter by device abi architecture") // private String abi; // @Parameter(names = "-api", description = "Filter by device api level") // private int apiVersion; // @Parameter(names = "-minApi", description = "Filter by device min api level") // private int minApiVersion; // @Parameter(names = "-maxApi", description = "Filter by device max api level") // private int maxApiVersion; // @Parameter(names = "-count", description = "Filter devices by count") // private int count; // @Parameter(names = "-name", description = "Filter devices by its name", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription nameFilterDescription; // @Parameter(names = "-provider", description = "Filter devices by provider", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription providerFilterDescription; // @Parameter(names = "-serial", description = "Filter devices by serial number", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription serialFilterDescription; // // @Override // public boolean isAllDevices() { // return allDevices; // } // // @Override // public String getAbi() { // return abi; // } // // @Override // public int getApiVersion() { // return apiVersion; // } // // @Override // public int getMinApiVersion() { // return minApiVersion; // } // // @Override // public int getMaxApiVersion() { // return maxApiVersion; // } // // @Override // public int getCount() { // return count; // } // // @Override // public StringsFilterDescription getNameFilterDescription() { // return nameFilterDescription; // } // // @Override // public StringsFilterDescription getProviderFilterDescription() { // return providerFilterDescription; // } // // @Override // public StringsFilterDescription getSerialFilterDescription() { // return serialFilterDescription; // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/commands/devices/DevicesCommand.java import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.beust.jcommander.ParametersDelegate; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.ConsoleDeviceParamsImpl; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import io.reactivex.Completable; import java.io.OutputStream; package com.github.e13mort.stf.console.commands.devices; @Parameters(commandDescription = "Print list of available devices") public class DevicesCommand implements CommandContainer.Command { private final FarmClient client; private final OutputStream output; @ParametersDelegate
private DevicesParams params = new ConsoleDeviceParamsImpl();
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/commands/devices/DevicesCommand.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/ConsoleDeviceParamsImpl.java // public class ConsoleDeviceParamsImpl implements DevicesParams { // @Parameter(names = "--all", description = "Show all devices. By default only available devices are returned.") // private boolean allDevices; // @Parameter(names = "-abi", description = "Filter by device abi architecture") // private String abi; // @Parameter(names = "-api", description = "Filter by device api level") // private int apiVersion; // @Parameter(names = "-minApi", description = "Filter by device min api level") // private int minApiVersion; // @Parameter(names = "-maxApi", description = "Filter by device max api level") // private int maxApiVersion; // @Parameter(names = "-count", description = "Filter devices by count") // private int count; // @Parameter(names = "-name", description = "Filter devices by its name", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription nameFilterDescription; // @Parameter(names = "-provider", description = "Filter devices by provider", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription providerFilterDescription; // @Parameter(names = "-serial", description = "Filter devices by serial number", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription serialFilterDescription; // // @Override // public boolean isAllDevices() { // return allDevices; // } // // @Override // public String getAbi() { // return abi; // } // // @Override // public int getApiVersion() { // return apiVersion; // } // // @Override // public int getMinApiVersion() { // return minApiVersion; // } // // @Override // public int getMaxApiVersion() { // return maxApiVersion; // } // // @Override // public int getCount() { // return count; // } // // @Override // public StringsFilterDescription getNameFilterDescription() { // return nameFilterDescription; // } // // @Override // public StringsFilterDescription getProviderFilterDescription() { // return providerFilterDescription; // } // // @Override // public StringsFilterDescription getSerialFilterDescription() { // return serialFilterDescription; // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // }
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.beust.jcommander.ParametersDelegate; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.ConsoleDeviceParamsImpl; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import io.reactivex.Completable; import java.io.OutputStream;
package com.github.e13mort.stf.console.commands.devices; @Parameters(commandDescription = "Print list of available devices") public class DevicesCommand implements CommandContainer.Command { private final FarmClient client; private final OutputStream output; @ParametersDelegate private DevicesParams params = new ConsoleDeviceParamsImpl(); @Parameter(names = {"--my-columns"}, description = "<BETA> Use columns from web panel") private boolean userColumns;
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/CommandContainer.java // public class CommandContainer { // // private Map<String, Command> commandMap = new HashMap<>(); // // public CommandContainer(StfCommanderContext c) { // commandMap.put("devices", new DevicesCommand(c.getClient(), c.getCache(), c.getOutput())); // commandMap.put("connect", new ConnectCommand(c.getClient(), c.getAdbRunner(), c.getCache(), c.getLogger())); // commandMap.put("disconnect", new DisconnectCommand(c.getClient(), c.getLogger())); // } // // public Command getCommand(String operation) { // return commandMap.get(operation); // } // // public Collection<String> getAllCommands() { // return commandMap.keySet(); // } // // public interface Command { // Completable execute(); // } // // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/ConsoleDeviceParamsImpl.java // public class ConsoleDeviceParamsImpl implements DevicesParams { // @Parameter(names = "--all", description = "Show all devices. By default only available devices are returned.") // private boolean allDevices; // @Parameter(names = "-abi", description = "Filter by device abi architecture") // private String abi; // @Parameter(names = "-api", description = "Filter by device api level") // private int apiVersion; // @Parameter(names = "-minApi", description = "Filter by device min api level") // private int minApiVersion; // @Parameter(names = "-maxApi", description = "Filter by device max api level") // private int maxApiVersion; // @Parameter(names = "-count", description = "Filter devices by count") // private int count; // @Parameter(names = "-name", description = "Filter devices by its name", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription nameFilterDescription; // @Parameter(names = "-provider", description = "Filter devices by provider", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription providerFilterDescription; // @Parameter(names = "-serial", description = "Filter devices by serial number", converter = FilterDescriptionConverterImpl.class) // private StringsFilterDescription serialFilterDescription; // // @Override // public boolean isAllDevices() { // return allDevices; // } // // @Override // public String getAbi() { // return abi; // } // // @Override // public int getApiVersion() { // return apiVersion; // } // // @Override // public int getMinApiVersion() { // return minApiVersion; // } // // @Override // public int getMaxApiVersion() { // return maxApiVersion; // } // // @Override // public int getCount() { // return count; // } // // @Override // public StringsFilterDescription getNameFilterDescription() { // return nameFilterDescription; // } // // @Override // public StringsFilterDescription getProviderFilterDescription() { // return providerFilterDescription; // } // // @Override // public StringsFilterDescription getSerialFilterDescription() { // return serialFilterDescription; // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/commands/devices/DevicesCommand.java import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.beust.jcommander.ParametersDelegate; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.console.commands.CommandContainer; import com.github.e13mort.stf.console.commands.ConsoleDeviceParamsImpl; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import io.reactivex.Completable; import java.io.OutputStream; package com.github.e13mort.stf.console.commands.devices; @Parameters(commandDescription = "Print list of available devices") public class DevicesCommand implements CommandContainer.Command { private final FarmClient client; private final OutputStream output; @ParametersDelegate private DevicesParams params = new ConsoleDeviceParamsImpl(); @Parameter(names = {"--my-columns"}, description = "<BETA> Use columns from web panel") private boolean userColumns;
private DeviceListCache cache;
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/commands/connect/DeviceConnector.java
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/EmptyDevicesException.java // public class EmptyDevicesException extends Exception { }
import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.console.AdbRunner; import com.github.e13mort.stf.console.commands.EmptyDevicesException; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.Notification; import org.reactivestreams.Publisher; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger;
package com.github.e13mort.stf.console.commands.connect; abstract class DeviceConnector { protected final FarmClient client;
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/EmptyDevicesException.java // public class EmptyDevicesException extends Exception { } // Path: client/src/main/java/com/github/e13mort/stf/console/commands/connect/DeviceConnector.java import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.console.AdbRunner; import com.github.e13mort.stf.console.commands.EmptyDevicesException; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.Notification; import org.reactivestreams.Publisher; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; package com.github.e13mort.stf.console.commands.connect; abstract class DeviceConnector { protected final FarmClient client;
protected final AdbRunner runner;
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/commands/connect/DeviceConnector.java
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/EmptyDevicesException.java // public class EmptyDevicesException extends Exception { }
import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.console.AdbRunner; import com.github.e13mort.stf.console.commands.EmptyDevicesException; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.Notification; import org.reactivestreams.Publisher; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger;
package com.github.e13mort.stf.console.commands.connect; abstract class DeviceConnector { protected final FarmClient client; protected final AdbRunner runner; protected final Logger logger; protected DeviceConnector(FarmClient client, AdbRunner runner, Logger logger) { this.client = client; this.runner = runner; this.logger = logger; } Completable connect() { return Completable.fromPublisher(createConnectionPublisher()); } protected abstract Publisher<Notification<String>> createConnectionPublisher(); protected Flowable<Notification<String>> getEmptyError() {
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // } // // Path: client/src/main/java/com/github/e13mort/stf/console/commands/EmptyDevicesException.java // public class EmptyDevicesException extends Exception { } // Path: client/src/main/java/com/github/e13mort/stf/console/commands/connect/DeviceConnector.java import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.console.AdbRunner; import com.github.e13mort.stf.console.commands.EmptyDevicesException; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.Notification; import org.reactivestreams.Publisher; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; package com.github.e13mort.stf.console.commands.connect; abstract class DeviceConnector { protected final FarmClient client; protected final AdbRunner runner; protected final Logger logger; protected DeviceConnector(FarmClient client, AdbRunner runner, Logger logger) { this.client = client; this.runner = runner; this.logger = logger; } Completable connect() { return Completable.fromPublisher(createConnectionPublisher()); } protected abstract Publisher<Notification<String>> createConnectionPublisher(); protected Flowable<Notification<String>> getEmptyError() {
return Flowable.error(new EmptyDevicesException());
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/commands/connect/FileParamsDeviceConnector.java
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // }
import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.client.parameters.JsonDeviceParametersReader; import com.github.e13mort.stf.console.AdbRunner; import org.reactivestreams.Publisher; import java.io.File; import java.net.URL; import java.util.logging.Logger; import io.reactivex.Flowable; import io.reactivex.Notification;
package com.github.e13mort.stf.console.commands.connect; class FileParamsDeviceConnector extends DeviceConnector { private final ParametersReader reader;
// Path: client/src/main/java/com/github/e13mort/stf/console/AdbRunner.java // public class AdbRunner { // private static final String ADB_DIRECTORY = "platform-tools"; // private final String androidSdkPath; // private static final String TAG_ADB = "ADB"; // private final Logger logger; // // AdbRunner(String androidSdkPath, Logger logger) { // if (androidSdkPath == null) { // androidSdkPath = ""; // } // this.androidSdkPath = androidSdkPath; // this.logger = logger; // } // // public void connectToDevice(String connectionUrl) throws IOException { // runComplexCommand("adb", "connect", connectionUrl); // runComplexCommand("adb", "wait-for-device"); // } // // private void runComplexCommand(String... params) throws IOException { // File adb = new File(androidSdkPath + File.separator + ADB_DIRECTORY); // Process exec = new ProcessBuilder(params) // .directory(adb) // .start(); // runProcess(exec); // } // // private void runProcess(Process process) throws IOException { // final InputStream stream = process.getInputStream(); // final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // try { // String line; // while ((line = reader.readLine()) != null) { // log(TAG_ADB, line); // } // } catch (IOException e) { // log(e); // } finally { // reader.close(); // stream.close(); // } // } // // private void log(Exception e) { // logger.log(Level.INFO, "message {0}", e.getMessage()); // } // // private void log(String tag, String message) { // logger.info(tag + ": " + message); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/commands/connect/FileParamsDeviceConnector.java import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.parameters.DevicesParams; import com.github.e13mort.stf.client.parameters.JsonDeviceParametersReader; import com.github.e13mort.stf.console.AdbRunner; import org.reactivestreams.Publisher; import java.io.File; import java.net.URL; import java.util.logging.Logger; import io.reactivex.Flowable; import io.reactivex.Notification; package com.github.e13mort.stf.console.commands.connect; class FileParamsDeviceConnector extends DeviceConnector { private final ParametersReader reader;
static DeviceConnector of(FarmClient client, AdbRunner adbRunner, Logger logger, File paramsFile) {
e13mort/stf-console-client
client/src/main/java/com/github/e13mort/stf/console/StfCommanderContext.java
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // }
import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.FarmInfo; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import io.reactivex.Single; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; import java.util.logging.Logger;
package com.github.e13mort.stf.console; public class StfCommanderContext { private static final String DEFAULT_PROPERTY_FILE_NAME = "farm.properties"; private final FarmClient client; private final AdbRunner adbRunner;
// Path: client/src/main/java/com/github/e13mort/stf/console/commands/cache/DeviceListCache.java // public interface DeviceListCache { // static DeviceListCache getCache() { // return new DeviceListCacheImpl(); // } // // DeviceListCache EMPTY = new DeviceListCache() { // @Override // public CacheTransaction beginTransaction() { // return CacheTransaction.EMPTY; // } // // @Override // public List<Device> getCachedFiles() { // return Collections.emptyList(); // } // }; // // CacheTransaction beginTransaction(); // // List<Device> getCachedFiles(); // // interface CacheTransaction { // CacheTransaction EMPTY = new CacheTransaction() { // @Override // public void addDevice(Device device) { // // } // // @Override // public void save() { // // } // }; // // void addDevice(Device device); // // void save(); // } // } // Path: client/src/main/java/com/github/e13mort/stf/console/StfCommanderContext.java import com.github.e13mort.stf.client.FarmClient; import com.github.e13mort.stf.client.FarmInfo; import com.github.e13mort.stf.console.commands.cache.DeviceListCache; import io.reactivex.Single; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; import java.util.logging.Logger; package com.github.e13mort.stf.console; public class StfCommanderContext { private static final String DEFAULT_PROPERTY_FILE_NAME = "farm.properties"; private final FarmClient client; private final AdbRunner adbRunner;
private DeviceListCache cache;
janishar/Tutorials
GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/MainActivity.java
// Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/gallery/ImageTypeBig.java // @NonReusable // @Layout(R.layout.gallery_item_big) // public class ImageTypeBig { // // @View(R.id.imageView) // private ImageView imageView; // // private String mUlr; // private Context mContext; // private PlaceHolderView mPlaceHolderView; // // public ImageTypeBig(Context context, PlaceHolderView placeHolderView, String ulr) { // mContext = context; // mPlaceHolderView = placeHolderView; // mUlr = ulr; // } // // @Resolve // private void onResolved() { // Glide.with(mContext).load(mUlr).into(imageView); // } // // @LongClick(R.id.imageView) // private void onLongClick(){ // mPlaceHolderView.removeView(this); // } // } // // Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/gallery/ImageTypeSmallList.java // @Animate(Animation.CARD_TOP_IN_DESC) // @NonReusable // @Layout(R.layout.gallery_item_small_list) // public class ImageTypeSmallList { // // @View(R.id.placeholderview) // private PlaceHolderView mPlaceHolderView; // // private Context mContext; // private List<Image> mImageList; // // public ImageTypeSmallList(Context context, List<Image> imageList) { // mContext = context; // mImageList = imageList; // } // // @Resolve // private void onResolved() { // mPlaceHolderView.getBuilder() // .setHasFixedSize(false) // .setItemViewCacheSize(10) // .setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)); // // for(Image image : mImageList) { // mPlaceHolderView.addView(new ImageTypeSmall(mContext, mPlaceHolderView, image.getImageUrl())); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.mindorks.placeholderview.PlaceHolderView; import java.util.ArrayList; import java.util.List; import test.mindorks.gallery.gallerytest.gallery.ImageTypeBig; import test.mindorks.gallery.gallerytest.gallery.ImageTypeSmallList;
package test.mindorks.gallery.gallerytest; public class MainActivity extends AppCompatActivity { private PlaceHolderView mGalleryView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGalleryView = (PlaceHolderView)findViewById(R.id.galleryView); setupGallery(); findViewById(R.id.remove).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mGalleryView.removeAllViews(); } }); } private void setupGallery(){ List<Image> imageList = Utils.loadImages(this.getApplicationContext()); List<Image> newImageList = new ArrayList<>(); for (int i = 0; i < (imageList.size() > 10 ? 10 : imageList.size()); i++) { newImageList.add(imageList.get(i)); }
// Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/gallery/ImageTypeBig.java // @NonReusable // @Layout(R.layout.gallery_item_big) // public class ImageTypeBig { // // @View(R.id.imageView) // private ImageView imageView; // // private String mUlr; // private Context mContext; // private PlaceHolderView mPlaceHolderView; // // public ImageTypeBig(Context context, PlaceHolderView placeHolderView, String ulr) { // mContext = context; // mPlaceHolderView = placeHolderView; // mUlr = ulr; // } // // @Resolve // private void onResolved() { // Glide.with(mContext).load(mUlr).into(imageView); // } // // @LongClick(R.id.imageView) // private void onLongClick(){ // mPlaceHolderView.removeView(this); // } // } // // Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/gallery/ImageTypeSmallList.java // @Animate(Animation.CARD_TOP_IN_DESC) // @NonReusable // @Layout(R.layout.gallery_item_small_list) // public class ImageTypeSmallList { // // @View(R.id.placeholderview) // private PlaceHolderView mPlaceHolderView; // // private Context mContext; // private List<Image> mImageList; // // public ImageTypeSmallList(Context context, List<Image> imageList) { // mContext = context; // mImageList = imageList; // } // // @Resolve // private void onResolved() { // mPlaceHolderView.getBuilder() // .setHasFixedSize(false) // .setItemViewCacheSize(10) // .setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)); // // for(Image image : mImageList) { // mPlaceHolderView.addView(new ImageTypeSmall(mContext, mPlaceHolderView, image.getImageUrl())); // } // } // } // Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/MainActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.mindorks.placeholderview.PlaceHolderView; import java.util.ArrayList; import java.util.List; import test.mindorks.gallery.gallerytest.gallery.ImageTypeBig; import test.mindorks.gallery.gallerytest.gallery.ImageTypeSmallList; package test.mindorks.gallery.gallerytest; public class MainActivity extends AppCompatActivity { private PlaceHolderView mGalleryView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGalleryView = (PlaceHolderView)findViewById(R.id.galleryView); setupGallery(); findViewById(R.id.remove).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mGalleryView.removeAllViews(); } }); } private void setupGallery(){ List<Image> imageList = Utils.loadImages(this.getApplicationContext()); List<Image> newImageList = new ArrayList<>(); for (int i = 0; i < (imageList.size() > 10 ? 10 : imageList.size()); i++) { newImageList.add(imageList.get(i)); }
mGalleryView.addView(new ImageTypeSmallList(this.getApplicationContext(), newImageList));
janishar/Tutorials
GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/MainActivity.java
// Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/gallery/ImageTypeBig.java // @NonReusable // @Layout(R.layout.gallery_item_big) // public class ImageTypeBig { // // @View(R.id.imageView) // private ImageView imageView; // // private String mUlr; // private Context mContext; // private PlaceHolderView mPlaceHolderView; // // public ImageTypeBig(Context context, PlaceHolderView placeHolderView, String ulr) { // mContext = context; // mPlaceHolderView = placeHolderView; // mUlr = ulr; // } // // @Resolve // private void onResolved() { // Glide.with(mContext).load(mUlr).into(imageView); // } // // @LongClick(R.id.imageView) // private void onLongClick(){ // mPlaceHolderView.removeView(this); // } // } // // Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/gallery/ImageTypeSmallList.java // @Animate(Animation.CARD_TOP_IN_DESC) // @NonReusable // @Layout(R.layout.gallery_item_small_list) // public class ImageTypeSmallList { // // @View(R.id.placeholderview) // private PlaceHolderView mPlaceHolderView; // // private Context mContext; // private List<Image> mImageList; // // public ImageTypeSmallList(Context context, List<Image> imageList) { // mContext = context; // mImageList = imageList; // } // // @Resolve // private void onResolved() { // mPlaceHolderView.getBuilder() // .setHasFixedSize(false) // .setItemViewCacheSize(10) // .setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)); // // for(Image image : mImageList) { // mPlaceHolderView.addView(new ImageTypeSmall(mContext, mPlaceHolderView, image.getImageUrl())); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.mindorks.placeholderview.PlaceHolderView; import java.util.ArrayList; import java.util.List; import test.mindorks.gallery.gallerytest.gallery.ImageTypeBig; import test.mindorks.gallery.gallerytest.gallery.ImageTypeSmallList;
package test.mindorks.gallery.gallerytest; public class MainActivity extends AppCompatActivity { private PlaceHolderView mGalleryView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGalleryView = (PlaceHolderView)findViewById(R.id.galleryView); setupGallery(); findViewById(R.id.remove).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mGalleryView.removeAllViews(); } }); } private void setupGallery(){ List<Image> imageList = Utils.loadImages(this.getApplicationContext()); List<Image> newImageList = new ArrayList<>(); for (int i = 0; i < (imageList.size() > 10 ? 10 : imageList.size()); i++) { newImageList.add(imageList.get(i)); } mGalleryView.addView(new ImageTypeSmallList(this.getApplicationContext(), newImageList)); // Not recycler the sub lists mGalleryView.getRecycledViewPool().setMaxRecycledViews(R.layout.gallery_item_small_list, 0); for (int i = imageList.size() - 1; i >= 0; i--) {
// Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/gallery/ImageTypeBig.java // @NonReusable // @Layout(R.layout.gallery_item_big) // public class ImageTypeBig { // // @View(R.id.imageView) // private ImageView imageView; // // private String mUlr; // private Context mContext; // private PlaceHolderView mPlaceHolderView; // // public ImageTypeBig(Context context, PlaceHolderView placeHolderView, String ulr) { // mContext = context; // mPlaceHolderView = placeHolderView; // mUlr = ulr; // } // // @Resolve // private void onResolved() { // Glide.with(mContext).load(mUlr).into(imageView); // } // // @LongClick(R.id.imageView) // private void onLongClick(){ // mPlaceHolderView.removeView(this); // } // } // // Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/gallery/ImageTypeSmallList.java // @Animate(Animation.CARD_TOP_IN_DESC) // @NonReusable // @Layout(R.layout.gallery_item_small_list) // public class ImageTypeSmallList { // // @View(R.id.placeholderview) // private PlaceHolderView mPlaceHolderView; // // private Context mContext; // private List<Image> mImageList; // // public ImageTypeSmallList(Context context, List<Image> imageList) { // mContext = context; // mImageList = imageList; // } // // @Resolve // private void onResolved() { // mPlaceHolderView.getBuilder() // .setHasFixedSize(false) // .setItemViewCacheSize(10) // .setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)); // // for(Image image : mImageList) { // mPlaceHolderView.addView(new ImageTypeSmall(mContext, mPlaceHolderView, image.getImageUrl())); // } // } // } // Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/MainActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.mindorks.placeholderview.PlaceHolderView; import java.util.ArrayList; import java.util.List; import test.mindorks.gallery.gallerytest.gallery.ImageTypeBig; import test.mindorks.gallery.gallerytest.gallery.ImageTypeSmallList; package test.mindorks.gallery.gallerytest; public class MainActivity extends AppCompatActivity { private PlaceHolderView mGalleryView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGalleryView = (PlaceHolderView)findViewById(R.id.galleryView); setupGallery(); findViewById(R.id.remove).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mGalleryView.removeAllViews(); } }); } private void setupGallery(){ List<Image> imageList = Utils.loadImages(this.getApplicationContext()); List<Image> newImageList = new ArrayList<>(); for (int i = 0; i < (imageList.size() > 10 ? 10 : imageList.size()); i++) { newImageList.add(imageList.get(i)); } mGalleryView.addView(new ImageTypeSmallList(this.getApplicationContext(), newImageList)); // Not recycler the sub lists mGalleryView.getRecycledViewPool().setMaxRecycledViews(R.layout.gallery_item_small_list, 0); for (int i = imageList.size() - 1; i >= 0; i--) {
mGalleryView.addView(new ImageTypeBig(this.getApplicationContext(), mGalleryView, imageList.get(i).getImageUrl()));
janishar/Tutorials
GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/gallery/ImageTypeSmallList.java
// Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/Image.java // public class Image { // // @SerializedName("url") // @Expose // private String imageUrl; // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // }
import android.content.Context; import android.support.v7.widget.LinearLayoutManager; import com.mindorks.placeholderview.Animation; import com.mindorks.placeholderview.PlaceHolderView; import com.mindorks.placeholderview.annotations.Animate; import com.mindorks.placeholderview.annotations.Layout; import com.mindorks.placeholderview.annotations.NonReusable; import com.mindorks.placeholderview.annotations.Resolve; import com.mindorks.placeholderview.annotations.View; import java.util.List; import test.mindorks.gallery.gallerytest.Image; import test.mindorks.gallery.gallerytest.R;
package test.mindorks.gallery.gallerytest.gallery; /** * Created by janisharali on 19/08/16. */ @Animate(Animation.CARD_TOP_IN_DESC) @NonReusable @Layout(R.layout.gallery_item_small_list) public class ImageTypeSmallList { @View(R.id.placeholderview) private PlaceHolderView mPlaceHolderView; private Context mContext;
// Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/Image.java // public class Image { // // @SerializedName("url") // @Expose // private String imageUrl; // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // } // Path: GalleryTest/app/src/main/java/test/mindorks/gallery/gallerytest/gallery/ImageTypeSmallList.java import android.content.Context; import android.support.v7.widget.LinearLayoutManager; import com.mindorks.placeholderview.Animation; import com.mindorks.placeholderview.PlaceHolderView; import com.mindorks.placeholderview.annotations.Animate; import com.mindorks.placeholderview.annotations.Layout; import com.mindorks.placeholderview.annotations.NonReusable; import com.mindorks.placeholderview.annotations.Resolve; import com.mindorks.placeholderview.annotations.View; import java.util.List; import test.mindorks.gallery.gallerytest.Image; import test.mindorks.gallery.gallerytest.R; package test.mindorks.gallery.gallerytest.gallery; /** * Created by janisharali on 19/08/16. */ @Animate(Animation.CARD_TOP_IN_DESC) @NonReusable @Layout(R.layout.gallery_item_small_list) public class ImageTypeSmallList { @View(R.id.placeholderview) private PlaceHolderView mPlaceHolderView; private Context mContext;
private List<Image> mImageList;
eigengo/specs2-spring
src/main/java/org/specs2/spring/annotation/Jndi.java
// Path: src/main/java/org/specs2/spring/BlankJndiBuilder.java // public class BlankJndiBuilder implements JndiBuilder { // // public BlankJndiBuilder() { // // } // // public void build(Map<String, Object> environment) throws Exception { // // do nothing // } // } // // Path: src/main/java/org/specs2/spring/JndiBuilder.java // public interface JndiBuilder { // // /** // * Adds the items into the environment; the key in the map is the JNDI name; the value is the // * object associated with that name. // * // * @param environment the environment to be added to; never {@code null}. // * @throws Exception if the environment could not be built. // */ // void build(Map<String, Object> environment) throws Exception; // // }
import org.specs2.spring.BlankJndiBuilder; import org.specs2.spring.JndiBuilder; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy;
package org.specs2.spring.annotation; /** * Use this annotation on your tests to inject values into the JNDI environment for the * tests. * <p>You can specify any number of {@link #dataSources()}, {@link #mailSessions()}, * {@link #beans()}</p> * <p>In addition to these fairly standard items, you can specify {@link #builder()}, * which needs to be an implementation of the {@link org.specs2.spring.JndiBuilder} interface with * nullary constructor. The runtime will instantiate the given class and call its * {@link org.specs2.spring.JndiBuilder#build(java.util.Map)} method.</p> * * * @author janmmachacek */ @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface Jndi { /** * Specify any number of {@link javax.sql.DataSource} JNDI entries. * <p>Typically, you'd write something like * <code>@DataSource(name = "java:comp/env/jdbc/x", url = "jdbc:hsqldb:mem:x", username = "sa", password = "")</code>: * this would register a {@link javax.sql.DataSource} entry in the JNDI environment under name <code>java:comp/env/jdbc/x</code>, * with the given {@code url}, {@code username} and {@code password}. * </p> * * @return the data sources */ DataSource[] dataSources() default {}; /** * Specify any number of {@link javax.mail.Session} JNDI entries. * * @return the mail sessions */ MailSession[] mailSessions() default {}; /** * Specify any number of any objects as JNDI entries. The objects must have nullary constructors. * * @return the beans */ Bean[] beans() default {}; WorkManager[] workManagers() default {}; /** * Specify any number of {@link javax.transaction.TransactionManager} as JNDI entries. * * @return the transaction managers. */ TransactionManager[] transactionManager() default {}; /** * Configure the JMS environment; configure the queues, topics and connection factory. * * @return the JMS environment */ Jms[] jms() default {}; /** * If you require some complex environment setup, you can set this value. The type you specify here * must be an implementation of the {@link org.specs2.spring.JndiBuilder} with nullary constructor. * * @return the custom JndiBuilder */
// Path: src/main/java/org/specs2/spring/BlankJndiBuilder.java // public class BlankJndiBuilder implements JndiBuilder { // // public BlankJndiBuilder() { // // } // // public void build(Map<String, Object> environment) throws Exception { // // do nothing // } // } // // Path: src/main/java/org/specs2/spring/JndiBuilder.java // public interface JndiBuilder { // // /** // * Adds the items into the environment; the key in the map is the JNDI name; the value is the // * object associated with that name. // * // * @param environment the environment to be added to; never {@code null}. // * @throws Exception if the environment could not be built. // */ // void build(Map<String, Object> environment) throws Exception; // // } // Path: src/main/java/org/specs2/spring/annotation/Jndi.java import org.specs2.spring.BlankJndiBuilder; import org.specs2.spring.JndiBuilder; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; package org.specs2.spring.annotation; /** * Use this annotation on your tests to inject values into the JNDI environment for the * tests. * <p>You can specify any number of {@link #dataSources()}, {@link #mailSessions()}, * {@link #beans()}</p> * <p>In addition to these fairly standard items, you can specify {@link #builder()}, * which needs to be an implementation of the {@link org.specs2.spring.JndiBuilder} interface with * nullary constructor. The runtime will instantiate the given class and call its * {@link org.specs2.spring.JndiBuilder#build(java.util.Map)} method.</p> * * * @author janmmachacek */ @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface Jndi { /** * Specify any number of {@link javax.sql.DataSource} JNDI entries. * <p>Typically, you'd write something like * <code>@DataSource(name = "java:comp/env/jdbc/x", url = "jdbc:hsqldb:mem:x", username = "sa", password = "")</code>: * this would register a {@link javax.sql.DataSource} entry in the JNDI environment under name <code>java:comp/env/jdbc/x</code>, * with the given {@code url}, {@code username} and {@code password}. * </p> * * @return the data sources */ DataSource[] dataSources() default {}; /** * Specify any number of {@link javax.mail.Session} JNDI entries. * * @return the mail sessions */ MailSession[] mailSessions() default {}; /** * Specify any number of any objects as JNDI entries. The objects must have nullary constructors. * * @return the beans */ Bean[] beans() default {}; WorkManager[] workManagers() default {}; /** * Specify any number of {@link javax.transaction.TransactionManager} as JNDI entries. * * @return the transaction managers. */ TransactionManager[] transactionManager() default {}; /** * Configure the JMS environment; configure the queues, topics and connection factory. * * @return the JMS environment */ Jms[] jms() default {}; /** * If you require some complex environment setup, you can set this value. The type you specify here * must be an implementation of the {@link org.specs2.spring.JndiBuilder} with nullary constructor. * * @return the custom JndiBuilder */
Class<? extends JndiBuilder> builder() default BlankJndiBuilder.class;
eigengo/specs2-spring
src/main/java/org/specs2/spring/annotation/Jndi.java
// Path: src/main/java/org/specs2/spring/BlankJndiBuilder.java // public class BlankJndiBuilder implements JndiBuilder { // // public BlankJndiBuilder() { // // } // // public void build(Map<String, Object> environment) throws Exception { // // do nothing // } // } // // Path: src/main/java/org/specs2/spring/JndiBuilder.java // public interface JndiBuilder { // // /** // * Adds the items into the environment; the key in the map is the JNDI name; the value is the // * object associated with that name. // * // * @param environment the environment to be added to; never {@code null}. // * @throws Exception if the environment could not be built. // */ // void build(Map<String, Object> environment) throws Exception; // // }
import org.specs2.spring.BlankJndiBuilder; import org.specs2.spring.JndiBuilder; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy;
package org.specs2.spring.annotation; /** * Use this annotation on your tests to inject values into the JNDI environment for the * tests. * <p>You can specify any number of {@link #dataSources()}, {@link #mailSessions()}, * {@link #beans()}</p> * <p>In addition to these fairly standard items, you can specify {@link #builder()}, * which needs to be an implementation of the {@link org.specs2.spring.JndiBuilder} interface with * nullary constructor. The runtime will instantiate the given class and call its * {@link org.specs2.spring.JndiBuilder#build(java.util.Map)} method.</p> * * * @author janmmachacek */ @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface Jndi { /** * Specify any number of {@link javax.sql.DataSource} JNDI entries. * <p>Typically, you'd write something like * <code>@DataSource(name = "java:comp/env/jdbc/x", url = "jdbc:hsqldb:mem:x", username = "sa", password = "")</code>: * this would register a {@link javax.sql.DataSource} entry in the JNDI environment under name <code>java:comp/env/jdbc/x</code>, * with the given {@code url}, {@code username} and {@code password}. * </p> * * @return the data sources */ DataSource[] dataSources() default {}; /** * Specify any number of {@link javax.mail.Session} JNDI entries. * * @return the mail sessions */ MailSession[] mailSessions() default {}; /** * Specify any number of any objects as JNDI entries. The objects must have nullary constructors. * * @return the beans */ Bean[] beans() default {}; WorkManager[] workManagers() default {}; /** * Specify any number of {@link javax.transaction.TransactionManager} as JNDI entries. * * @return the transaction managers. */ TransactionManager[] transactionManager() default {}; /** * Configure the JMS environment; configure the queues, topics and connection factory. * * @return the JMS environment */ Jms[] jms() default {}; /** * If you require some complex environment setup, you can set this value. The type you specify here * must be an implementation of the {@link org.specs2.spring.JndiBuilder} with nullary constructor. * * @return the custom JndiBuilder */
// Path: src/main/java/org/specs2/spring/BlankJndiBuilder.java // public class BlankJndiBuilder implements JndiBuilder { // // public BlankJndiBuilder() { // // } // // public void build(Map<String, Object> environment) throws Exception { // // do nothing // } // } // // Path: src/main/java/org/specs2/spring/JndiBuilder.java // public interface JndiBuilder { // // /** // * Adds the items into the environment; the key in the map is the JNDI name; the value is the // * object associated with that name. // * // * @param environment the environment to be added to; never {@code null}. // * @throws Exception if the environment could not be built. // */ // void build(Map<String, Object> environment) throws Exception; // // } // Path: src/main/java/org/specs2/spring/annotation/Jndi.java import org.specs2.spring.BlankJndiBuilder; import org.specs2.spring.JndiBuilder; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; package org.specs2.spring.annotation; /** * Use this annotation on your tests to inject values into the JNDI environment for the * tests. * <p>You can specify any number of {@link #dataSources()}, {@link #mailSessions()}, * {@link #beans()}</p> * <p>In addition to these fairly standard items, you can specify {@link #builder()}, * which needs to be an implementation of the {@link org.specs2.spring.JndiBuilder} interface with * nullary constructor. The runtime will instantiate the given class and call its * {@link org.specs2.spring.JndiBuilder#build(java.util.Map)} method.</p> * * * @author janmmachacek */ @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface Jndi { /** * Specify any number of {@link javax.sql.DataSource} JNDI entries. * <p>Typically, you'd write something like * <code>@DataSource(name = "java:comp/env/jdbc/x", url = "jdbc:hsqldb:mem:x", username = "sa", password = "")</code>: * this would register a {@link javax.sql.DataSource} entry in the JNDI environment under name <code>java:comp/env/jdbc/x</code>, * with the given {@code url}, {@code username} and {@code password}. * </p> * * @return the data sources */ DataSource[] dataSources() default {}; /** * Specify any number of {@link javax.mail.Session} JNDI entries. * * @return the mail sessions */ MailSession[] mailSessions() default {}; /** * Specify any number of any objects as JNDI entries. The objects must have nullary constructors. * * @return the beans */ Bean[] beans() default {}; WorkManager[] workManagers() default {}; /** * Specify any number of {@link javax.transaction.TransactionManager} as JNDI entries. * * @return the transaction managers. */ TransactionManager[] transactionManager() default {}; /** * Configure the JMS environment; configure the queues, topics and connection factory. * * @return the JMS environment */ Jms[] jms() default {}; /** * If you require some complex environment setup, you can set this value. The type you specify here * must be an implementation of the {@link org.specs2.spring.JndiBuilder} with nullary constructor. * * @return the custom JndiBuilder */
Class<? extends JndiBuilder> builder() default BlankJndiBuilder.class;
openmhealth/schemas
test-data-validator/src/main/java/org/openmhealth/schema/service/SchemaClassServiceImpl.java
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/SchemaId.java // public class SchemaId implements Comparable<SchemaId>, SchemaSupport { // // public static final String NAMESPACE_PATTERN_STRING = "[a-zA-Z0-9.-]+"; // public static final Pattern NAMESPACE_PATTERN = compile(NAMESPACE_PATTERN_STRING); // public static final String NAME_PATTERN_STRING = "[a-zA-Z0-9-]+"; // public static final Pattern NAME_PATTERN = compile(NAME_PATTERN_STRING); // // public static final SchemaId SCHEMA_ID = new SchemaId(OMH_NAMESPACE, "schema-id", "1.0"); // // private String namespace; // private String name; // private SchemaVersion version; // // // @SerializationConstructor // protected SchemaId() { // } // // public SchemaId(String namespace, String name, String version) { // // this(namespace, name, new SchemaVersion(version)); // } // // public SchemaId(String namespace, String name, SchemaVersion version) { // // checkNotNull(namespace, "A namespace hasn't been specified."); // checkArgument(isValidNamespace(namespace), "An invalid namespace has been specified."); // checkNotNull(name, "A name hasn't been specified."); // checkArgument(isValidName(name), "An invalid name has been specified."); // checkNotNull(version, "A version hasn't been specified."); // // this.namespace = namespace; // this.name = name; // this.version = version; // } // // public String getNamespace() { // return namespace; // } // // public static boolean isValidNamespace(String namespace) { // return namespace == null || NAMESPACE_PATTERN.matcher(namespace).matches(); // } // // public String getName() { // return name; // } // // public static boolean isValidName(String name) { // return name == null || NAME_PATTERN.matcher(name).matches(); // } // // public SchemaVersion getVersion() { // return version; // } // // @Override // public String toString() { // // return Joiner.on(":").join(namespace, name, version); // } // // @Override // public SchemaId getSchemaId() { // return SCHEMA_ID; // } // // @Override // public boolean equals(Object object) { // // if (this == object) { // return true; // } // // if (object == null || getClass() != object.getClass()) { // return false; // } // // SchemaId schemaId = (SchemaId) object; // // return name.equals(schemaId.name) && namespace.equals(schemaId.namespace) && version.equals(schemaId.version); // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // @Override // public int compareTo(SchemaId that) { // // if (getNamespace().compareTo(that.getNamespace()) != 0) { // return getNamespace().compareTo(that.getNamespace()); // } // // if (getName().compareTo(that.getName()) != 0) { // return getName().compareTo(that.getName()); // } // // return getVersion().compareTo(that.getVersion()); // } // }
import org.openmhealth.schema.domain.omh.SchemaId; import org.openmhealth.schema.domain.omh.SchemaSupport; import org.reflections.Reflections; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.service; /** * A schema identifier service that uses reflection at load-time to determine which schema classes are available on the * classpath. * * @author Emerson Farrugia */ @Service public class SchemaClassServiceImpl implements SchemaClassService { public static final String SCHEMA_CLASS_PACKAGE = "org.openmhealth.schema.domain";
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/SchemaId.java // public class SchemaId implements Comparable<SchemaId>, SchemaSupport { // // public static final String NAMESPACE_PATTERN_STRING = "[a-zA-Z0-9.-]+"; // public static final Pattern NAMESPACE_PATTERN = compile(NAMESPACE_PATTERN_STRING); // public static final String NAME_PATTERN_STRING = "[a-zA-Z0-9-]+"; // public static final Pattern NAME_PATTERN = compile(NAME_PATTERN_STRING); // // public static final SchemaId SCHEMA_ID = new SchemaId(OMH_NAMESPACE, "schema-id", "1.0"); // // private String namespace; // private String name; // private SchemaVersion version; // // // @SerializationConstructor // protected SchemaId() { // } // // public SchemaId(String namespace, String name, String version) { // // this(namespace, name, new SchemaVersion(version)); // } // // public SchemaId(String namespace, String name, SchemaVersion version) { // // checkNotNull(namespace, "A namespace hasn't been specified."); // checkArgument(isValidNamespace(namespace), "An invalid namespace has been specified."); // checkNotNull(name, "A name hasn't been specified."); // checkArgument(isValidName(name), "An invalid name has been specified."); // checkNotNull(version, "A version hasn't been specified."); // // this.namespace = namespace; // this.name = name; // this.version = version; // } // // public String getNamespace() { // return namespace; // } // // public static boolean isValidNamespace(String namespace) { // return namespace == null || NAMESPACE_PATTERN.matcher(namespace).matches(); // } // // public String getName() { // return name; // } // // public static boolean isValidName(String name) { // return name == null || NAME_PATTERN.matcher(name).matches(); // } // // public SchemaVersion getVersion() { // return version; // } // // @Override // public String toString() { // // return Joiner.on(":").join(namespace, name, version); // } // // @Override // public SchemaId getSchemaId() { // return SCHEMA_ID; // } // // @Override // public boolean equals(Object object) { // // if (this == object) { // return true; // } // // if (object == null || getClass() != object.getClass()) { // return false; // } // // SchemaId schemaId = (SchemaId) object; // // return name.equals(schemaId.name) && namespace.equals(schemaId.namespace) && version.equals(schemaId.version); // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // @Override // public int compareTo(SchemaId that) { // // if (getNamespace().compareTo(that.getNamespace()) != 0) { // return getNamespace().compareTo(that.getNamespace()); // } // // if (getName().compareTo(that.getName()) != 0) { // return getName().compareTo(that.getName()); // } // // return getVersion().compareTo(that.getVersion()); // } // } // Path: test-data-validator/src/main/java/org/openmhealth/schema/service/SchemaClassServiceImpl.java import org.openmhealth.schema.domain.omh.SchemaId; import org.openmhealth.schema.domain.omh.SchemaSupport; import org.reflections.Reflections; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.service; /** * A schema identifier service that uses reflection at load-time to determine which schema classes are available on the * classpath. * * @author Emerson Farrugia */ @Service public class SchemaClassServiceImpl implements SchemaClassService { public static final String SCHEMA_CLASS_PACKAGE = "org.openmhealth.schema.domain";
private Set<SchemaId> schemaIds = new HashSet<>();
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/PhysicalActivityUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import static org.openmhealth.schema.domain.omh.PhysicalActivity.SelfReportedIntensity.MODERATE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import org.testng.annotations.Test; import java.math.BigDecimal; import java.time.LocalDate; import static java.math.BigDecimal.ONE; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.KcalUnit.KILOCALORIE; import static org.openmhealth.schema.domain.omh.LengthUnit.KILOMETER; import static org.openmhealth.schema.domain.omh.LengthUnit.MILE; import static org.openmhealth.schema.domain.omh.PartOfDay.MORNING; import static org.openmhealth.schema.domain.omh.PhysicalActivity.SelfReportedIntensity.LIGHT;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class PhysicalActivityUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/physical-activity-1.2.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedActivityName() { new PhysicalActivity.Builder(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void constructorShouldThrowExceptionOnEmptyActivityName() { new PhysicalActivity.Builder(""); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { PhysicalActivity physicalActivity = new PhysicalActivity.Builder("walking").build(); assertThat(physicalActivity, notNullValue()); assertThat(physicalActivity.getActivityName(), equalTo("walking")); assertThat(physicalActivity.getDistance(), nullValue()); assertThat(physicalActivity.getReportedActivityIntensity(), nullValue()); assertThat(physicalActivity.getEffectiveTimeFrame(), nullValue()); assertThat(physicalActivity.getDescriptiveStatistic(), nullValue()); assertThat(physicalActivity.getUserNotes(), nullValue()); assertThat(physicalActivity.getCaloriesBurned(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { LengthUnitValue distance = new LengthUnitValue(KILOMETER, ONE); KcalUnitValue caloriesBurned = new KcalUnitValue(KILOCALORIE, 15.7); PhysicalActivity physicalActivity = new PhysicalActivity.Builder("walking") .setDistance(distance) .setReportedActivityIntensity(LIGHT)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/PhysicalActivityUnitTests.java import static org.openmhealth.schema.domain.omh.PhysicalActivity.SelfReportedIntensity.MODERATE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import org.testng.annotations.Test; import java.math.BigDecimal; import java.time.LocalDate; import static java.math.BigDecimal.ONE; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.KcalUnit.KILOCALORIE; import static org.openmhealth.schema.domain.omh.LengthUnit.KILOMETER; import static org.openmhealth.schema.domain.omh.LengthUnit.MILE; import static org.openmhealth.schema.domain.omh.PartOfDay.MORNING; import static org.openmhealth.schema.domain.omh.PhysicalActivity.SelfReportedIntensity.LIGHT; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class PhysicalActivityUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/physical-activity-1.2.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedActivityName() { new PhysicalActivity.Builder(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void constructorShouldThrowExceptionOnEmptyActivityName() { new PhysicalActivity.Builder(""); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { PhysicalActivity physicalActivity = new PhysicalActivity.Builder("walking").build(); assertThat(physicalActivity, notNullValue()); assertThat(physicalActivity.getActivityName(), equalTo("walking")); assertThat(physicalActivity.getDistance(), nullValue()); assertThat(physicalActivity.getReportedActivityIntensity(), nullValue()); assertThat(physicalActivity.getEffectiveTimeFrame(), nullValue()); assertThat(physicalActivity.getDescriptiveStatistic(), nullValue()); assertThat(physicalActivity.getUserNotes(), nullValue()); assertThat(physicalActivity.getCaloriesBurned(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { LengthUnitValue distance = new LengthUnitValue(KILOMETER, ONE); KcalUnitValue caloriesBurned = new KcalUnitValue(KILOCALORIE, 15.7); PhysicalActivity physicalActivity = new PhysicalActivity.Builder("walking") .setDistance(distance) .setReportedActivityIntensity(LIGHT)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/StepCount2UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class StepCount2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/step-count-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedStepCount() {
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/StepCount2UnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class StepCount2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/step-count-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedStepCount() {
new StepCount2.Builder(null, FIXED_MONTH);
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/StepCount2UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class StepCount2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/step-count-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedStepCount() { new StepCount2.Builder(null, FIXED_MONTH); } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedEffectiveTimeFrame() { new StepCount2.Builder(TEN, (TimeFrame) null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() {
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/StepCount2UnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class StepCount2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/step-count-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedStepCount() { new StepCount2.Builder(null, FIXED_MONTH); } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedEffectiveTimeFrame() { new StepCount2.Builder(TEN, (TimeFrame) null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() {
StepCount2 stepCount = new StepCount2.Builder(TEN, FIXED_DAY).build();
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/AmbientTemperatureUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.TemperatureUnit.CELSIUS; import static org.openmhealth.schema.domain.omh.TemperatureUnit.FAHRENHEIT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Chris Schaefbauer */ public class AmbientTemperatureUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/ambient-temperature-1.0.json"; @Override public String getSchemaFilename() { return SCHEMA_FILENAME; } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionWhenBodyTemperatureIsNull() { new AmbientTemperature.Builder(null); } @Test public void buildShouldConstructCorrectMeasureUsingOnlyRequiredProperties() { AmbientTemperature ambientTemperature = new AmbientTemperature.Builder(new TemperatureUnitValue(CELSIUS, 50.3)) .build(); assertThat(ambientTemperature, notNullValue()); assertThat(ambientTemperature.getAmbientTemperature().getTypedUnit(), equalTo(CELSIUS)); assertThat(ambientTemperature.getAmbientTemperature().getValue().doubleValue(), equalTo(50.3)); assertThat(ambientTemperature.getUserNotes(), nullValue()); assertThat(ambientTemperature.getEffectiveTimeFrame(), nullValue()); assertThat(ambientTemperature.getDescriptiveStatistic(), nullValue()); } @Test public void buildShouldConstructCorrectMeasureIncludingOptionalProperties() { AmbientTemperature ambientTemperature = new AmbientTemperature.Builder(new TemperatureUnitValue(FAHRENHEIT, 87L)) .setDescriptiveStatistic(MEDIAN)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/AmbientTemperatureUnitTests.java import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.TemperatureUnit.CELSIUS; import static org.openmhealth.schema.domain.omh.TemperatureUnit.FAHRENHEIT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Chris Schaefbauer */ public class AmbientTemperatureUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/ambient-temperature-1.0.json"; @Override public String getSchemaFilename() { return SCHEMA_FILENAME; } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionWhenBodyTemperatureIsNull() { new AmbientTemperature.Builder(null); } @Test public void buildShouldConstructCorrectMeasureUsingOnlyRequiredProperties() { AmbientTemperature ambientTemperature = new AmbientTemperature.Builder(new TemperatureUnitValue(CELSIUS, 50.3)) .build(); assertThat(ambientTemperature, notNullValue()); assertThat(ambientTemperature.getAmbientTemperature().getTypedUnit(), equalTo(CELSIUS)); assertThat(ambientTemperature.getAmbientTemperature().getValue().doubleValue(), equalTo(50.3)); assertThat(ambientTemperature.getUserNotes(), nullValue()); assertThat(ambientTemperature.getEffectiveTimeFrame(), nullValue()); assertThat(ambientTemperature.getDescriptiveStatistic(), nullValue()); } @Test public void buildShouldConstructCorrectMeasureIncludingOptionalProperties() { AmbientTemperature ambientTemperature = new AmbientTemperature.Builder(new TemperatureUnitValue(FAHRENHEIT, 87L)) .setDescriptiveStatistic(MEDIAN)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/AmbientTemperatureUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.TemperatureUnit.CELSIUS; import static org.openmhealth.schema.domain.omh.TemperatureUnit.FAHRENHEIT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME;
assertThat(ambientTemperature, notNullValue()); assertThat(ambientTemperature.getAmbientTemperature().getTypedUnit(), equalTo(CELSIUS)); assertThat(ambientTemperature.getAmbientTemperature().getValue().doubleValue(), equalTo(50.3)); assertThat(ambientTemperature.getUserNotes(), nullValue()); assertThat(ambientTemperature.getEffectiveTimeFrame(), nullValue()); assertThat(ambientTemperature.getDescriptiveStatistic(), nullValue()); } @Test public void buildShouldConstructCorrectMeasureIncludingOptionalProperties() { AmbientTemperature ambientTemperature = new AmbientTemperature.Builder(new TemperatureUnitValue(FAHRENHEIT, 87L)) .setDescriptiveStatistic(MEDIAN) .setEffectiveTimeFrame(FIXED_MONTH) .setUserNotes("Temp is fine") .build(); assertThat(ambientTemperature.getAmbientTemperature().getTypedUnit(), equalTo(FAHRENHEIT)); assertThat(ambientTemperature.getAmbientTemperature().getValue().intValue(), equalTo(87)); assertThat(ambientTemperature.getUserNotes(), equalTo("Temp is fine")); assertThat(ambientTemperature.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(ambientTemperature.getDescriptiveStatistic(), equalTo(MEDIAN)); } @Test public void measureShouldSerializeCorrectly() throws Exception { AmbientTemperature ambientTemperature = new AmbientTemperature.Builder(new TemperatureUnitValue(CELSIUS, 34L))
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/AmbientTemperatureUnitTests.java import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.TemperatureUnit.CELSIUS; import static org.openmhealth.schema.domain.omh.TemperatureUnit.FAHRENHEIT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; assertThat(ambientTemperature, notNullValue()); assertThat(ambientTemperature.getAmbientTemperature().getTypedUnit(), equalTo(CELSIUS)); assertThat(ambientTemperature.getAmbientTemperature().getValue().doubleValue(), equalTo(50.3)); assertThat(ambientTemperature.getUserNotes(), nullValue()); assertThat(ambientTemperature.getEffectiveTimeFrame(), nullValue()); assertThat(ambientTemperature.getDescriptiveStatistic(), nullValue()); } @Test public void buildShouldConstructCorrectMeasureIncludingOptionalProperties() { AmbientTemperature ambientTemperature = new AmbientTemperature.Builder(new TemperatureUnitValue(FAHRENHEIT, 87L)) .setDescriptiveStatistic(MEDIAN) .setEffectiveTimeFrame(FIXED_MONTH) .setUserNotes("Temp is fine") .build(); assertThat(ambientTemperature.getAmbientTemperature().getTypedUnit(), equalTo(FAHRENHEIT)); assertThat(ambientTemperature.getAmbientTemperature().getValue().intValue(), equalTo(87)); assertThat(ambientTemperature.getUserNotes(), equalTo("Temp is fine")); assertThat(ambientTemperature.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(ambientTemperature.getDescriptiveStatistic(), equalTo(MEDIAN)); } @Test public void measureShouldSerializeCorrectly() throws Exception { AmbientTemperature ambientTemperature = new AmbientTemperature.Builder(new TemperatureUnitValue(CELSIUS, 34L))
.setEffectiveTimeFrame(FIXED_POINT_IN_TIME)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SleepEpisodeUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_NIGHT_TIME_HOURS = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).minusHours(1).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).plusHours(7).toOffsetDateTime() // ));
import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.MINUTE; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_NIGHT_TIME_HOURS;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SleepEpisodeUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/sleep-episode-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedEffectiveTimeFrame() { new SleepEpisode.Builder((TimeFrame) null); } @Test(expectedExceptions = UnsupportedOperationException.class) public void buildShouldThrowExceptionOnSettingDescriptiveStatistic() {
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_NIGHT_TIME_HOURS = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).minusHours(1).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).plusHours(7).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SleepEpisodeUnitTests.java import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.MINUTE; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_NIGHT_TIME_HOURS; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SleepEpisodeUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/sleep-episode-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedEffectiveTimeFrame() { new SleepEpisode.Builder((TimeFrame) null); } @Test(expectedExceptions = UnsupportedOperationException.class) public void buildShouldThrowExceptionOnSettingDescriptiveStatistic() {
new SleepEpisode.Builder(FIXED_NIGHT_TIME_HOURS).setDescriptiveStatistic(AVERAGE);
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SpeedUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.SpeedUnit.KILOMETERS_PER_HOUR; import static org.openmhealth.schema.domain.omh.SpeedUnit.METERS_PER_SECOND; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SpeedUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/speed-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedSpeed() {
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SpeedUnitTests.java import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.SpeedUnit.KILOMETERS_PER_HOUR; import static org.openmhealth.schema.domain.omh.SpeedUnit.METERS_PER_SECOND; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SpeedUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/speed-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedSpeed() {
new Speed.Builder(null, FIXED_MONTH);
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SpeedUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.SpeedUnit.KILOMETERS_PER_HOUR; import static org.openmhealth.schema.domain.omh.SpeedUnit.METERS_PER_SECOND; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SpeedUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/speed-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedSpeed() { new Speed.Builder(null, FIXED_MONTH); } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedEffectiveTimeFrame() { new Speed.Builder(METERS_PER_SECOND.newUnitValue(15), (OffsetDateTime) null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { SpeedUnitValue speedUnitValue = KILOMETERS_PER_HOUR.newUnitValue(10);
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SpeedUnitTests.java import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.SpeedUnit.KILOMETERS_PER_HOUR; import static org.openmhealth.schema.domain.omh.SpeedUnit.METERS_PER_SECOND; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SpeedUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/speed-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedSpeed() { new Speed.Builder(null, FIXED_MONTH); } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedEffectiveTimeFrame() { new Speed.Builder(METERS_PER_SECOND.newUnitValue(15), (OffsetDateTime) null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { SpeedUnitValue speedUnitValue = KILOMETERS_PER_HOUR.newUnitValue(10);
Speed speed = new Speed.Builder(speedUnitValue, FIXED_POINT_IN_TIME).build();
openmhealth/schemas
test-data-validator/src/main/java/org/openmhealth/schema/domain/SchemaFile.java
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/SchemaId.java // public class SchemaId implements Comparable<SchemaId>, SchemaSupport { // // public static final String NAMESPACE_PATTERN_STRING = "[a-zA-Z0-9.-]+"; // public static final Pattern NAMESPACE_PATTERN = compile(NAMESPACE_PATTERN_STRING); // public static final String NAME_PATTERN_STRING = "[a-zA-Z0-9-]+"; // public static final Pattern NAME_PATTERN = compile(NAME_PATTERN_STRING); // // public static final SchemaId SCHEMA_ID = new SchemaId(OMH_NAMESPACE, "schema-id", "1.0"); // // private String namespace; // private String name; // private SchemaVersion version; // // // @SerializationConstructor // protected SchemaId() { // } // // public SchemaId(String namespace, String name, String version) { // // this(namespace, name, new SchemaVersion(version)); // } // // public SchemaId(String namespace, String name, SchemaVersion version) { // // checkNotNull(namespace, "A namespace hasn't been specified."); // checkArgument(isValidNamespace(namespace), "An invalid namespace has been specified."); // checkNotNull(name, "A name hasn't been specified."); // checkArgument(isValidName(name), "An invalid name has been specified."); // checkNotNull(version, "A version hasn't been specified."); // // this.namespace = namespace; // this.name = name; // this.version = version; // } // // public String getNamespace() { // return namespace; // } // // public static boolean isValidNamespace(String namespace) { // return namespace == null || NAMESPACE_PATTERN.matcher(namespace).matches(); // } // // public String getName() { // return name; // } // // public static boolean isValidName(String name) { // return name == null || NAME_PATTERN.matcher(name).matches(); // } // // public SchemaVersion getVersion() { // return version; // } // // @Override // public String toString() { // // return Joiner.on(":").join(namespace, name, version); // } // // @Override // public SchemaId getSchemaId() { // return SCHEMA_ID; // } // // @Override // public boolean equals(Object object) { // // if (this == object) { // return true; // } // // if (object == null || getClass() != object.getClass()) { // return false; // } // // SchemaId schemaId = (SchemaId) object; // // return name.equals(schemaId.name) && namespace.equals(schemaId.namespace) && version.equals(schemaId.version); // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // @Override // public int compareTo(SchemaId that) { // // if (getNamespace().compareTo(that.getNamespace()) != 0) { // return getNamespace().compareTo(that.getNamespace()); // } // // if (getName().compareTo(that.getName()) != 0) { // return getName().compareTo(that.getName()); // } // // return getVersion().compareTo(that.getVersion()); // } // }
import com.github.fge.jsonschema.main.JsonSchema; import org.openmhealth.schema.domain.omh.SchemaId; import org.openmhealth.schema.domain.omh.SchemaVersion; import java.net.URI; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.regex.Pattern.compile;
/* * Copyright 2016 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain; /** * A representation of a schema file. * * @author Emerson Farrugia */ public class SchemaFile { /* * This pattern corresponds to the current layout in the /schema directory. The metadata extracted from the URI * should probably live in the schema itself. */ public static final Pattern SCHEMA_URI_PATTERN = compile("/([a-z0-9-]+)/([a-z0-9-]+)-([^-]+)\\.json$");
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/SchemaId.java // public class SchemaId implements Comparable<SchemaId>, SchemaSupport { // // public static final String NAMESPACE_PATTERN_STRING = "[a-zA-Z0-9.-]+"; // public static final Pattern NAMESPACE_PATTERN = compile(NAMESPACE_PATTERN_STRING); // public static final String NAME_PATTERN_STRING = "[a-zA-Z0-9-]+"; // public static final Pattern NAME_PATTERN = compile(NAME_PATTERN_STRING); // // public static final SchemaId SCHEMA_ID = new SchemaId(OMH_NAMESPACE, "schema-id", "1.0"); // // private String namespace; // private String name; // private SchemaVersion version; // // // @SerializationConstructor // protected SchemaId() { // } // // public SchemaId(String namespace, String name, String version) { // // this(namespace, name, new SchemaVersion(version)); // } // // public SchemaId(String namespace, String name, SchemaVersion version) { // // checkNotNull(namespace, "A namespace hasn't been specified."); // checkArgument(isValidNamespace(namespace), "An invalid namespace has been specified."); // checkNotNull(name, "A name hasn't been specified."); // checkArgument(isValidName(name), "An invalid name has been specified."); // checkNotNull(version, "A version hasn't been specified."); // // this.namespace = namespace; // this.name = name; // this.version = version; // } // // public String getNamespace() { // return namespace; // } // // public static boolean isValidNamespace(String namespace) { // return namespace == null || NAMESPACE_PATTERN.matcher(namespace).matches(); // } // // public String getName() { // return name; // } // // public static boolean isValidName(String name) { // return name == null || NAME_PATTERN.matcher(name).matches(); // } // // public SchemaVersion getVersion() { // return version; // } // // @Override // public String toString() { // // return Joiner.on(":").join(namespace, name, version); // } // // @Override // public SchemaId getSchemaId() { // return SCHEMA_ID; // } // // @Override // public boolean equals(Object object) { // // if (this == object) { // return true; // } // // if (object == null || getClass() != object.getClass()) { // return false; // } // // SchemaId schemaId = (SchemaId) object; // // return name.equals(schemaId.name) && namespace.equals(schemaId.namespace) && version.equals(schemaId.version); // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // @Override // public int compareTo(SchemaId that) { // // if (getNamespace().compareTo(that.getNamespace()) != 0) { // return getNamespace().compareTo(that.getNamespace()); // } // // if (getName().compareTo(that.getName()) != 0) { // return getName().compareTo(that.getName()); // } // // return getVersion().compareTo(that.getVersion()); // } // } // Path: test-data-validator/src/main/java/org/openmhealth/schema/domain/SchemaFile.java import com.github.fge.jsonschema.main.JsonSchema; import org.openmhealth.schema.domain.omh.SchemaId; import org.openmhealth.schema.domain.omh.SchemaVersion; import java.net.URI; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.regex.Pattern.compile; /* * Copyright 2016 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain; /** * A representation of a schema file. * * @author Emerson Farrugia */ public class SchemaFile { /* * This pattern corresponds to the current layout in the /schema directory. The metadata extracted from the URI * should probably live in the schema itself. */ public static final Pattern SCHEMA_URI_PATTERN = compile("/([a-z0-9-]+)/([a-z0-9-]+)-([^-]+)\\.json$");
private SchemaId schemaId;
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/OxygenSaturationUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.OxygenFlowRateUnit.LITERS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.OxygenSaturation.MeasurementMethod.PULSE_OXIMETRY; import static org.openmhealth.schema.domain.omh.OxygenSaturation.MeasurementSystem.PERIPHERAL_CAPILLARY; import static org.openmhealth.schema.domain.omh.OxygenSaturation.SupplementalOxygenAdministrationMode.NASAL_CANNULA; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.SchemaSupport.OMH_NAMESPACE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Chris Schaefbauer */ public class OxygenSaturationUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/oxygen-saturation-1.0.json"; @Override public String getSchemaFilename() { return SCHEMA_FILENAME; } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnNullOxygenSaturationValue() { new OxygenSaturation.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { OxygenSaturation oxygenSaturation = new OxygenSaturation.Builder(new TypedUnitValue<>(PERCENT, 92)).build(); assertThat(oxygenSaturation, notNullValue()); assertThat(oxygenSaturation.getOxygenSaturation(), equalTo(new TypedUnitValue<>(PERCENT, 92))); assertThat(oxygenSaturation.getEffectiveTimeFrame(), nullValue()); assertThat(oxygenSaturation.getUserNotes(), nullValue()); assertThat(oxygenSaturation.getDescriptiveStatistic(), nullValue()); assertThat(oxygenSaturation.getSupplementalOxygenFlowRate(), nullValue()); assertThat(oxygenSaturation.getMeasurementSystem(), nullValue()); assertThat(oxygenSaturation.getSupplementalOxygenAdministrationMode(), nullValue()); assertThat(oxygenSaturation.getMeasurementMethod(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { OxygenSaturation oxygenSaturation = new OxygenSaturation.Builder(new TypedUnitValue<>(PERCENT, 93.5))
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/OxygenSaturationUnitTests.java import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.OxygenFlowRateUnit.LITERS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.OxygenSaturation.MeasurementMethod.PULSE_OXIMETRY; import static org.openmhealth.schema.domain.omh.OxygenSaturation.MeasurementSystem.PERIPHERAL_CAPILLARY; import static org.openmhealth.schema.domain.omh.OxygenSaturation.SupplementalOxygenAdministrationMode.NASAL_CANNULA; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.SchemaSupport.OMH_NAMESPACE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Chris Schaefbauer */ public class OxygenSaturationUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/oxygen-saturation-1.0.json"; @Override public String getSchemaFilename() { return SCHEMA_FILENAME; } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnNullOxygenSaturationValue() { new OxygenSaturation.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { OxygenSaturation oxygenSaturation = new OxygenSaturation.Builder(new TypedUnitValue<>(PERCENT, 92)).build(); assertThat(oxygenSaturation, notNullValue()); assertThat(oxygenSaturation.getOxygenSaturation(), equalTo(new TypedUnitValue<>(PERCENT, 92))); assertThat(oxygenSaturation.getEffectiveTimeFrame(), nullValue()); assertThat(oxygenSaturation.getUserNotes(), nullValue()); assertThat(oxygenSaturation.getDescriptiveStatistic(), nullValue()); assertThat(oxygenSaturation.getSupplementalOxygenFlowRate(), nullValue()); assertThat(oxygenSaturation.getMeasurementSystem(), nullValue()); assertThat(oxygenSaturation.getSupplementalOxygenAdministrationMode(), nullValue()); assertThat(oxygenSaturation.getMeasurementMethod(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { OxygenSaturation oxygenSaturation = new OxygenSaturation.Builder(new TypedUnitValue<>(PERCENT, 93.5))
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/OxygenSaturationUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.OxygenFlowRateUnit.LITERS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.OxygenSaturation.MeasurementMethod.PULSE_OXIMETRY; import static org.openmhealth.schema.domain.omh.OxygenSaturation.MeasurementSystem.PERIPHERAL_CAPILLARY; import static org.openmhealth.schema.domain.omh.OxygenSaturation.SupplementalOxygenAdministrationMode.NASAL_CANNULA; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.SchemaSupport.OMH_NAMESPACE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
@Test public void buildShouldConstructMeasureUsingOptionalProperties() { OxygenSaturation oxygenSaturation = new OxygenSaturation.Builder(new TypedUnitValue<>(PERCENT, 93.5)) .setEffectiveTimeFrame(FIXED_MONTH) .setUserNotes("a note about oxygen sat") .setDescriptiveStatistic(MAXIMUM) .setMeasurementSystem(PERIPHERAL_CAPILLARY) .setSupplementalOxygenFlowRate(new TypedUnitValue<>(LITERS_PER_MINUTE, 3.2)) .setSupplementalOxygenAdministrationMode(NASAL_CANNULA) .setMeasurementMethod(PULSE_OXIMETRY) .build(); assertThat(oxygenSaturation, notNullValue()); assertThat(oxygenSaturation.getOxygenSaturation(), equalTo(new TypedUnitValue<>(PERCENT, 93.5))); assertThat(oxygenSaturation.getUserNotes(), equalTo("a note about oxygen sat")); assertThat(oxygenSaturation.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(oxygenSaturation.getDescriptiveStatistic(), equalTo(MAXIMUM)); assertThat(oxygenSaturation.getMeasurementSystem(), equalTo(PERIPHERAL_CAPILLARY)); assertThat(oxygenSaturation.getSupplementalOxygenFlowRate(), equalTo(new TypedUnitValue<>(LITERS_PER_MINUTE, 3.2))); assertThat(oxygenSaturation.getSupplementalOxygenAdministrationMode(), equalTo(NASAL_CANNULA)); assertThat(oxygenSaturation.getMeasurementMethod(), equalTo(PULSE_OXIMETRY)); } @Test public void measureShouldSerializeCorrectly() throws Exception { OxygenSaturation oxygenSaturation = new OxygenSaturation.Builder(new TypedUnitValue<>(PERCENT, 96.5))
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/OxygenSaturationUnitTests.java import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.OxygenFlowRateUnit.LITERS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.OxygenSaturation.MeasurementMethod.PULSE_OXIMETRY; import static org.openmhealth.schema.domain.omh.OxygenSaturation.MeasurementSystem.PERIPHERAL_CAPILLARY; import static org.openmhealth.schema.domain.omh.OxygenSaturation.SupplementalOxygenAdministrationMode.NASAL_CANNULA; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.SchemaSupport.OMH_NAMESPACE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; @Test public void buildShouldConstructMeasureUsingOptionalProperties() { OxygenSaturation oxygenSaturation = new OxygenSaturation.Builder(new TypedUnitValue<>(PERCENT, 93.5)) .setEffectiveTimeFrame(FIXED_MONTH) .setUserNotes("a note about oxygen sat") .setDescriptiveStatistic(MAXIMUM) .setMeasurementSystem(PERIPHERAL_CAPILLARY) .setSupplementalOxygenFlowRate(new TypedUnitValue<>(LITERS_PER_MINUTE, 3.2)) .setSupplementalOxygenAdministrationMode(NASAL_CANNULA) .setMeasurementMethod(PULSE_OXIMETRY) .build(); assertThat(oxygenSaturation, notNullValue()); assertThat(oxygenSaturation.getOxygenSaturation(), equalTo(new TypedUnitValue<>(PERCENT, 93.5))); assertThat(oxygenSaturation.getUserNotes(), equalTo("a note about oxygen sat")); assertThat(oxygenSaturation.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(oxygenSaturation.getDescriptiveStatistic(), equalTo(MAXIMUM)); assertThat(oxygenSaturation.getMeasurementSystem(), equalTo(PERIPHERAL_CAPILLARY)); assertThat(oxygenSaturation.getSupplementalOxygenFlowRate(), equalTo(new TypedUnitValue<>(LITERS_PER_MINUTE, 3.2))); assertThat(oxygenSaturation.getSupplementalOxygenAdministrationMode(), equalTo(NASAL_CANNULA)); assertThat(oxygenSaturation.getMeasurementMethod(), equalTo(PULSE_OXIMETRY)); } @Test public void measureShouldSerializeCorrectly() throws Exception { OxygenSaturation oxygenSaturation = new OxygenSaturation.Builder(new TypedUnitValue<>(PERCENT, 96.5))
.setEffectiveTimeFrame(FIXED_POINT_IN_TIME)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SleepDuration2UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.WEEK; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SleepDuration2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/sleep-duration-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedSleepDuration() {
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SleepDuration2UnitTests.java import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.WEEK; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SleepDuration2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/sleep-duration-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedSleepDuration() {
new SleepDuration2.Builder(null, FIXED_DAY);
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SleepDuration2UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.WEEK; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SleepDuration2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/sleep-duration-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedSleepDuration() { new SleepDuration2.Builder(null, FIXED_DAY); } @Test(expectedExceptions = IllegalArgumentException.class) public void constructorShouldThrowExceptionOnInvalidDurationUnit() {
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SleepDuration2UnitTests.java import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.WEEK; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SleepDuration2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/sleep-duration-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedSleepDuration() { new SleepDuration2.Builder(null, FIXED_DAY); } @Test(expectedExceptions = IllegalArgumentException.class) public void constructorShouldThrowExceptionOnInvalidDurationUnit() {
new SleepDuration2.Builder(new DurationUnitValue(WEEK, ONE), FIXED_MONTH);
openmhealth/schemas
test-data-validator/src/main/java/org/openmhealth/schema/domain/DataFile.java
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/SchemaId.java // public class SchemaId implements Comparable<SchemaId>, SchemaSupport { // // public static final String NAMESPACE_PATTERN_STRING = "[a-zA-Z0-9.-]+"; // public static final Pattern NAMESPACE_PATTERN = compile(NAMESPACE_PATTERN_STRING); // public static final String NAME_PATTERN_STRING = "[a-zA-Z0-9-]+"; // public static final Pattern NAME_PATTERN = compile(NAME_PATTERN_STRING); // // public static final SchemaId SCHEMA_ID = new SchemaId(OMH_NAMESPACE, "schema-id", "1.0"); // // private String namespace; // private String name; // private SchemaVersion version; // // // @SerializationConstructor // protected SchemaId() { // } // // public SchemaId(String namespace, String name, String version) { // // this(namespace, name, new SchemaVersion(version)); // } // // public SchemaId(String namespace, String name, SchemaVersion version) { // // checkNotNull(namespace, "A namespace hasn't been specified."); // checkArgument(isValidNamespace(namespace), "An invalid namespace has been specified."); // checkNotNull(name, "A name hasn't been specified."); // checkArgument(isValidName(name), "An invalid name has been specified."); // checkNotNull(version, "A version hasn't been specified."); // // this.namespace = namespace; // this.name = name; // this.version = version; // } // // public String getNamespace() { // return namespace; // } // // public static boolean isValidNamespace(String namespace) { // return namespace == null || NAMESPACE_PATTERN.matcher(namespace).matches(); // } // // public String getName() { // return name; // } // // public static boolean isValidName(String name) { // return name == null || NAME_PATTERN.matcher(name).matches(); // } // // public SchemaVersion getVersion() { // return version; // } // // @Override // public String toString() { // // return Joiner.on(":").join(namespace, name, version); // } // // @Override // public SchemaId getSchemaId() { // return SCHEMA_ID; // } // // @Override // public boolean equals(Object object) { // // if (this == object) { // return true; // } // // if (object == null || getClass() != object.getClass()) { // return false; // } // // SchemaId schemaId = (SchemaId) object; // // return name.equals(schemaId.name) && namespace.equals(schemaId.namespace) && version.equals(schemaId.version); // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // @Override // public int compareTo(SchemaId that) { // // if (getNamespace().compareTo(that.getNamespace()) != 0) { // return getNamespace().compareTo(that.getNamespace()); // } // // if (getName().compareTo(that.getName()) != 0) { // return getName().compareTo(that.getName()); // } // // return getVersion().compareTo(that.getVersion()); // } // }
import com.fasterxml.jackson.databind.JsonNode; import org.openmhealth.schema.domain.omh.SchemaId; import org.openmhealth.schema.domain.omh.SchemaVersion; import java.net.URI; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static java.util.regex.Pattern.compile; import static org.openmhealth.schema.domain.DataFileValidationResult.FAIL; import static org.openmhealth.schema.domain.DataFileValidationResult.PASS;
/* * Copyright 2016 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain; /** * A representation of a data file containing a JSON document. * * @author Emerson Farrugia */ public class DataFile { public static final Pattern TEST_DATA_URI_PATTERN = compile("/([a-z0-9-]+)/([a-z0-9-]+)/([^/]+)/(shouldPass|shouldFail)/([a-z0-9-]+)\\.json$"); private String name; private URI location; private String path;
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/SchemaId.java // public class SchemaId implements Comparable<SchemaId>, SchemaSupport { // // public static final String NAMESPACE_PATTERN_STRING = "[a-zA-Z0-9.-]+"; // public static final Pattern NAMESPACE_PATTERN = compile(NAMESPACE_PATTERN_STRING); // public static final String NAME_PATTERN_STRING = "[a-zA-Z0-9-]+"; // public static final Pattern NAME_PATTERN = compile(NAME_PATTERN_STRING); // // public static final SchemaId SCHEMA_ID = new SchemaId(OMH_NAMESPACE, "schema-id", "1.0"); // // private String namespace; // private String name; // private SchemaVersion version; // // // @SerializationConstructor // protected SchemaId() { // } // // public SchemaId(String namespace, String name, String version) { // // this(namespace, name, new SchemaVersion(version)); // } // // public SchemaId(String namespace, String name, SchemaVersion version) { // // checkNotNull(namespace, "A namespace hasn't been specified."); // checkArgument(isValidNamespace(namespace), "An invalid namespace has been specified."); // checkNotNull(name, "A name hasn't been specified."); // checkArgument(isValidName(name), "An invalid name has been specified."); // checkNotNull(version, "A version hasn't been specified."); // // this.namespace = namespace; // this.name = name; // this.version = version; // } // // public String getNamespace() { // return namespace; // } // // public static boolean isValidNamespace(String namespace) { // return namespace == null || NAMESPACE_PATTERN.matcher(namespace).matches(); // } // // public String getName() { // return name; // } // // public static boolean isValidName(String name) { // return name == null || NAME_PATTERN.matcher(name).matches(); // } // // public SchemaVersion getVersion() { // return version; // } // // @Override // public String toString() { // // return Joiner.on(":").join(namespace, name, version); // } // // @Override // public SchemaId getSchemaId() { // return SCHEMA_ID; // } // // @Override // public boolean equals(Object object) { // // if (this == object) { // return true; // } // // if (object == null || getClass() != object.getClass()) { // return false; // } // // SchemaId schemaId = (SchemaId) object; // // return name.equals(schemaId.name) && namespace.equals(schemaId.namespace) && version.equals(schemaId.version); // } // // @Override // public int hashCode() { // return name.hashCode(); // } // // @Override // public int compareTo(SchemaId that) { // // if (getNamespace().compareTo(that.getNamespace()) != 0) { // return getNamespace().compareTo(that.getNamespace()); // } // // if (getName().compareTo(that.getName()) != 0) { // return getName().compareTo(that.getName()); // } // // return getVersion().compareTo(that.getVersion()); // } // } // Path: test-data-validator/src/main/java/org/openmhealth/schema/domain/DataFile.java import com.fasterxml.jackson.databind.JsonNode; import org.openmhealth.schema.domain.omh.SchemaId; import org.openmhealth.schema.domain.omh.SchemaVersion; import java.net.URI; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static java.util.regex.Pattern.compile; import static org.openmhealth.schema.domain.DataFileValidationResult.FAIL; import static org.openmhealth.schema.domain.DataFileValidationResult.PASS; /* * Copyright 2016 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain; /** * A representation of a data file containing a JSON document. * * @author Emerson Farrugia */ public class DataFile { public static final Pattern TEST_DATA_URI_PATTERN = compile("/([a-z0-9-]+)/([a-z0-9-]+)/([^/]+)/(shouldPass|shouldFail)/([a-z0-9-]+)\\.json$"); private String name; private URI location; private String path;
private SchemaId schemaId;
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyHeightUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.LengthUnit.CENTIMETER; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class BodyHeightUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/body-height-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedBodyHeight() { new BodyHeight.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { LengthUnitValue lengthUnitValue = new LengthUnitValue(CENTIMETER, BigDecimal.valueOf(180)); BodyHeight bodyHeight = new BodyHeight.Builder(lengthUnitValue).build(); assertThat(bodyHeight, notNullValue()); assertThat(bodyHeight.getBodyHeight(), equalTo(lengthUnitValue)); assertThat(bodyHeight.getEffectiveTimeFrame(), nullValue()); assertThat(bodyHeight.getDescriptiveStatistic(), nullValue()); assertThat(bodyHeight.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { LengthUnitValue lengthUnitValue = new LengthUnitValue(CENTIMETER, BigDecimal.valueOf(180)); BodyHeight bodyHeight = new BodyHeight.Builder(lengthUnitValue)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyHeightUnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.LengthUnit.CENTIMETER; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class BodyHeightUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/body-height-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedBodyHeight() { new BodyHeight.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { LengthUnitValue lengthUnitValue = new LengthUnitValue(CENTIMETER, BigDecimal.valueOf(180)); BodyHeight bodyHeight = new BodyHeight.Builder(lengthUnitValue).build(); assertThat(bodyHeight, notNullValue()); assertThat(bodyHeight.getBodyHeight(), equalTo(lengthUnitValue)); assertThat(bodyHeight.getEffectiveTimeFrame(), nullValue()); assertThat(bodyHeight.getDescriptiveStatistic(), nullValue()); assertThat(bodyHeight.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { LengthUnitValue lengthUnitValue = new LengthUnitValue(CENTIMETER, BigDecimal.valueOf(180)); BodyHeight bodyHeight = new BodyHeight.Builder(lengthUnitValue)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BloodPressureUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.BloodPressureUnit.MM_OF_MERCURY; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.PositionDuringMeasurement.LYING_DOWN; import static org.openmhealth.schema.domain.omh.PositionDuringMeasurement.SITTING; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
public void constructorShouldThrowExceptionOnUndefinedSystolicBloodPressure() { new BloodPressure.Builder(null, diastolicBloodPressure); } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedDiastolicBloodPressure() { new BloodPressure.Builder(systolicBloodPressure, null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { BloodPressure bloodPressure = new BloodPressure.Builder(systolicBloodPressure, diastolicBloodPressure).build(); assertThat(bloodPressure, notNullValue()); assertThat(bloodPressure.getSystolicBloodPressure(), equalTo(systolicBloodPressure)); assertThat(bloodPressure.getDiastolicBloodPressure(), equalTo(diastolicBloodPressure)); assertThat(bloodPressure.getPositionDuringMeasurement(), nullValue()); assertThat(bloodPressure.getEffectiveTimeFrame(), nullValue()); assertThat(bloodPressure.getDescriptiveStatistic(), nullValue()); assertThat(bloodPressure.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { BloodPressure bloodPressure = new BloodPressure.Builder(systolicBloodPressure, diastolicBloodPressure) .setPositionDuringMeasurement(LYING_DOWN)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BloodPressureUnitTests.java import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.BloodPressureUnit.MM_OF_MERCURY; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.PositionDuringMeasurement.LYING_DOWN; import static org.openmhealth.schema.domain.omh.PositionDuringMeasurement.SITTING; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; public void constructorShouldThrowExceptionOnUndefinedSystolicBloodPressure() { new BloodPressure.Builder(null, diastolicBloodPressure); } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedDiastolicBloodPressure() { new BloodPressure.Builder(systolicBloodPressure, null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { BloodPressure bloodPressure = new BloodPressure.Builder(systolicBloodPressure, diastolicBloodPressure).build(); assertThat(bloodPressure, notNullValue()); assertThat(bloodPressure.getSystolicBloodPressure(), equalTo(systolicBloodPressure)); assertThat(bloodPressure.getDiastolicBloodPressure(), equalTo(diastolicBloodPressure)); assertThat(bloodPressure.getPositionDuringMeasurement(), nullValue()); assertThat(bloodPressure.getEffectiveTimeFrame(), nullValue()); assertThat(bloodPressure.getDescriptiveStatistic(), nullValue()); assertThat(bloodPressure.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { BloodPressure bloodPressure = new BloodPressure.Builder(systolicBloodPressure, diastolicBloodPressure) .setPositionDuringMeasurement(LYING_DOWN)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyMassIndex1UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.BodyMassIndexUnit1.KILOGRAMS_PER_SQUARE_METER; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class BodyMassIndex1UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/body-mass-index-1.0.json"; @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { TypedUnitValue<BodyMassIndexUnit1> bmiValue = new TypedUnitValue<>(KILOGRAMS_PER_SQUARE_METER, 20); BodyMassIndex1 bmi = new BodyMassIndex1.Builder(bmiValue).build(); assertThat(bmi, notNullValue()); assertThat(bmi.getBodyMassIndex(), equalTo(bmiValue)); assertThat(bmi.getEffectiveTimeFrame(), nullValue()); assertThat(bmi.getDescriptiveStatistic(), nullValue()); assertThat(bmi.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { TypedUnitValue<BodyMassIndexUnit1> bmiValue = new TypedUnitValue<>(KILOGRAMS_PER_SQUARE_METER, 20); BodyMassIndex1 bmi = new BodyMassIndex1.Builder(bmiValue)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyMassIndex1UnitTests.java import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.BodyMassIndexUnit1.KILOGRAMS_PER_SQUARE_METER; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class BodyMassIndex1UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/body-mass-index-1.0.json"; @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { TypedUnitValue<BodyMassIndexUnit1> bmiValue = new TypedUnitValue<>(KILOGRAMS_PER_SQUARE_METER, 20); BodyMassIndex1 bmi = new BodyMassIndex1.Builder(bmiValue).build(); assertThat(bmi, notNullValue()); assertThat(bmi.getBodyMassIndex(), equalTo(bmiValue)); assertThat(bmi.getEffectiveTimeFrame(), nullValue()); assertThat(bmi.getDescriptiveStatistic(), nullValue()); assertThat(bmi.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { TypedUnitValue<BodyMassIndexUnit1> bmiValue = new TypedUnitValue<>(KILOGRAMS_PER_SQUARE_METER, 20); BodyMassIndex1 bmi = new BodyMassIndex1.Builder(bmiValue)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyTemperatureUnitTests.java
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TemperatureUnit.java // public enum TemperatureUnit implements Unit { // // KELVIN("K"), // CELSIUS("C"), // FAHRENHEIT("F"); // // private static Map<String, TemperatureUnit> constantsBySchemaValue = Maps.newHashMap(); // private final String schemaValue; // // static { // for (TemperatureUnit unit : values()) { // constantsBySchemaValue.put(unit.getSchemaValue(), unit); // } // } // // TemperatureUnit(String schemaValue) { // this.schemaValue = schemaValue; // } // // @Override // @JsonValue // public String getSchemaValue() { // return schemaValue; // } // // @Nullable // @JsonCreator // public static TemperatureUnit findBySchemaValue(String schemaValue) { // return constantsBySchemaValue.get(schemaValue); // } // // public TemperatureUnitValue newUnitValue(BigDecimal value) { // return new TemperatureUnitValue(this, value); // } // // public TemperatureUnitValue newUnitValue(double value) { // return new TemperatureUnitValue(this, value); // } // // public TemperatureUnitValue newUnitValue(long value) { // return new TemperatureUnitValue(this, value); // } // } // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.BodyTemperature.MeasurementLocation.ORAL; import static org.openmhealth.schema.domain.omh.BodyTemperature.MeasurementLocation.RECTAL; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.TemperatureUnit.*; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Chris Schaefbauer */ public class BodyTemperatureUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/body-temperature-1.0.json"; @Override public String getSchemaFilename() { return SCHEMA_FILENAME; } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionWhenBodyTemperatureIsNull() { new BodyTemperature.Builder(null).build(); } @Test public void buildShouldConstructCorrectMeasureUsingOnlyRequiredProperties() { BodyTemperature bodyTemperature = new BodyTemperature.Builder(new TemperatureUnitValue(CELSIUS, 37.3)) .build(); assertThat(bodyTemperature.getBodyTemperature(), notNullValue()); assertThat(bodyTemperature.getBodyTemperature(), equalTo(new TemperatureUnitValue(CELSIUS, 37.3))); assertThat(bodyTemperature.getMeasurementLocation(), nullValue()); assertThat(bodyTemperature.getEffectiveTimeFrame(), nullValue()); assertThat(bodyTemperature.getDescriptiveStatistic(), nullValue()); assertThat(bodyTemperature.getUserNotes(), nullValue()); } @Test public void buildShouldConstructCorrectMeasureUsingOptionalProperties() { BodyTemperature bodyTemperature = new BodyTemperature.Builder(new TemperatureUnitValue(FAHRENHEIT, 99.8)) .setDescriptiveStatistic(MAXIMUM)
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TemperatureUnit.java // public enum TemperatureUnit implements Unit { // // KELVIN("K"), // CELSIUS("C"), // FAHRENHEIT("F"); // // private static Map<String, TemperatureUnit> constantsBySchemaValue = Maps.newHashMap(); // private final String schemaValue; // // static { // for (TemperatureUnit unit : values()) { // constantsBySchemaValue.put(unit.getSchemaValue(), unit); // } // } // // TemperatureUnit(String schemaValue) { // this.schemaValue = schemaValue; // } // // @Override // @JsonValue // public String getSchemaValue() { // return schemaValue; // } // // @Nullable // @JsonCreator // public static TemperatureUnit findBySchemaValue(String schemaValue) { // return constantsBySchemaValue.get(schemaValue); // } // // public TemperatureUnitValue newUnitValue(BigDecimal value) { // return new TemperatureUnitValue(this, value); // } // // public TemperatureUnitValue newUnitValue(double value) { // return new TemperatureUnitValue(this, value); // } // // public TemperatureUnitValue newUnitValue(long value) { // return new TemperatureUnitValue(this, value); // } // } // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyTemperatureUnitTests.java import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.BodyTemperature.MeasurementLocation.ORAL; import static org.openmhealth.schema.domain.omh.BodyTemperature.MeasurementLocation.RECTAL; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.TemperatureUnit.*; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Chris Schaefbauer */ public class BodyTemperatureUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/body-temperature-1.0.json"; @Override public String getSchemaFilename() { return SCHEMA_FILENAME; } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionWhenBodyTemperatureIsNull() { new BodyTemperature.Builder(null).build(); } @Test public void buildShouldConstructCorrectMeasureUsingOnlyRequiredProperties() { BodyTemperature bodyTemperature = new BodyTemperature.Builder(new TemperatureUnitValue(CELSIUS, 37.3)) .build(); assertThat(bodyTemperature.getBodyTemperature(), notNullValue()); assertThat(bodyTemperature.getBodyTemperature(), equalTo(new TemperatureUnitValue(CELSIUS, 37.3))); assertThat(bodyTemperature.getMeasurementLocation(), nullValue()); assertThat(bodyTemperature.getEffectiveTimeFrame(), nullValue()); assertThat(bodyTemperature.getDescriptiveStatistic(), nullValue()); assertThat(bodyTemperature.getUserNotes(), nullValue()); } @Test public void buildShouldConstructCorrectMeasureUsingOptionalProperties() { BodyTemperature bodyTemperature = new BodyTemperature.Builder(new TemperatureUnitValue(FAHRENHEIT, 99.8)) .setDescriptiveStatistic(MAXIMUM)
.setEffectiveTimeFrame(FIXED_POINT_IN_TIME)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/StepCount1UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class StepCount1UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/step-count-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedStepCount() { new StepCount1.Builder(null); } @Test(expectedExceptions = UnsupportedOperationException.class) public void setDescriptiveStatisticShouldThrowException() { new StepCount1.Builder(TEN).setDescriptiveStatistic(MEDIAN); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { StepCount1 stepCount = new StepCount1.Builder(TEN).build(); assertThat(stepCount, notNullValue()); assertThat(stepCount.getStepCount(), equalTo(TEN)); assertThat(stepCount.getEffectiveTimeFrame(), nullValue()); assertThat(stepCount.getDescriptiveStatistic(), nullValue()); assertThat(stepCount.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { StepCount1 stepCount = new StepCount1.Builder(TEN)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/StepCount1UnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class StepCount1UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/step-count-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedStepCount() { new StepCount1.Builder(null); } @Test(expectedExceptions = UnsupportedOperationException.class) public void setDescriptiveStatisticShouldThrowException() { new StepCount1.Builder(TEN).setDescriptiveStatistic(MEDIAN); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { StepCount1 stepCount = new StepCount1.Builder(TEN).build(); assertThat(stepCount, notNullValue()); assertThat(stepCount.getStepCount(), equalTo(TEN)); assertThat(stepCount.getEffectiveTimeFrame(), nullValue()); assertThat(stepCount.getDescriptiveStatistic(), nullValue()); assertThat(stepCount.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { StepCount1 stepCount = new StepCount1.Builder(TEN)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/StepCount1UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
assertThat(stepCount.getStepCount(), equalTo(TEN)); assertThat(stepCount.getEffectiveTimeFrame(), nullValue()); assertThat(stepCount.getDescriptiveStatistic(), nullValue()); assertThat(stepCount.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { StepCount1 stepCount = new StepCount1.Builder(TEN) .setEffectiveTimeFrame(FIXED_MONTH) .setUserNotes("feeling fine") .build(); assertThat(stepCount, notNullValue()); assertThat(stepCount.getStepCount(), equalTo(TEN)); assertThat(stepCount.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(stepCount.getDescriptiveStatistic(), nullValue()); assertThat(stepCount.getUserNotes(), equalTo("feeling fine")); } @Override protected String getSchemaFilename() { return SCHEMA_FILENAME; } @Test public void measureShouldSerializeCorrectly() throws Exception { StepCount1 stepCount = new StepCount1.Builder(BigDecimal.valueOf(6000))
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/StepCount1UnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; assertThat(stepCount.getStepCount(), equalTo(TEN)); assertThat(stepCount.getEffectiveTimeFrame(), nullValue()); assertThat(stepCount.getDescriptiveStatistic(), nullValue()); assertThat(stepCount.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { StepCount1 stepCount = new StepCount1.Builder(TEN) .setEffectiveTimeFrame(FIXED_MONTH) .setUserNotes("feeling fine") .build(); assertThat(stepCount, notNullValue()); assertThat(stepCount.getStepCount(), equalTo(TEN)); assertThat(stepCount.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(stepCount.getDescriptiveStatistic(), nullValue()); assertThat(stepCount.getUserNotes(), equalTo("feeling fine")); } @Override protected String getSchemaFilename() { return SCHEMA_FILENAME; } @Test public void measureShouldSerializeCorrectly() throws Exception { StepCount1 stepCount = new StepCount1.Builder(BigDecimal.valueOf(6000))
.setEffectiveTimeFrame(FIXED_DAY)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyFatPercentageUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // // Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TimeInterval.java // public static TimeInterval ofStartDateTimeAndEndDateTime(OffsetDateTime startDateTime, OffsetDateTime endDateTime) { // // checkNotNull(startDateTime, "A start date time hasn't been specified."); // checkNotNull(endDateTime, "An end date time hasn't been specified."); // checkArgument(!endDateTime.isBefore(startDateTime), "The specified start and end date times are reversed."); // // TimeInterval timeInterval = new TimeInterval(); // // timeInterval.startDateTime = startDateTime; // timeInterval.endDateTime = endDateTime; // // return timeInterval; // }
import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; import static org.openmhealth.schema.domain.omh.TimeInterval.ofStartDateTimeAndEndDateTime;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Chris Schaefbauer */ public class BodyFatPercentageUnitTests extends SerializationUnitTests { private static final String SCHEMA_FILENAME = "schema/omh/body-fat-percentage-1.0.json"; @Override public String getSchemaFilename() { return SCHEMA_FILENAME; } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionWhenBodyTemperatureIsNull() { new BodyFatPercentage.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 22.3)) .build(); assertThat(bodyFatPercentage, notNullValue()); assertThat(bodyFatPercentage.getBodyFatPercentage().getTypedUnit(), equalTo(PERCENT)); assertThat(bodyFatPercentage.getBodyFatPercentage().getValue().doubleValue(), equalTo(22.3)); assertThat(bodyFatPercentage.getEffectiveTimeFrame(), nullValue()); assertThat(bodyFatPercentage.getDescriptiveStatistic(), nullValue()); assertThat(bodyFatPercentage.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 31)) .setDescriptiveStatistic(MAXIMUM)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // // Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TimeInterval.java // public static TimeInterval ofStartDateTimeAndEndDateTime(OffsetDateTime startDateTime, OffsetDateTime endDateTime) { // // checkNotNull(startDateTime, "A start date time hasn't been specified."); // checkNotNull(endDateTime, "An end date time hasn't been specified."); // checkArgument(!endDateTime.isBefore(startDateTime), "The specified start and end date times are reversed."); // // TimeInterval timeInterval = new TimeInterval(); // // timeInterval.startDateTime = startDateTime; // timeInterval.endDateTime = endDateTime; // // return timeInterval; // } // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyFatPercentageUnitTests.java import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; import static org.openmhealth.schema.domain.omh.TimeInterval.ofStartDateTimeAndEndDateTime; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Chris Schaefbauer */ public class BodyFatPercentageUnitTests extends SerializationUnitTests { private static final String SCHEMA_FILENAME = "schema/omh/body-fat-percentage-1.0.json"; @Override public String getSchemaFilename() { return SCHEMA_FILENAME; } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionWhenBodyTemperatureIsNull() { new BodyFatPercentage.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 22.3)) .build(); assertThat(bodyFatPercentage, notNullValue()); assertThat(bodyFatPercentage.getBodyFatPercentage().getTypedUnit(), equalTo(PERCENT)); assertThat(bodyFatPercentage.getBodyFatPercentage().getValue().doubleValue(), equalTo(22.3)); assertThat(bodyFatPercentage.getEffectiveTimeFrame(), nullValue()); assertThat(bodyFatPercentage.getDescriptiveStatistic(), nullValue()); assertThat(bodyFatPercentage.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 31)) .setDescriptiveStatistic(MAXIMUM)
.setEffectiveTimeFrame(FIXED_POINT_IN_TIME)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyFatPercentageUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // // Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TimeInterval.java // public static TimeInterval ofStartDateTimeAndEndDateTime(OffsetDateTime startDateTime, OffsetDateTime endDateTime) { // // checkNotNull(startDateTime, "A start date time hasn't been specified."); // checkNotNull(endDateTime, "An end date time hasn't been specified."); // checkArgument(!endDateTime.isBefore(startDateTime), "The specified start and end date times are reversed."); // // TimeInterval timeInterval = new TimeInterval(); // // timeInterval.startDateTime = startDateTime; // timeInterval.endDateTime = endDateTime; // // return timeInterval; // }
import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; import static org.openmhealth.schema.domain.omh.TimeInterval.ofStartDateTimeAndEndDateTime;
assertThat(bodyFatPercentage.getBodyFatPercentage().getTypedUnit(), equalTo(PERCENT)); assertThat(bodyFatPercentage.getBodyFatPercentage().getValue().doubleValue(), equalTo(22.3)); assertThat(bodyFatPercentage.getEffectiveTimeFrame(), nullValue()); assertThat(bodyFatPercentage.getDescriptiveStatistic(), nullValue()); assertThat(bodyFatPercentage.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 31)) .setDescriptiveStatistic(MAXIMUM) .setEffectiveTimeFrame(FIXED_POINT_IN_TIME) .setUserNotes("some note") .build(); assertThat(bodyFatPercentage, notNullValue()); assertThat(bodyFatPercentage.getBodyFatPercentage().getTypedUnit(), equalTo(PERCENT)); assertThat(bodyFatPercentage.getBodyFatPercentage().getValue().intValue(), equalTo(31)); assertThat(bodyFatPercentage.getDescriptiveStatistic(), equalTo(MAXIMUM)); assertThat(bodyFatPercentage.getEffectiveTimeFrame(), equalTo(FIXED_POINT_IN_TIME)); assertThat(bodyFatPercentage.getUserNotes(), equalTo("some note")); } @Test public void measureShouldSerializeCorrectly() throws Exception { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 16)) .setDescriptiveStatistic(MAXIMUM)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // // Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TimeInterval.java // public static TimeInterval ofStartDateTimeAndEndDateTime(OffsetDateTime startDateTime, OffsetDateTime endDateTime) { // // checkNotNull(startDateTime, "A start date time hasn't been specified."); // checkNotNull(endDateTime, "An end date time hasn't been specified."); // checkArgument(!endDateTime.isBefore(startDateTime), "The specified start and end date times are reversed."); // // TimeInterval timeInterval = new TimeInterval(); // // timeInterval.startDateTime = startDateTime; // timeInterval.endDateTime = endDateTime; // // return timeInterval; // } // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyFatPercentageUnitTests.java import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; import static org.openmhealth.schema.domain.omh.TimeInterval.ofStartDateTimeAndEndDateTime; assertThat(bodyFatPercentage.getBodyFatPercentage().getTypedUnit(), equalTo(PERCENT)); assertThat(bodyFatPercentage.getBodyFatPercentage().getValue().doubleValue(), equalTo(22.3)); assertThat(bodyFatPercentage.getEffectiveTimeFrame(), nullValue()); assertThat(bodyFatPercentage.getDescriptiveStatistic(), nullValue()); assertThat(bodyFatPercentage.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 31)) .setDescriptiveStatistic(MAXIMUM) .setEffectiveTimeFrame(FIXED_POINT_IN_TIME) .setUserNotes("some note") .build(); assertThat(bodyFatPercentage, notNullValue()); assertThat(bodyFatPercentage.getBodyFatPercentage().getTypedUnit(), equalTo(PERCENT)); assertThat(bodyFatPercentage.getBodyFatPercentage().getValue().intValue(), equalTo(31)); assertThat(bodyFatPercentage.getDescriptiveStatistic(), equalTo(MAXIMUM)); assertThat(bodyFatPercentage.getEffectiveTimeFrame(), equalTo(FIXED_POINT_IN_TIME)); assertThat(bodyFatPercentage.getUserNotes(), equalTo("some note")); } @Test public void measureShouldSerializeCorrectly() throws Exception { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 16)) .setDescriptiveStatistic(MAXIMUM)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyFatPercentageUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // // Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TimeInterval.java // public static TimeInterval ofStartDateTimeAndEndDateTime(OffsetDateTime startDateTime, OffsetDateTime endDateTime) { // // checkNotNull(startDateTime, "A start date time hasn't been specified."); // checkNotNull(endDateTime, "An end date time hasn't been specified."); // checkArgument(!endDateTime.isBefore(startDateTime), "The specified start and end date times are reversed."); // // TimeInterval timeInterval = new TimeInterval(); // // timeInterval.startDateTime = startDateTime; // timeInterval.endDateTime = endDateTime; // // return timeInterval; // }
import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; import static org.openmhealth.schema.domain.omh.TimeInterval.ofStartDateTimeAndEndDateTime;
public void measureShouldSerializeCorrectly() throws Exception { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 16)) .setDescriptiveStatistic(MAXIMUM) .setEffectiveTimeFrame(FIXED_MONTH) .build(); String expectedDocument = "{\n" + " \"body_fat_percentage\": {\n" + " \"value\": 16,\n" + " \"unit\": \"%\"\n" + " },\n" + " \"effective_time_frame\": {\n" + " \"time_interval\": {\n" + " \"start_date_time\": \"2015-10-01T00:00:00-07:00\",\n" + " \"end_date_time\": \"2015-11-01T00:00:00-07:00\"\n" + " }\n" + " },\n" + " \"descriptive_statistic\": \"maximum\"\n" + "}"; serializationShouldCreateValidDocument(bodyFatPercentage, expectedDocument); deserializationShouldCreateValidObject(expectedDocument, bodyFatPercentage); } @Test public void equalsShouldReturnTrueWhenSameValuesForAllValues() { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 16)) .setDescriptiveStatistic(MAXIMUM)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // // Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TimeInterval.java // public static TimeInterval ofStartDateTimeAndEndDateTime(OffsetDateTime startDateTime, OffsetDateTime endDateTime) { // // checkNotNull(startDateTime, "A start date time hasn't been specified."); // checkNotNull(endDateTime, "An end date time hasn't been specified."); // checkArgument(!endDateTime.isBefore(startDateTime), "The specified start and end date times are reversed."); // // TimeInterval timeInterval = new TimeInterval(); // // timeInterval.startDateTime = startDateTime; // timeInterval.endDateTime = endDateTime; // // return timeInterval; // } // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyFatPercentageUnitTests.java import org.testng.annotations.Test; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.PercentUnit.PERCENT; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; import static org.openmhealth.schema.domain.omh.TimeInterval.ofStartDateTimeAndEndDateTime; public void measureShouldSerializeCorrectly() throws Exception { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 16)) .setDescriptiveStatistic(MAXIMUM) .setEffectiveTimeFrame(FIXED_MONTH) .build(); String expectedDocument = "{\n" + " \"body_fat_percentage\": {\n" + " \"value\": 16,\n" + " \"unit\": \"%\"\n" + " },\n" + " \"effective_time_frame\": {\n" + " \"time_interval\": {\n" + " \"start_date_time\": \"2015-10-01T00:00:00-07:00\",\n" + " \"end_date_time\": \"2015-11-01T00:00:00-07:00\"\n" + " }\n" + " },\n" + " \"descriptive_statistic\": \"maximum\"\n" + "}"; serializationShouldCreateValidDocument(bodyFatPercentage, expectedDocument); deserializationShouldCreateValidObject(expectedDocument, bodyFatPercentage); } @Test public void equalsShouldReturnTrueWhenSameValuesForAllValues() { BodyFatPercentage bodyFatPercentage = new BodyFatPercentage.Builder(new TypedUnitValue<>(PERCENT, 16)) .setDescriptiveStatistic(MAXIMUM)
.setEffectiveTimeFrame(ofStartDateTimeAndEndDateTime(OffsetDateTime.parse("2013-01-01T00:00:00Z"),
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyWeightUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.MassUnit.KILOGRAM; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class BodyWeightUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/body-weight-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedBodyWeight() { new BodyWeight.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { MassUnitValue massUnitValue = new MassUnitValue(KILOGRAM, BigDecimal.valueOf(65)); BodyWeight bodyWeight = new BodyWeight.Builder(massUnitValue).build(); assertThat(bodyWeight, notNullValue()); assertThat(bodyWeight.getBodyWeight(), equalTo(massUnitValue)); assertThat(bodyWeight.getEffectiveTimeFrame(), nullValue()); assertThat(bodyWeight.getDescriptiveStatistic(), nullValue()); assertThat(bodyWeight.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingTimeIntervalTimeFrame() { MassUnitValue massUnitValue = new MassUnitValue(KILOGRAM, BigDecimal.valueOf(65)); BodyWeight bodyWeight = new BodyWeight.Builder(massUnitValue)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyWeightUnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.MassUnit.KILOGRAM; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class BodyWeightUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/body-weight-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedBodyWeight() { new BodyWeight.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { MassUnitValue massUnitValue = new MassUnitValue(KILOGRAM, BigDecimal.valueOf(65)); BodyWeight bodyWeight = new BodyWeight.Builder(massUnitValue).build(); assertThat(bodyWeight, notNullValue()); assertThat(bodyWeight.getBodyWeight(), equalTo(massUnitValue)); assertThat(bodyWeight.getEffectiveTimeFrame(), nullValue()); assertThat(bodyWeight.getDescriptiveStatistic(), nullValue()); assertThat(bodyWeight.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingTimeIntervalTimeFrame() { MassUnitValue massUnitValue = new MassUnitValue(KILOGRAM, BigDecimal.valueOf(65)); BodyWeight bodyWeight = new BodyWeight.Builder(massUnitValue)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyWeightUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.MassUnit.KILOGRAM; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME;
assertThat(bodyWeight.getBodyWeight(), equalTo(massUnitValue)); assertThat(bodyWeight.getEffectiveTimeFrame(), nullValue()); assertThat(bodyWeight.getDescriptiveStatistic(), nullValue()); assertThat(bodyWeight.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingTimeIntervalTimeFrame() { MassUnitValue massUnitValue = new MassUnitValue(KILOGRAM, BigDecimal.valueOf(65)); BodyWeight bodyWeight = new BodyWeight.Builder(massUnitValue) .setEffectiveTimeFrame(FIXED_MONTH) .setDescriptiveStatistic(AVERAGE) .setUserNotes("feeling fine") .build(); assertThat(bodyWeight, notNullValue()); assertThat(bodyWeight.getBodyWeight(), equalTo(massUnitValue)); assertThat(bodyWeight.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(bodyWeight.getDescriptiveStatistic(), equalTo(AVERAGE)); assertThat(bodyWeight.getUserNotes(), equalTo("feeling fine")); } @Test public void buildShouldConstructMeasureUsingDateTimeTimeFrame() { MassUnitValue massUnitValue = new MassUnitValue(KILOGRAM, BigDecimal.valueOf(65)); BodyWeight bodyWeight = new BodyWeight.Builder(massUnitValue)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyWeightUnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.MassUnit.KILOGRAM; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; assertThat(bodyWeight.getBodyWeight(), equalTo(massUnitValue)); assertThat(bodyWeight.getEffectiveTimeFrame(), nullValue()); assertThat(bodyWeight.getDescriptiveStatistic(), nullValue()); assertThat(bodyWeight.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingTimeIntervalTimeFrame() { MassUnitValue massUnitValue = new MassUnitValue(KILOGRAM, BigDecimal.valueOf(65)); BodyWeight bodyWeight = new BodyWeight.Builder(massUnitValue) .setEffectiveTimeFrame(FIXED_MONTH) .setDescriptiveStatistic(AVERAGE) .setUserNotes("feeling fine") .build(); assertThat(bodyWeight, notNullValue()); assertThat(bodyWeight.getBodyWeight(), equalTo(massUnitValue)); assertThat(bodyWeight.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(bodyWeight.getDescriptiveStatistic(), equalTo(AVERAGE)); assertThat(bodyWeight.getUserNotes(), equalTo("feeling fine")); } @Test public void buildShouldConstructMeasureUsingDateTimeTimeFrame() { MassUnitValue massUnitValue = new MassUnitValue(KILOGRAM, BigDecimal.valueOf(65)); BodyWeight bodyWeight = new BodyWeight.Builder(massUnitValue)
.setEffectiveTimeFrame(FIXED_POINT_IN_TIME)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/MinutesModerateActivityUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.MINUTE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class MinutesModerateActivityUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/minutes-moderate-activity-1.0.json"; @Test(expectedExceptions = IllegalArgumentException.class) public void constructorShouldThrowExceptionOnInvalidDurationUnit() { new MinutesModerateActivity.Builder(new DurationUnitValue(HOUR, ONE)); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { DurationUnitValue durationUnitValue = new DurationUnitValue(MINUTE, TEN); MinutesModerateActivity minutesModerateActivity = new MinutesModerateActivity.Builder(durationUnitValue).build(); assertThat(minutesModerateActivity, notNullValue()); assertThat(minutesModerateActivity.getMinutesModerateActivity(), equalTo(durationUnitValue)); assertThat(minutesModerateActivity.getEffectiveTimeFrame(), nullValue()); assertThat(minutesModerateActivity.getDescriptiveStatistic(), nullValue()); assertThat(minutesModerateActivity.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { DurationUnitValue durationUnitValue = new DurationUnitValue(MINUTE, TEN); MinutesModerateActivity minutesModerateActivity = new MinutesModerateActivity.Builder(durationUnitValue)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/MinutesModerateActivityUnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.MINUTE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class MinutesModerateActivityUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/minutes-moderate-activity-1.0.json"; @Test(expectedExceptions = IllegalArgumentException.class) public void constructorShouldThrowExceptionOnInvalidDurationUnit() { new MinutesModerateActivity.Builder(new DurationUnitValue(HOUR, ONE)); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { DurationUnitValue durationUnitValue = new DurationUnitValue(MINUTE, TEN); MinutesModerateActivity minutesModerateActivity = new MinutesModerateActivity.Builder(durationUnitValue).build(); assertThat(minutesModerateActivity, notNullValue()); assertThat(minutesModerateActivity.getMinutesModerateActivity(), equalTo(durationUnitValue)); assertThat(minutesModerateActivity.getEffectiveTimeFrame(), nullValue()); assertThat(minutesModerateActivity.getDescriptiveStatistic(), nullValue()); assertThat(minutesModerateActivity.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { DurationUnitValue durationUnitValue = new DurationUnitValue(MINUTE, TEN); MinutesModerateActivity minutesModerateActivity = new MinutesModerateActivity.Builder(durationUnitValue)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/HeartRateUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.HeartRateUnit.BEATS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.AFTER_EXERCISE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.AT_REST; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToSleep.BEFORE_SLEEPING; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class HeartRateUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/heart-rate-1.1.json"; @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { BigDecimal heartRateValue = BigDecimal.valueOf(60); HeartRate heartRate = new HeartRate.Builder(heartRateValue).build(); assertThat(heartRate, notNullValue()); assertThat(heartRate.getHeartRate(), equalTo(new TypedUnitValue<>(BEATS_PER_MINUTE, heartRateValue))); assertThat(heartRate.getTemporalRelationshipToPhysicalActivity(), nullValue()); assertThat(heartRate.getTemporalRelationshipToSleep(), nullValue()); assertThat(heartRate.getEffectiveTimeFrame(), nullValue()); assertThat(heartRate.getDescriptiveStatistic(), nullValue()); assertThat(heartRate.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { BigDecimal heartRateValue = BigDecimal.valueOf(60); HeartRate heartRate = new HeartRate.Builder(heartRateValue) .setTemporalRelationshipToPhysicalActivity(AFTER_EXERCISE) .setTemporalRelationshipToSleep(BEFORE_SLEEPING)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/HeartRateUnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.HeartRateUnit.BEATS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.AFTER_EXERCISE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.AT_REST; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToSleep.BEFORE_SLEEPING; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class HeartRateUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/heart-rate-1.1.json"; @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { BigDecimal heartRateValue = BigDecimal.valueOf(60); HeartRate heartRate = new HeartRate.Builder(heartRateValue).build(); assertThat(heartRate, notNullValue()); assertThat(heartRate.getHeartRate(), equalTo(new TypedUnitValue<>(BEATS_PER_MINUTE, heartRateValue))); assertThat(heartRate.getTemporalRelationshipToPhysicalActivity(), nullValue()); assertThat(heartRate.getTemporalRelationshipToSleep(), nullValue()); assertThat(heartRate.getEffectiveTimeFrame(), nullValue()); assertThat(heartRate.getDescriptiveStatistic(), nullValue()); assertThat(heartRate.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { BigDecimal heartRateValue = BigDecimal.valueOf(60); HeartRate heartRate = new HeartRate.Builder(heartRateValue) .setTemporalRelationshipToPhysicalActivity(AFTER_EXERCISE) .setTemporalRelationshipToSleep(BEFORE_SLEEPING)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/HeartRateUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.HeartRateUnit.BEATS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.AFTER_EXERCISE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.AT_REST; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToSleep.BEFORE_SLEEPING; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME;
BigDecimal heartRateValue = BigDecimal.valueOf(60); HeartRate heartRate = new HeartRate.Builder(heartRateValue) .setTemporalRelationshipToPhysicalActivity(AFTER_EXERCISE) .setTemporalRelationshipToSleep(BEFORE_SLEEPING) .setEffectiveTimeFrame(FIXED_MONTH) .setDescriptiveStatistic(AVERAGE) .setUserNotes("feeling fine") .build(); assertThat(heartRate, notNullValue()); assertThat(heartRate.getHeartRate(), equalTo(new TypedUnitValue<>(BEATS_PER_MINUTE, heartRateValue))); assertThat(heartRate.getTemporalRelationshipToPhysicalActivity(), equalTo(AFTER_EXERCISE)); assertThat(heartRate.getTemporalRelationshipToSleep(), equalTo(BEFORE_SLEEPING)); assertThat(heartRate.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(heartRate.getDescriptiveStatistic(), equalTo(AVERAGE)); assertThat(heartRate.getUserNotes(), equalTo("feeling fine")); } @Override protected String getSchemaFilename() { return SCHEMA_FILENAME; } @Test public void measureShouldSerializeCorrectly() throws Exception { HeartRate heartRate = new HeartRate.Builder(BigDecimal.valueOf(50)) .setTemporalRelationshipToPhysicalActivity(AT_REST) .setTemporalRelationshipToSleep(BEFORE_SLEEPING)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/HeartRateUnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.HeartRateUnit.BEATS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.AFTER_EXERCISE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.AT_REST; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToSleep.BEFORE_SLEEPING; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; BigDecimal heartRateValue = BigDecimal.valueOf(60); HeartRate heartRate = new HeartRate.Builder(heartRateValue) .setTemporalRelationshipToPhysicalActivity(AFTER_EXERCISE) .setTemporalRelationshipToSleep(BEFORE_SLEEPING) .setEffectiveTimeFrame(FIXED_MONTH) .setDescriptiveStatistic(AVERAGE) .setUserNotes("feeling fine") .build(); assertThat(heartRate, notNullValue()); assertThat(heartRate.getHeartRate(), equalTo(new TypedUnitValue<>(BEATS_PER_MINUTE, heartRateValue))); assertThat(heartRate.getTemporalRelationshipToPhysicalActivity(), equalTo(AFTER_EXERCISE)); assertThat(heartRate.getTemporalRelationshipToSleep(), equalTo(BEFORE_SLEEPING)); assertThat(heartRate.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(heartRate.getDescriptiveStatistic(), equalTo(AVERAGE)); assertThat(heartRate.getUserNotes(), equalTo("feeling fine")); } @Override protected String getSchemaFilename() { return SCHEMA_FILENAME; } @Test public void measureShouldSerializeCorrectly() throws Exception { HeartRate heartRate = new HeartRate.Builder(BigDecimal.valueOf(50)) .setTemporalRelationshipToPhysicalActivity(AT_REST) .setTemporalRelationshipToSleep(BEFORE_SLEEPING)
.setEffectiveTimeFrame(FIXED_POINT_IN_TIME)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/CaloriesBurned1UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.KcalUnit.KILOCALORIE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class CaloriesBurned1UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/calories-burned-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedCaloriesBurned() { new CaloriesBurned1.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { KcalUnitValue kcalBurned = new KcalUnitValue(KILOCALORIE, 200); CaloriesBurned1 caloriesBurned = new CaloriesBurned1.Builder(kcalBurned).build(); assertThat(caloriesBurned, notNullValue()); assertThat(caloriesBurned.getKcalBurned(), equalTo(kcalBurned)); assertThat(caloriesBurned.getActivityName(), nullValue()); assertThat(caloriesBurned.getEffectiveTimeFrame(), nullValue()); assertThat(caloriesBurned.getDescriptiveStatistic(), nullValue()); assertThat(caloriesBurned.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { KcalUnitValue kcalBurned = new KcalUnitValue(KILOCALORIE, 800); CaloriesBurned1 caloriesBurned = new CaloriesBurned1.Builder(kcalBurned) .setActivityName("swimming")
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/CaloriesBurned1UnitTests.java import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.KcalUnit.KILOCALORIE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class CaloriesBurned1UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/calories-burned-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedCaloriesBurned() { new CaloriesBurned1.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { KcalUnitValue kcalBurned = new KcalUnitValue(KILOCALORIE, 200); CaloriesBurned1 caloriesBurned = new CaloriesBurned1.Builder(kcalBurned).build(); assertThat(caloriesBurned, notNullValue()); assertThat(caloriesBurned.getKcalBurned(), equalTo(kcalBurned)); assertThat(caloriesBurned.getActivityName(), nullValue()); assertThat(caloriesBurned.getEffectiveTimeFrame(), nullValue()); assertThat(caloriesBurned.getDescriptiveStatistic(), nullValue()); assertThat(caloriesBurned.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { KcalUnitValue kcalBurned = new KcalUnitValue(KILOCALORIE, 800); CaloriesBurned1 caloriesBurned = new CaloriesBurned1.Builder(kcalBurned) .setActivityName("swimming")
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyMassIndex2UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.BodyMassIndexUnit2.KILOGRAMS_PER_SQUARE_METER; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class BodyMassIndex2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/body-mass-index-2.0.json"; @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { TypedUnitValue<BodyMassIndexUnit2> bmiValue = new TypedUnitValue<>(KILOGRAMS_PER_SQUARE_METER, 20);
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BodyMassIndex2UnitTests.java import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.BodyMassIndexUnit2.KILOGRAMS_PER_SQUARE_METER; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class BodyMassIndex2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/body-mass-index-2.0.json"; @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { TypedUnitValue<BodyMassIndexUnit2> bmiValue = new TypedUnitValue<>(KILOGRAMS_PER_SQUARE_METER, 20);
BodyMassIndex2 bmi = new BodyMassIndex2.Builder(bmiValue, FIXED_MONTH).build();
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/DataPointUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import static org.openmhealth.schema.domain.omh.PhysicalActivity.SelfReportedIntensity.MODERATE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.math.BigDecimal; import java.time.OffsetDateTime; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static java.time.ZoneOffset.UTC; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.LengthUnit.MILE;
@Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedBody() { new DataPoint<>(header, null); } @Test public void constructorShouldWork() { Map<String,String> body = new HashMap<>(); body.put("key", "value"); DataPoint dataPoint = new DataPoint<>(header, body); assertThat(dataPoint, notNullValue()); assertThat(dataPoint.getHeader(), equalTo(header)); assertThat(dataPoint.getBody(), equalTo(body)); } @Override protected String getSchemaFilename() { return SCHEMA_FILENAME; } @Test public void objectShouldSerializeCorrectly() throws Exception { PhysicalActivity physicalActivity = new PhysicalActivity.Builder("walking") .setDistance(new LengthUnitValue(MILE, BigDecimal.valueOf(1.5))) .setReportedActivityIntensity(MODERATE)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/DataPointUnitTests.java import static org.openmhealth.schema.domain.omh.PhysicalActivity.SelfReportedIntensity.MODERATE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.math.BigDecimal; import java.time.OffsetDateTime; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static java.time.ZoneOffset.UTC; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.LengthUnit.MILE; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedBody() { new DataPoint<>(header, null); } @Test public void constructorShouldWork() { Map<String,String> body = new HashMap<>(); body.put("key", "value"); DataPoint dataPoint = new DataPoint<>(header, body); assertThat(dataPoint, notNullValue()); assertThat(dataPoint.getHeader(), equalTo(header)); assertThat(dataPoint.getBody(), equalTo(body)); } @Override protected String getSchemaFilename() { return SCHEMA_FILENAME; } @Test public void objectShouldSerializeCorrectly() throws Exception { PhysicalActivity physicalActivity = new PhysicalActivity.Builder("walking") .setDistance(new LengthUnitValue(MILE, BigDecimal.valueOf(1.5))) .setReportedActivityIntensity(MODERATE)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/RespiratoryRateUnitTests.java
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/RespiratoryRate.java // public enum RespirationUnit implements Unit { // // BREATHS_PER_MINUTE("breaths/min"); // // private final String schemaValue; // private static final Map<String, RespirationUnit> constantsBySchemaValue = Maps.newHashMap(); // // static { // for (RespirationUnit unit : values()) { // constantsBySchemaValue.put(unit.getSchemaValue(), unit); // } // } // // RespirationUnit(String schemaValue) { // this.schemaValue = schemaValue; // } // // @Override // @JsonValue // public String getSchemaValue() { // return schemaValue; // } // // @JsonCreator // @Nullable // public RespirationUnit findBySchemaValue(String schemaValue) { // return constantsBySchemaValue.get(schemaValue); // } // } // // Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TemporalRelationshipToPhysicalActivity.java // public enum TemporalRelationshipToPhysicalActivity implements SchemaEnumValue, SchemaSupport { // // AT_REST, // ACTIVE, // BEFORE_EXERCISE, // AFTER_EXERCISE, // DURING_EXERCISE; // // public static final SchemaId SCHEMA_ID = // new SchemaId(OMH_NAMESPACE, "temporal-relationship-to-physical-activity", "1.0"); // // private String schemaValue; // private static final Map<String, TemporalRelationshipToPhysicalActivity> constantsBySchemaValue = new HashMap<>(); // // static { // for (TemporalRelationshipToPhysicalActivity constant : values()) { // constantsBySchemaValue.put(constant.getSchemaValue(), constant); // } // } // // TemporalRelationshipToPhysicalActivity() { // this.schemaValue = name().toLowerCase().replace('_', ' '); // } // // @Override // public SchemaId getSchemaId() { // return SCHEMA_ID; // } // // @Override // @JsonValue // public String getSchemaValue() { // return this.schemaValue; // } // // @Nullable // @JsonCreator // public static TemporalRelationshipToPhysicalActivity findBySchemaValue(String schemaValue) { // return constantsBySchemaValue.get(schemaValue); // } // } // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import org.openmhealth.schema.domain.omh.RespiratoryRate.RespirationUnit; import org.testng.annotations.Test; import java.math.BigDecimal; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.RespiratoryRate.RespirationUnit.BREATHS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.*; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Chris Schaefbauer */ public class RespiratoryRateUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/respiratory-rate-1.0.json"; @Override public String getSchemaFilename() { return SCHEMA_FILENAME; } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedRespiratoryRate() { new RespiratoryRate.Builder(null); } @Test public void buildShouldConstructMeasureCorrectlyUsingOnlyRequiredProperties() { RespiratoryRate respiratoryRate = new RespiratoryRate.Builder(new TypedUnitValue<>(BREATHS_PER_MINUTE, 20)) .build(); assertThat(respiratoryRate, notNullValue()); assertThat(respiratoryRate.getRespiratoryRate(), notNullValue()); assertThat(respiratoryRate.getRespiratoryRate().getTypedUnit(), equalTo(BREATHS_PER_MINUTE)); assertThat(respiratoryRate.getRespiratoryRate().getValue(), equalTo(BigDecimal.valueOf(20))); assertThat(respiratoryRate.getEffectiveTimeFrame(), nullValue()); assertThat(respiratoryRate.getUserNotes(), nullValue()); assertThat(respiratoryRate.getDescriptiveStatistic(), nullValue()); assertThat(respiratoryRate.getTemporalRelationshipToPhysicalActivity(), nullValue()); } @Test public void buildShouldConstructMeasureCorrectlyUsingOptionalProperties() { RespiratoryRate respiratoryRate = new RespiratoryRate.Builder(new TypedUnitValue<>(BREATHS_PER_MINUTE, 15.5)) .setDescriptiveStatistic(MAXIMUM)
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/RespiratoryRate.java // public enum RespirationUnit implements Unit { // // BREATHS_PER_MINUTE("breaths/min"); // // private final String schemaValue; // private static final Map<String, RespirationUnit> constantsBySchemaValue = Maps.newHashMap(); // // static { // for (RespirationUnit unit : values()) { // constantsBySchemaValue.put(unit.getSchemaValue(), unit); // } // } // // RespirationUnit(String schemaValue) { // this.schemaValue = schemaValue; // } // // @Override // @JsonValue // public String getSchemaValue() { // return schemaValue; // } // // @JsonCreator // @Nullable // public RespirationUnit findBySchemaValue(String schemaValue) { // return constantsBySchemaValue.get(schemaValue); // } // } // // Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TemporalRelationshipToPhysicalActivity.java // public enum TemporalRelationshipToPhysicalActivity implements SchemaEnumValue, SchemaSupport { // // AT_REST, // ACTIVE, // BEFORE_EXERCISE, // AFTER_EXERCISE, // DURING_EXERCISE; // // public static final SchemaId SCHEMA_ID = // new SchemaId(OMH_NAMESPACE, "temporal-relationship-to-physical-activity", "1.0"); // // private String schemaValue; // private static final Map<String, TemporalRelationshipToPhysicalActivity> constantsBySchemaValue = new HashMap<>(); // // static { // for (TemporalRelationshipToPhysicalActivity constant : values()) { // constantsBySchemaValue.put(constant.getSchemaValue(), constant); // } // } // // TemporalRelationshipToPhysicalActivity() { // this.schemaValue = name().toLowerCase().replace('_', ' '); // } // // @Override // public SchemaId getSchemaId() { // return SCHEMA_ID; // } // // @Override // @JsonValue // public String getSchemaValue() { // return this.schemaValue; // } // // @Nullable // @JsonCreator // public static TemporalRelationshipToPhysicalActivity findBySchemaValue(String schemaValue) { // return constantsBySchemaValue.get(schemaValue); // } // } // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/RespiratoryRateUnitTests.java import org.openmhealth.schema.domain.omh.RespiratoryRate.RespirationUnit; import org.testng.annotations.Test; import java.math.BigDecimal; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.RespiratoryRate.RespirationUnit.BREATHS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.*; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Chris Schaefbauer */ public class RespiratoryRateUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/respiratory-rate-1.0.json"; @Override public String getSchemaFilename() { return SCHEMA_FILENAME; } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedRespiratoryRate() { new RespiratoryRate.Builder(null); } @Test public void buildShouldConstructMeasureCorrectlyUsingOnlyRequiredProperties() { RespiratoryRate respiratoryRate = new RespiratoryRate.Builder(new TypedUnitValue<>(BREATHS_PER_MINUTE, 20)) .build(); assertThat(respiratoryRate, notNullValue()); assertThat(respiratoryRate.getRespiratoryRate(), notNullValue()); assertThat(respiratoryRate.getRespiratoryRate().getTypedUnit(), equalTo(BREATHS_PER_MINUTE)); assertThat(respiratoryRate.getRespiratoryRate().getValue(), equalTo(BigDecimal.valueOf(20))); assertThat(respiratoryRate.getEffectiveTimeFrame(), nullValue()); assertThat(respiratoryRate.getUserNotes(), nullValue()); assertThat(respiratoryRate.getDescriptiveStatistic(), nullValue()); assertThat(respiratoryRate.getTemporalRelationshipToPhysicalActivity(), nullValue()); } @Test public void buildShouldConstructMeasureCorrectlyUsingOptionalProperties() { RespiratoryRate respiratoryRate = new RespiratoryRate.Builder(new TypedUnitValue<>(BREATHS_PER_MINUTE, 15.5)) .setDescriptiveStatistic(MAXIMUM)
.setEffectiveTimeFrame(FIXED_POINT_IN_TIME)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/RespiratoryRateUnitTests.java
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/RespiratoryRate.java // public enum RespirationUnit implements Unit { // // BREATHS_PER_MINUTE("breaths/min"); // // private final String schemaValue; // private static final Map<String, RespirationUnit> constantsBySchemaValue = Maps.newHashMap(); // // static { // for (RespirationUnit unit : values()) { // constantsBySchemaValue.put(unit.getSchemaValue(), unit); // } // } // // RespirationUnit(String schemaValue) { // this.schemaValue = schemaValue; // } // // @Override // @JsonValue // public String getSchemaValue() { // return schemaValue; // } // // @JsonCreator // @Nullable // public RespirationUnit findBySchemaValue(String schemaValue) { // return constantsBySchemaValue.get(schemaValue); // } // } // // Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TemporalRelationshipToPhysicalActivity.java // public enum TemporalRelationshipToPhysicalActivity implements SchemaEnumValue, SchemaSupport { // // AT_REST, // ACTIVE, // BEFORE_EXERCISE, // AFTER_EXERCISE, // DURING_EXERCISE; // // public static final SchemaId SCHEMA_ID = // new SchemaId(OMH_NAMESPACE, "temporal-relationship-to-physical-activity", "1.0"); // // private String schemaValue; // private static final Map<String, TemporalRelationshipToPhysicalActivity> constantsBySchemaValue = new HashMap<>(); // // static { // for (TemporalRelationshipToPhysicalActivity constant : values()) { // constantsBySchemaValue.put(constant.getSchemaValue(), constant); // } // } // // TemporalRelationshipToPhysicalActivity() { // this.schemaValue = name().toLowerCase().replace('_', ' '); // } // // @Override // public SchemaId getSchemaId() { // return SCHEMA_ID; // } // // @Override // @JsonValue // public String getSchemaValue() { // return this.schemaValue; // } // // @Nullable // @JsonCreator // public static TemporalRelationshipToPhysicalActivity findBySchemaValue(String schemaValue) { // return constantsBySchemaValue.get(schemaValue); // } // } // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime());
import org.openmhealth.schema.domain.omh.RespiratoryRate.RespirationUnit; import org.testng.annotations.Test; import java.math.BigDecimal; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.RespiratoryRate.RespirationUnit.BREATHS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.*; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME;
RespiratoryRate sameRespiratoryRate = new RespiratoryRate.Builder(new TypedUnitValue<>(BREATHS_PER_MINUTE, 12)) .setEffectiveTimeFrame(OffsetDateTime.parse("2013-02-05T07:25:00Z")) .setTemporalRelationshipToPhysicalActivity(AT_REST) .build(); assertThat(respiratoryRate.equals(sameRespiratoryRate), is(true)); } @Test public void equalsShouldReturnFalseWhenDifferentRequiredValues() { OffsetDateTime offsetDateTime = OffsetDateTime.parse("2013-02-05T07:25:00Z"); RespiratoryRate respiratoryRate = new RespiratoryRate.Builder(new TypedUnitValue<>(BREATHS_PER_MINUTE, 12)) .setEffectiveTimeFrame(offsetDateTime) .setTemporalRelationshipToPhysicalActivity(AT_REST) .build(); RespiratoryRate withDifferentRequiredValues = new RespiratoryRate.Builder(new TypedUnitValue<>(BREATHS_PER_MINUTE, 12.5)) .setEffectiveTimeFrame(offsetDateTime) .setTemporalRelationshipToPhysicalActivity(AT_REST) .build(); assertThat(respiratoryRate.equals(withDifferentRequiredValues), is(false)); } @Test public void equalsShouldReturnFalseWhenDifferentTemporalRelationshipToActivity() {
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/RespiratoryRate.java // public enum RespirationUnit implements Unit { // // BREATHS_PER_MINUTE("breaths/min"); // // private final String schemaValue; // private static final Map<String, RespirationUnit> constantsBySchemaValue = Maps.newHashMap(); // // static { // for (RespirationUnit unit : values()) { // constantsBySchemaValue.put(unit.getSchemaValue(), unit); // } // } // // RespirationUnit(String schemaValue) { // this.schemaValue = schemaValue; // } // // @Override // @JsonValue // public String getSchemaValue() { // return schemaValue; // } // // @JsonCreator // @Nullable // public RespirationUnit findBySchemaValue(String schemaValue) { // return constantsBySchemaValue.get(schemaValue); // } // } // // Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TemporalRelationshipToPhysicalActivity.java // public enum TemporalRelationshipToPhysicalActivity implements SchemaEnumValue, SchemaSupport { // // AT_REST, // ACTIVE, // BEFORE_EXERCISE, // AFTER_EXERCISE, // DURING_EXERCISE; // // public static final SchemaId SCHEMA_ID = // new SchemaId(OMH_NAMESPACE, "temporal-relationship-to-physical-activity", "1.0"); // // private String schemaValue; // private static final Map<String, TemporalRelationshipToPhysicalActivity> constantsBySchemaValue = new HashMap<>(); // // static { // for (TemporalRelationshipToPhysicalActivity constant : values()) { // constantsBySchemaValue.put(constant.getSchemaValue(), constant); // } // } // // TemporalRelationshipToPhysicalActivity() { // this.schemaValue = name().toLowerCase().replace('_', ' '); // } // // @Override // public SchemaId getSchemaId() { // return SCHEMA_ID; // } // // @Override // @JsonValue // public String getSchemaValue() { // return this.schemaValue; // } // // @Nullable // @JsonCreator // public static TemporalRelationshipToPhysicalActivity findBySchemaValue(String schemaValue) { // return constantsBySchemaValue.get(schemaValue); // } // } // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_POINT_IN_TIME = // new TimeFrame(ZonedDateTime.of(2015, OCTOBER.getValue(), 21, 16, 29, 0, 0, PT).toOffsetDateTime()); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/RespiratoryRateUnitTests.java import org.openmhealth.schema.domain.omh.RespiratoryRate.RespirationUnit; import org.testng.annotations.Test; import java.math.BigDecimal; import java.time.OffsetDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.RespiratoryRate.RespirationUnit.BREATHS_PER_MINUTE; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToPhysicalActivity.*; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_POINT_IN_TIME; RespiratoryRate sameRespiratoryRate = new RespiratoryRate.Builder(new TypedUnitValue<>(BREATHS_PER_MINUTE, 12)) .setEffectiveTimeFrame(OffsetDateTime.parse("2013-02-05T07:25:00Z")) .setTemporalRelationshipToPhysicalActivity(AT_REST) .build(); assertThat(respiratoryRate.equals(sameRespiratoryRate), is(true)); } @Test public void equalsShouldReturnFalseWhenDifferentRequiredValues() { OffsetDateTime offsetDateTime = OffsetDateTime.parse("2013-02-05T07:25:00Z"); RespiratoryRate respiratoryRate = new RespiratoryRate.Builder(new TypedUnitValue<>(BREATHS_PER_MINUTE, 12)) .setEffectiveTimeFrame(offsetDateTime) .setTemporalRelationshipToPhysicalActivity(AT_REST) .build(); RespiratoryRate withDifferentRequiredValues = new RespiratoryRate.Builder(new TypedUnitValue<>(BREATHS_PER_MINUTE, 12.5)) .setEffectiveTimeFrame(offsetDateTime) .setTemporalRelationshipToPhysicalActivity(AT_REST) .build(); assertThat(respiratoryRate.equals(withDifferentRequiredValues), is(false)); } @Test public void equalsShouldReturnFalseWhenDifferentTemporalRelationshipToActivity() {
TypedUnitValue<RespirationUnit> respirationUnitValue = new TypedUnitValue<>(BREATHS_PER_MINUTE, 12);
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TimeInterval.java // public static TimeInterval ofStartDateTimeAndEndDateTime(OffsetDateTime startDateTime, OffsetDateTime endDateTime) { // // checkNotNull(startDateTime, "A start date time hasn't been specified."); // checkNotNull(endDateTime, "An end date time hasn't been specified."); // checkArgument(!endDateTime.isBefore(startDateTime), "The specified start and end date times are reversed."); // // TimeInterval timeInterval = new TimeInterval(); // // timeInterval.startDateTime = startDateTime; // timeInterval.endDateTime = endDateTime; // // return timeInterval; // }
import java.time.LocalDate; import java.time.ZoneId; import java.time.ZonedDateTime; import static java.time.Month.NOVEMBER; import static java.time.Month.OCTOBER; import static org.openmhealth.schema.domain.omh.TimeInterval.ofStartDateTimeAndEndDateTime;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * A factory of time frames used to simplify tests and avoid repetition. * * @author Emerson Farrugia */ public class TimeFrameFactory { public static final ZoneId PT = ZoneId.of("America/Los_Angeles"); public static final TimeFrame FIXED_MONTH =
// Path: java-schema-sdk/src/main/java/org/openmhealth/schema/domain/omh/TimeInterval.java // public static TimeInterval ofStartDateTimeAndEndDateTime(OffsetDateTime startDateTime, OffsetDateTime endDateTime) { // // checkNotNull(startDateTime, "A start date time hasn't been specified."); // checkNotNull(endDateTime, "An end date time hasn't been specified."); // checkArgument(!endDateTime.isBefore(startDateTime), "The specified start and end date times are reversed."); // // TimeInterval timeInterval = new TimeInterval(); // // timeInterval.startDateTime = startDateTime; // timeInterval.endDateTime = endDateTime; // // return timeInterval; // } // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java import java.time.LocalDate; import java.time.ZoneId; import java.time.ZonedDateTime; import static java.time.Month.NOVEMBER; import static java.time.Month.OCTOBER; import static org.openmhealth.schema.domain.omh.TimeInterval.ofStartDateTimeAndEndDateTime; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * A factory of time frames used to simplify tests and avoid repetition. * * @author Emerson Farrugia */ public class TimeFrameFactory { public static final ZoneId PT = ZoneId.of("America/Los_Angeles"); public static final TimeFrame FIXED_MONTH =
new TimeFrame(ofStartDateTimeAndEndDateTime(
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BloodGlucoseUnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.BloodGlucoseUnit.MILLIGRAMS_PER_DECILITER; import static org.openmhealth.schema.domain.omh.BloodSpecimenType.PLASMA; import static org.openmhealth.schema.domain.omh.BloodSpecimenType.WHOLE_BLOOD; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToMeal.FASTING; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToSleep.BEFORE_SLEEPING; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToSleep.ON_WAKING; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class BloodGlucoseUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/blood-glucose-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedBloodGlucose() { new BloodGlucose.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { TypedUnitValue<BloodGlucoseUnit> bloodGlucoseLevel = new TypedUnitValue<>(MILLIGRAMS_PER_DECILITER, 110); BloodGlucose bloodGlucose = new BloodGlucose.Builder(bloodGlucoseLevel).build(); assertThat(bloodGlucose, notNullValue()); assertThat(bloodGlucose.getBloodGlucose(), equalTo(bloodGlucoseLevel)); assertThat(bloodGlucose.getBloodSpecimenType(), nullValue()); assertThat(bloodGlucose.getTemporalRelationshipToMeal(), nullValue()); assertThat(bloodGlucose.getTemporalRelationshipToSleep(), nullValue()); assertThat(bloodGlucose.getEffectiveTimeFrame(), nullValue()); assertThat(bloodGlucose.getDescriptiveStatistic(), nullValue()); assertThat(bloodGlucose.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { TypedUnitValue<BloodGlucoseUnit> bloodGlucoseLevel = new TypedUnitValue<>(MILLIGRAMS_PER_DECILITER, 110); BloodGlucose bloodGlucose = new BloodGlucose.Builder(bloodGlucoseLevel) .setBloodSpecimenType(WHOLE_BLOOD) .setTemporalRelationshipToMeal(FASTING) .setTemporalRelationshipToSleep(BEFORE_SLEEPING)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/BloodGlucoseUnitTests.java import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.BloodGlucoseUnit.MILLIGRAMS_PER_DECILITER; import static org.openmhealth.schema.domain.omh.BloodSpecimenType.PLASMA; import static org.openmhealth.schema.domain.omh.BloodSpecimenType.WHOLE_BLOOD; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MINIMUM; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToMeal.FASTING; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToSleep.BEFORE_SLEEPING; import static org.openmhealth.schema.domain.omh.TemporalRelationshipToSleep.ON_WAKING; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class BloodGlucoseUnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/blood-glucose-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedBloodGlucose() { new BloodGlucose.Builder(null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { TypedUnitValue<BloodGlucoseUnit> bloodGlucoseLevel = new TypedUnitValue<>(MILLIGRAMS_PER_DECILITER, 110); BloodGlucose bloodGlucose = new BloodGlucose.Builder(bloodGlucoseLevel).build(); assertThat(bloodGlucose, notNullValue()); assertThat(bloodGlucose.getBloodGlucose(), equalTo(bloodGlucoseLevel)); assertThat(bloodGlucose.getBloodSpecimenType(), nullValue()); assertThat(bloodGlucose.getTemporalRelationshipToMeal(), nullValue()); assertThat(bloodGlucose.getTemporalRelationshipToSleep(), nullValue()); assertThat(bloodGlucose.getEffectiveTimeFrame(), nullValue()); assertThat(bloodGlucose.getDescriptiveStatistic(), nullValue()); assertThat(bloodGlucose.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { TypedUnitValue<BloodGlucoseUnit> bloodGlucoseLevel = new TypedUnitValue<>(MILLIGRAMS_PER_DECILITER, 110); BloodGlucose bloodGlucose = new BloodGlucose.Builder(bloodGlucoseLevel) .setBloodSpecimenType(WHOLE_BLOOD) .setTemporalRelationshipToMeal(FASTING) .setTemporalRelationshipToSleep(BEFORE_SLEEPING)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/CaloriesBurned2UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.KcalUnit.KILOCALORIE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class CaloriesBurned2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/calories-burned-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedCaloriesBurned() {
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/CaloriesBurned2UnitTests.java import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.KcalUnit.KILOCALORIE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class CaloriesBurned2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/calories-burned-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedCaloriesBurned() {
new CaloriesBurned2.Builder(null, FIXED_MONTH);
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/CaloriesBurned2UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.KcalUnit.KILOCALORIE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class CaloriesBurned2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/calories-burned-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedCaloriesBurned() { new CaloriesBurned2.Builder(null, FIXED_MONTH); } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedEffectiveTimeFrame() { new CaloriesBurned2.Builder(KILOCALORIE.newUnitValue(100), (TimeFrame) null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { KcalUnitValue kcalBurned = KILOCALORIE.newUnitValue(200);
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/CaloriesBurned2UnitTests.java import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.AVERAGE; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MEDIAN; import static org.openmhealth.schema.domain.omh.DescriptiveStatisticDenominator.DAY; import static org.openmhealth.schema.domain.omh.KcalUnit.KILOCALORIE; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class CaloriesBurned2UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/calories-burned-2.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedCaloriesBurned() { new CaloriesBurned2.Builder(null, FIXED_MONTH); } @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedEffectiveTimeFrame() { new CaloriesBurned2.Builder(KILOCALORIE.newUnitValue(100), (TimeFrame) null); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { KcalUnitValue kcalBurned = KILOCALORIE.newUnitValue(200);
CaloriesBurned2 caloriesBurned = new CaloriesBurned2.Builder(kcalBurned, FIXED_DAY).build();
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SleepDuration1UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.WEEK; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
/* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SleepDuration1UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/sleep-duration-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedSleepDuration() { new SleepDuration1.Builder(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void constructorShouldThrowExceptionOnInvalidDurationUnit() { new SleepDuration1.Builder(new DurationUnitValue(WEEK, ONE)); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { DurationUnitValue durationUnitValue = new DurationUnitValue(HOUR, TEN); SleepDuration1 sleepDuration = new SleepDuration1.Builder(durationUnitValue).build(); assertThat(sleepDuration, notNullValue()); assertThat(sleepDuration.getSleepDuration(), equalTo(durationUnitValue)); assertThat(sleepDuration.getEffectiveTimeFrame(), nullValue()); assertThat(sleepDuration.getDescriptiveStatistic(), nullValue()); assertThat(sleepDuration.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { DurationUnitValue durationUnitValue = new DurationUnitValue(HOUR, TEN); SleepDuration1 sleepDuration = new SleepDuration1.Builder(durationUnitValue)
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SleepDuration1UnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.WEEK; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; /* * Copyright 2015 Open mHealth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openmhealth.schema.domain.omh; /** * @author Emerson Farrugia */ public class SleepDuration1UnitTests extends SerializationUnitTests { public static final String SCHEMA_FILENAME = "schema/omh/sleep-duration-1.0.json"; @Test(expectedExceptions = NullPointerException.class) public void constructorShouldThrowExceptionOnUndefinedSleepDuration() { new SleepDuration1.Builder(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void constructorShouldThrowExceptionOnInvalidDurationUnit() { new SleepDuration1.Builder(new DurationUnitValue(WEEK, ONE)); } @Test public void buildShouldConstructMeasureUsingOnlyRequiredProperties() { DurationUnitValue durationUnitValue = new DurationUnitValue(HOUR, TEN); SleepDuration1 sleepDuration = new SleepDuration1.Builder(durationUnitValue).build(); assertThat(sleepDuration, notNullValue()); assertThat(sleepDuration.getSleepDuration(), equalTo(durationUnitValue)); assertThat(sleepDuration.getEffectiveTimeFrame(), nullValue()); assertThat(sleepDuration.getDescriptiveStatistic(), nullValue()); assertThat(sleepDuration.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { DurationUnitValue durationUnitValue = new DurationUnitValue(HOUR, TEN); SleepDuration1 sleepDuration = new SleepDuration1.Builder(durationUnitValue)
.setEffectiveTimeFrame(FIXED_MONTH)
openmhealth/schemas
java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SleepDuration1UnitTests.java
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // ));
import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.WEEK; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH;
assertThat(sleepDuration.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { DurationUnitValue durationUnitValue = new DurationUnitValue(HOUR, TEN); SleepDuration1 sleepDuration = new SleepDuration1.Builder(durationUnitValue) .setEffectiveTimeFrame(FIXED_MONTH) .setDescriptiveStatistic(MAXIMUM) .setUserNotes("feeling fine") .build(); assertThat(sleepDuration, notNullValue()); assertThat(sleepDuration.getSleepDuration(), equalTo(durationUnitValue)); assertThat(sleepDuration.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(sleepDuration.getDescriptiveStatistic(), equalTo(MAXIMUM)); assertThat(sleepDuration.getUserNotes(), equalTo("feeling fine")); } @Override protected String getSchemaFilename() { return SCHEMA_FILENAME; } @Test public void measureShouldSerializeCorrectly() throws Exception { SleepDuration1 sleepDuration = new SleepDuration1.Builder(new DurationUnitValue(HOUR, BigDecimal.valueOf(6)))
// Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_DAY = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 21).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, OCTOBER, 22).atStartOfDay(PT).toOffsetDateTime() // )); // // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/TimeFrameFactory.java // public static final TimeFrame FIXED_MONTH = // new TimeFrame(ofStartDateTimeAndEndDateTime( // LocalDate.of(2015, OCTOBER, 1).atStartOfDay(PT).toOffsetDateTime(), // LocalDate.of(2015, NOVEMBER, 1).atStartOfDay(PT).toOffsetDateTime() // )); // Path: java-schema-sdk/src/test/java/org/openmhealth/schema/domain/omh/SleepDuration1UnitTests.java import org.testng.annotations.Test; import java.math.BigDecimal; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.openmhealth.schema.domain.omh.DescriptiveStatistic.MAXIMUM; import static org.openmhealth.schema.domain.omh.DurationUnit.HOUR; import static org.openmhealth.schema.domain.omh.DurationUnit.WEEK; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_DAY; import static org.openmhealth.schema.domain.omh.TimeFrameFactory.FIXED_MONTH; assertThat(sleepDuration.getUserNotes(), nullValue()); } @Test public void buildShouldConstructMeasureUsingOptionalProperties() { DurationUnitValue durationUnitValue = new DurationUnitValue(HOUR, TEN); SleepDuration1 sleepDuration = new SleepDuration1.Builder(durationUnitValue) .setEffectiveTimeFrame(FIXED_MONTH) .setDescriptiveStatistic(MAXIMUM) .setUserNotes("feeling fine") .build(); assertThat(sleepDuration, notNullValue()); assertThat(sleepDuration.getSleepDuration(), equalTo(durationUnitValue)); assertThat(sleepDuration.getEffectiveTimeFrame(), equalTo(FIXED_MONTH)); assertThat(sleepDuration.getDescriptiveStatistic(), equalTo(MAXIMUM)); assertThat(sleepDuration.getUserNotes(), equalTo("feeling fine")); } @Override protected String getSchemaFilename() { return SCHEMA_FILENAME; } @Test public void measureShouldSerializeCorrectly() throws Exception { SleepDuration1 sleepDuration = new SleepDuration1.Builder(new DurationUnitValue(HOUR, BigDecimal.valueOf(6)))
.setEffectiveTimeFrame(FIXED_DAY)
dazraf/vertx-futures
src/main/java/io/dazraf/vertx/tuple/Tuple3.java
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer3.java // @FunctionalInterface // public interface Consumer3<T1, T2, T3> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3); // } // // Path: src/main/java/io/dazraf/vertx/function/Function3.java // @FunctionalInterface // public interface Function3<T1, T2, T3, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3); // }
import io.dazraf.vertx.consumer.Consumer3; import io.dazraf.vertx.function.Function3; import io.vertx.core.CompositeFuture;
package io.dazraf.vertx.tuple; /** * A tuple of three values of type {@link T1}, {@link T2} and {@link T3} * @param <T1> The type of the first value in the tuple * @param <T2> The type of the second value in the tuple * @param <T3> The type of the third value in the tuple */ public class Tuple3<T1, T2, T3> extends Tuple<Tuple3<T1, T2, T3>> { private final T1 t1; private final T2 t2; private final T3 t3; /** * Construct using values for the three types * @param t1 the value of the first type * @param t2 the value of the second type * @param t3 the value of the third type */ public Tuple3(T1 t1, T2 t2, T3 t3) { this.t1 = t1; this.t2 = t2; this.t3 = t3; } /** * Construct from a <i>completed</i> future * @param compositeFuture a composite future that should contain three values of types that are assignable to this types generic parameters */ public Tuple3(CompositeFuture compositeFuture) { assert(compositeFuture.succeeded()); this.t1 = compositeFuture.result(0); this.t2 = compositeFuture.result(1); this.t3 = compositeFuture.result(2); } /** * Retrieve the first value * @return the value of the first type */ public T1 getT1() { return t1; } /** * Retrieve the second value * @return the value of the second type */ public T2 getT2() { return t2; } /** * Retrieve the third value * @return the value of the third type */ public T3 getT3() { return t3; } /** * Calls a {@link Consumer3} function with three values of this tuple. Any exceptions are propagated up the stack. * @param consumer The consumer function, that will be called with three values from this tuple. */
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer3.java // @FunctionalInterface // public interface Consumer3<T1, T2, T3> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3); // } // // Path: src/main/java/io/dazraf/vertx/function/Function3.java // @FunctionalInterface // public interface Function3<T1, T2, T3, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3); // } // Path: src/main/java/io/dazraf/vertx/tuple/Tuple3.java import io.dazraf.vertx.consumer.Consumer3; import io.dazraf.vertx.function.Function3; import io.vertx.core.CompositeFuture; package io.dazraf.vertx.tuple; /** * A tuple of three values of type {@link T1}, {@link T2} and {@link T3} * @param <T1> The type of the first value in the tuple * @param <T2> The type of the second value in the tuple * @param <T3> The type of the third value in the tuple */ public class Tuple3<T1, T2, T3> extends Tuple<Tuple3<T1, T2, T3>> { private final T1 t1; private final T2 t2; private final T3 t3; /** * Construct using values for the three types * @param t1 the value of the first type * @param t2 the value of the second type * @param t3 the value of the third type */ public Tuple3(T1 t1, T2 t2, T3 t3) { this.t1 = t1; this.t2 = t2; this.t3 = t3; } /** * Construct from a <i>completed</i> future * @param compositeFuture a composite future that should contain three values of types that are assignable to this types generic parameters */ public Tuple3(CompositeFuture compositeFuture) { assert(compositeFuture.succeeded()); this.t1 = compositeFuture.result(0); this.t2 = compositeFuture.result(1); this.t3 = compositeFuture.result(2); } /** * Retrieve the first value * @return the value of the first type */ public T1 getT1() { return t1; } /** * Retrieve the second value * @return the value of the second type */ public T2 getT2() { return t2; } /** * Retrieve the third value * @return the value of the third type */ public T3 getT3() { return t3; } /** * Calls a {@link Consumer3} function with three values of this tuple. Any exceptions are propagated up the stack. * @param consumer The consumer function, that will be called with three values from this tuple. */
public void accept(Consumer3<T1, T2, T3> consumer) {
dazraf/vertx-futures
src/main/java/io/dazraf/vertx/tuple/Tuple3.java
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer3.java // @FunctionalInterface // public interface Consumer3<T1, T2, T3> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3); // } // // Path: src/main/java/io/dazraf/vertx/function/Function3.java // @FunctionalInterface // public interface Function3<T1, T2, T3, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3); // }
import io.dazraf.vertx.consumer.Consumer3; import io.dazraf.vertx.function.Function3; import io.vertx.core.CompositeFuture;
package io.dazraf.vertx.tuple; /** * A tuple of three values of type {@link T1}, {@link T2} and {@link T3} * @param <T1> The type of the first value in the tuple * @param <T2> The type of the second value in the tuple * @param <T3> The type of the third value in the tuple */ public class Tuple3<T1, T2, T3> extends Tuple<Tuple3<T1, T2, T3>> { private final T1 t1; private final T2 t2; private final T3 t3; /** * Construct using values for the three types * @param t1 the value of the first type * @param t2 the value of the second type * @param t3 the value of the third type */ public Tuple3(T1 t1, T2 t2, T3 t3) { this.t1 = t1; this.t2 = t2; this.t3 = t3; } /** * Construct from a <i>completed</i> future * @param compositeFuture a composite future that should contain three values of types that are assignable to this types generic parameters */ public Tuple3(CompositeFuture compositeFuture) { assert(compositeFuture.succeeded()); this.t1 = compositeFuture.result(0); this.t2 = compositeFuture.result(1); this.t3 = compositeFuture.result(2); } /** * Retrieve the first value * @return the value of the first type */ public T1 getT1() { return t1; } /** * Retrieve the second value * @return the value of the second type */ public T2 getT2() { return t2; } /** * Retrieve the third value * @return the value of the third type */ public T3 getT3() { return t3; } /** * Calls a {@link Consumer3} function with three values of this tuple. Any exceptions are propagated up the stack. * @param consumer The consumer function, that will be called with three values from this tuple. */ public void accept(Consumer3<T1, T2, T3> consumer) { consumer.accept(t1, t2, t3); } /** * Calls a {@link Function3} function with the three values of the tuple and returns the result of that function. * Any exceptions are propagated up the stack. * @param function the function, that will be called with three values from this tuple and returns a result of type {@link R} * @param <R> The type of the result returned from <code>#function</code> * @return The result from calling the function */
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer3.java // @FunctionalInterface // public interface Consumer3<T1, T2, T3> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3); // } // // Path: src/main/java/io/dazraf/vertx/function/Function3.java // @FunctionalInterface // public interface Function3<T1, T2, T3, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3); // } // Path: src/main/java/io/dazraf/vertx/tuple/Tuple3.java import io.dazraf.vertx.consumer.Consumer3; import io.dazraf.vertx.function.Function3; import io.vertx.core.CompositeFuture; package io.dazraf.vertx.tuple; /** * A tuple of three values of type {@link T1}, {@link T2} and {@link T3} * @param <T1> The type of the first value in the tuple * @param <T2> The type of the second value in the tuple * @param <T3> The type of the third value in the tuple */ public class Tuple3<T1, T2, T3> extends Tuple<Tuple3<T1, T2, T3>> { private final T1 t1; private final T2 t2; private final T3 t3; /** * Construct using values for the three types * @param t1 the value of the first type * @param t2 the value of the second type * @param t3 the value of the third type */ public Tuple3(T1 t1, T2 t2, T3 t3) { this.t1 = t1; this.t2 = t2; this.t3 = t3; } /** * Construct from a <i>completed</i> future * @param compositeFuture a composite future that should contain three values of types that are assignable to this types generic parameters */ public Tuple3(CompositeFuture compositeFuture) { assert(compositeFuture.succeeded()); this.t1 = compositeFuture.result(0); this.t2 = compositeFuture.result(1); this.t3 = compositeFuture.result(2); } /** * Retrieve the first value * @return the value of the first type */ public T1 getT1() { return t1; } /** * Retrieve the second value * @return the value of the second type */ public T2 getT2() { return t2; } /** * Retrieve the third value * @return the value of the third type */ public T3 getT3() { return t3; } /** * Calls a {@link Consumer3} function with three values of this tuple. Any exceptions are propagated up the stack. * @param consumer The consumer function, that will be called with three values from this tuple. */ public void accept(Consumer3<T1, T2, T3> consumer) { consumer.accept(t1, t2, t3); } /** * Calls a {@link Function3} function with the three values of the tuple and returns the result of that function. * Any exceptions are propagated up the stack. * @param function the function, that will be called with three values from this tuple and returns a result of type {@link R} * @param <R> The type of the result returned from <code>#function</code> * @return The result from calling the function */
public <R> R apply(Function3<T1, T2, T3, R> function) {
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/processors/RunProcessorTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.failedFuture; import static io.vertx.core.Future.future; import static io.vertx.core.Future.succeededFuture;
package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class RunProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); private static final int NUMBER = 1; private static final String MSG = "one"; @Test public void testSimpleSuccess(TestContext context) { Async async = context.async();
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // Path: src/test/java/io/dazraf/vertx/futures/processors/RunProcessorTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.failedFuture; import static io.vertx.core.Future.future; import static io.vertx.core.Future.succeededFuture; package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class RunProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); private static final int NUMBER = 1; private static final String MSG = "one"; @Test public void testSimpleSuccess(TestContext context) { Async async = context.async();
when(futureMessage())
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/processors/RunProcessorTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.failedFuture; import static io.vertx.core.Future.future; import static io.vertx.core.Future.succeededFuture;
package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class RunProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); private static final int NUMBER = 1; private static final String MSG = "one"; @Test public void testSimpleSuccess(TestContext context) { Async async = context.async(); when(futureMessage())
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // Path: src/test/java/io/dazraf/vertx/futures/processors/RunProcessorTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.failedFuture; import static io.vertx.core.Future.future; import static io.vertx.core.Future.succeededFuture; package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class RunProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); private static final int NUMBER = 1; private static final String MSG = "one"; @Test public void testSimpleSuccess(TestContext context) { Async async = context.async(); when(futureMessage())
.then(run(result -> {
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/processors/RunProcessorTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.failedFuture; import static io.vertx.core.Future.future; import static io.vertx.core.Future.succeededFuture;
package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class RunProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); private static final int NUMBER = 1; private static final String MSG = "one"; @Test public void testSimpleSuccess(TestContext context) { Async async = context.async(); when(futureMessage()) .then(run(result -> { context.assertEquals(MSG, result); async.complete(); }))
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // Path: src/test/java/io/dazraf/vertx/futures/processors/RunProcessorTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.failedFuture; import static io.vertx.core.Future.future; import static io.vertx.core.Future.succeededFuture; package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class RunProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); private static final int NUMBER = 1; private static final String MSG = "one"; @Test public void testSimpleSuccess(TestContext context) { Async async = context.async(); when(futureMessage()) .then(run(result -> { context.assertEquals(MSG, result); async.complete(); }))
.then(runOnFail(context::fail));
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/processors/RunProcessorTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.failedFuture; import static io.vertx.core.Future.future; import static io.vertx.core.Future.succeededFuture;
.then(run(async::complete)) .then(runOnFail(context::fail)); vertxContext.vertx().setTimer(10, id -> future.complete(MSG)); } @Test public void testSimpleFailure(TestContext context) { Async async = context.async(); when(failedFuture(MSG)) .then(run(() -> context.fail("should have failed"))) .then(runOnFail(err -> context.assertEquals(MSG, err.getMessage()))) .then(runOnFail(err -> async.complete())); } @Test public void testSimpleAsyncFailure(TestContext context) { Async async = context.async(); String MSG = "error"; Future<String> future = future(); when(future) .then(run(() -> context.fail("should have failed"))) .then(runOnFail((err -> context.assertEquals(MSG, err.getMessage())))) .then(runOnFail(err -> async.complete())); vertxContext.vertx().setTimer(10, id -> future.fail(MSG)); } @Test public void test2SuccessfulFlow(TestContext context) { Async async = context.async(); when(futureMessage(), futureNumber())
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // Path: src/test/java/io/dazraf/vertx/futures/processors/RunProcessorTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.failedFuture; import static io.vertx.core.Future.future; import static io.vertx.core.Future.succeededFuture; .then(run(async::complete)) .then(runOnFail(context::fail)); vertxContext.vertx().setTimer(10, id -> future.complete(MSG)); } @Test public void testSimpleFailure(TestContext context) { Async async = context.async(); when(failedFuture(MSG)) .then(run(() -> context.fail("should have failed"))) .then(runOnFail(err -> context.assertEquals(MSG, err.getMessage()))) .then(runOnFail(err -> async.complete())); } @Test public void testSimpleAsyncFailure(TestContext context) { Async async = context.async(); String MSG = "error"; Future<String> future = future(); when(future) .then(run(() -> context.fail("should have failed"))) .then(runOnFail((err -> context.assertEquals(MSG, err.getMessage())))) .then(runOnFail(err -> async.complete())); vertxContext.vertx().setTimer(10, id -> future.fail(MSG)); } @Test public void test2SuccessfulFlow(TestContext context) { Async async = context.async(); when(futureMessage(), futureNumber())
.then(map((msg, number) -> msg + number))
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/processors/RunProcessorTest.java
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // }
import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.failedFuture; import static io.vertx.core.Future.future; import static io.vertx.core.Future.succeededFuture;
.then(runOnFail(err -> context.assertEquals(MSG, err.getMessage()))) .then(runOnFail(err -> async.complete())); } @Test public void testSimpleAsyncFailure(TestContext context) { Async async = context.async(); String MSG = "error"; Future<String> future = future(); when(future) .then(run(() -> context.fail("should have failed"))) .then(runOnFail((err -> context.assertEquals(MSG, err.getMessage())))) .then(runOnFail(err -> async.complete())); vertxContext.vertx().setTimer(10, id -> future.fail(MSG)); } @Test public void test2SuccessfulFlow(TestContext context) { Async async = context.async(); when(futureMessage(), futureNumber()) .then(map((msg, number) -> msg + number)) .then(run(val -> context.assertEquals(MSG + NUMBER, val))) .then(run(async::complete)) .then(runOnFail(context::fail)); } @Test public void test2Then1SuccessfulFlow(TestContext context) { Async async = context.async(); when(futureMessage(), futureNumber())
// Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/CallProcessor.java // static <T, R> CallProcessor<T, R> call(Supplier<Future<R>> supplier) { // return call(result -> supplier.get()); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/MapProcessor.java // static <T, R> MapProcessor<T, R> map(Function<T, R> function) { // return mapOnResponse(future -> { // if (future.succeeded()) { // return function.apply(future.result()); // } else { // throw new WrappedException(future.cause()); // } // }); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // Path: src/test/java/io/dazraf/vertx/futures/processors/RunProcessorTest.java import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import io.vertx.core.Future; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.processors.CallProcessor.call; import static io.dazraf.vertx.futures.processors.MapProcessor.map; import static io.dazraf.vertx.futures.processors.RunProcessor.runOnFail; import static io.dazraf.vertx.futures.processors.RunProcessor.run; import static io.vertx.core.Future.failedFuture; import static io.vertx.core.Future.future; import static io.vertx.core.Future.succeededFuture; .then(runOnFail(err -> context.assertEquals(MSG, err.getMessage()))) .then(runOnFail(err -> async.complete())); } @Test public void testSimpleAsyncFailure(TestContext context) { Async async = context.async(); String MSG = "error"; Future<String> future = future(); when(future) .then(run(() -> context.fail("should have failed"))) .then(runOnFail((err -> context.assertEquals(MSG, err.getMessage())))) .then(runOnFail(err -> async.complete())); vertxContext.vertx().setTimer(10, id -> future.fail(MSG)); } @Test public void test2SuccessfulFlow(TestContext context) { Async async = context.async(); when(futureMessage(), futureNumber()) .then(map((msg, number) -> msg + number)) .then(run(val -> context.assertEquals(MSG + NUMBER, val))) .then(run(async::complete)) .then(runOnFail(context::fail)); } @Test public void test2Then1SuccessfulFlow(TestContext context) { Async async = context.async(); when(futureMessage(), futureNumber())
.then(call((msg, number) -> succeededFuture(msg + number)))
dazraf/vertx-futures
src/main/java/io/dazraf/vertx/futures/FuturesImpl.java
// Path: src/main/java/io/dazraf/vertx/futures/processors/FutureProcessor.java // @FunctionalInterface // public interface FutureProcessor<T1, T2> extends Function<Future<T1>, Future<T2>> { // }
import java.util.LinkedList; import java.util.List; import java.util.function.Consumer; import io.dazraf.vertx.futures.processors.FutureProcessor; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.impl.NoStackTraceThrowable;
return new FuturesImpl<>(future, future); } } public FuturesImpl(Future parent) { this.parent = parent; } public FuturesImpl(Future<T> future, Future parent) { this(parent); initialise(future); } private FuturesImpl<T> initialise(Future<T> future) { future.setHandler(asyncResult -> { if (asyncResult.failed()) { fail(asyncResult.cause()); } else if (asyncResult.succeeded()) { complete(asyncResult.result()); } notifyAllDependents(this); }); return this; } private void notifyAllDependents(Future<T> future) { dependents.forEach(dependent -> dependent.accept(future)); } @Override
// Path: src/main/java/io/dazraf/vertx/futures/processors/FutureProcessor.java // @FunctionalInterface // public interface FutureProcessor<T1, T2> extends Function<Future<T1>, Future<T2>> { // } // Path: src/main/java/io/dazraf/vertx/futures/FuturesImpl.java import java.util.LinkedList; import java.util.List; import java.util.function.Consumer; import io.dazraf.vertx.futures.processors.FutureProcessor; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.impl.NoStackTraceThrowable; return new FuturesImpl<>(future, future); } } public FuturesImpl(Future parent) { this.parent = parent; } public FuturesImpl(Future<T> future, Future parent) { this(parent); initialise(future); } private FuturesImpl<T> initialise(Future<T> future) { future.setHandler(asyncResult -> { if (asyncResult.failed()) { fail(asyncResult.cause()); } else if (asyncResult.succeeded()) { complete(asyncResult.result()); } notifyAllDependents(this); }); return this; } private void notifyAllDependents(Future<T> future) { dependents.forEach(dependent -> dependent.accept(future)); } @Override
public <R> Futures<R> then(FutureProcessor<T, R> processor) {
dazraf/vertx-futures
src/main/java/io/dazraf/vertx/tuple/Tuple5.java
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer5.java // @FunctionalInterface // public interface Consumer5<T1, T2, T3, T4, T5> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); // } // // Path: src/main/java/io/dazraf/vertx/function/Function5.java // @FunctionalInterface // public interface Function5<T1, T2, T3, T4, T5, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); // }
import io.dazraf.vertx.consumer.Consumer5; import io.dazraf.vertx.function.Function5; import io.vertx.core.CompositeFuture;
* * @return the value of the third type */ public T3 getT3() { return t3; } /** * Retrieve the fourth value * * @return the value for the fourth type */ public T4 getT4() { return t4; } /** * Retrieve the fourth value * * @return the value for the fifth type */ public T5 getT5() { return t5; } /** * Calls a {@link Consumer5} function with the five values of this tuple. Any exceptions are propagated up the stack. * * @param consumer The consumer function, that will be called with five values from this tuple. */
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer5.java // @FunctionalInterface // public interface Consumer5<T1, T2, T3, T4, T5> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); // } // // Path: src/main/java/io/dazraf/vertx/function/Function5.java // @FunctionalInterface // public interface Function5<T1, T2, T3, T4, T5, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); // } // Path: src/main/java/io/dazraf/vertx/tuple/Tuple5.java import io.dazraf.vertx.consumer.Consumer5; import io.dazraf.vertx.function.Function5; import io.vertx.core.CompositeFuture; * * @return the value of the third type */ public T3 getT3() { return t3; } /** * Retrieve the fourth value * * @return the value for the fourth type */ public T4 getT4() { return t4; } /** * Retrieve the fourth value * * @return the value for the fifth type */ public T5 getT5() { return t5; } /** * Calls a {@link Consumer5} function with the five values of this tuple. Any exceptions are propagated up the stack. * * @param consumer The consumer function, that will be called with five values from this tuple. */
public void accept(Consumer5<T1, T2, T3, T4, T5> consumer) {
dazraf/vertx-futures
src/main/java/io/dazraf/vertx/tuple/Tuple5.java
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer5.java // @FunctionalInterface // public interface Consumer5<T1, T2, T3, T4, T5> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); // } // // Path: src/main/java/io/dazraf/vertx/function/Function5.java // @FunctionalInterface // public interface Function5<T1, T2, T3, T4, T5, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); // }
import io.dazraf.vertx.consumer.Consumer5; import io.dazraf.vertx.function.Function5; import io.vertx.core.CompositeFuture;
public T4 getT4() { return t4; } /** * Retrieve the fourth value * * @return the value for the fifth type */ public T5 getT5() { return t5; } /** * Calls a {@link Consumer5} function with the five values of this tuple. Any exceptions are propagated up the stack. * * @param consumer The consumer function, that will be called with five values from this tuple. */ public void accept(Consumer5<T1, T2, T3, T4, T5> consumer) { consumer.accept(t1, t2, t3, t4, t5); } /** * Calls a {@link Function5} function with the five values of the tuple and returns the result of that function. * Any exceptions are propagated up the stack. * * @param function the function, that will be called with five values from this tuple and returns a result of type {@link R} * @param <R> The type of the result returned from <code>#function</code> * @return The result from calling the function */
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer5.java // @FunctionalInterface // public interface Consumer5<T1, T2, T3, T4, T5> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); // } // // Path: src/main/java/io/dazraf/vertx/function/Function5.java // @FunctionalInterface // public interface Function5<T1, T2, T3, T4, T5, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); // } // Path: src/main/java/io/dazraf/vertx/tuple/Tuple5.java import io.dazraf.vertx.consumer.Consumer5; import io.dazraf.vertx.function.Function5; import io.vertx.core.CompositeFuture; public T4 getT4() { return t4; } /** * Retrieve the fourth value * * @return the value for the fifth type */ public T5 getT5() { return t5; } /** * Calls a {@link Consumer5} function with the five values of this tuple. Any exceptions are propagated up the stack. * * @param consumer The consumer function, that will be called with five values from this tuple. */ public void accept(Consumer5<T1, T2, T3, T4, T5> consumer) { consumer.accept(t1, t2, t3, t4, t5); } /** * Calls a {@link Function5} function with the five values of the tuple and returns the result of that function. * Any exceptions are propagated up the stack. * * @param function the function, that will be called with five values from this tuple and returns a result of type {@link R} * @param <R> The type of the result returned from <code>#function</code> * @return The result from calling the function */
public <R> R apply(Function5<T1, T2, T3, T4, T5, R> function) {
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/HttpServerWrapper.java
// Path: src/test/java/io/dazraf/vertx/SocketTestUtils.java // public static int getFreePort() { // return getFreePort(1).get(0); // } // // Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // }
import org.slf4j.Logger; import java.util.function.Consumer; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerRequest; import static io.dazraf.vertx.SocketTestUtils.getFreePort; import static io.dazraf.vertx.futures.Futures.when; import static io.vertx.core.Future.future; import static org.slf4j.LoggerFactory.getLogger;
package io.dazraf.vertx; public class HttpServerWrapper { private static final String MESSAGE_OK = "OK"; private static final Logger LOG = getLogger(HttpServerWrapper.class); private final int serverPort; private final HttpServer httpServer; private HttpServerWrapper(int serverPort, HttpServer httpServer) { this.serverPort = serverPort; this.httpServer = httpServer; } public static Future<HttpServerWrapper> createHttpServer(Vertx vertx) { return createHttpServer(vertx, request -> request.bodyHandler(buffer -> { request.response().end(MESSAGE_OK); })); } public static Future<HttpServerWrapper> createHttpServer(Vertx vertx, Consumer<HttpServerRequest> handler) { Future<HttpServerWrapper> httpServer = future();
// Path: src/test/java/io/dazraf/vertx/SocketTestUtils.java // public static int getFreePort() { // return getFreePort(1).get(0); // } // // Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // Path: src/test/java/io/dazraf/vertx/HttpServerWrapper.java import org.slf4j.Logger; import java.util.function.Consumer; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerRequest; import static io.dazraf.vertx.SocketTestUtils.getFreePort; import static io.dazraf.vertx.futures.Futures.when; import static io.vertx.core.Future.future; import static org.slf4j.LoggerFactory.getLogger; package io.dazraf.vertx; public class HttpServerWrapper { private static final String MESSAGE_OK = "OK"; private static final Logger LOG = getLogger(HttpServerWrapper.class); private final int serverPort; private final HttpServer httpServer; private HttpServerWrapper(int serverPort, HttpServer httpServer) { this.serverPort = serverPort; this.httpServer = httpServer; } public static Future<HttpServerWrapper> createHttpServer(Vertx vertx) { return createHttpServer(vertx, request -> request.bodyHandler(buffer -> { request.response().end(MESSAGE_OK); })); } public static Future<HttpServerWrapper> createHttpServer(Vertx vertx, Consumer<HttpServerRequest> handler) { Future<HttpServerWrapper> httpServer = future();
int serverPort = getFreePort();
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/HttpServerWrapper.java
// Path: src/test/java/io/dazraf/vertx/SocketTestUtils.java // public static int getFreePort() { // return getFreePort(1).get(0); // } // // Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // }
import org.slf4j.Logger; import java.util.function.Consumer; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerRequest; import static io.dazraf.vertx.SocketTestUtils.getFreePort; import static io.dazraf.vertx.futures.Futures.when; import static io.vertx.core.Future.future; import static org.slf4j.LoggerFactory.getLogger;
package io.dazraf.vertx; public class HttpServerWrapper { private static final String MESSAGE_OK = "OK"; private static final Logger LOG = getLogger(HttpServerWrapper.class); private final int serverPort; private final HttpServer httpServer; private HttpServerWrapper(int serverPort, HttpServer httpServer) { this.serverPort = serverPort; this.httpServer = httpServer; } public static Future<HttpServerWrapper> createHttpServer(Vertx vertx) { return createHttpServer(vertx, request -> request.bodyHandler(buffer -> { request.response().end(MESSAGE_OK); })); } public static Future<HttpServerWrapper> createHttpServer(Vertx vertx, Consumer<HttpServerRequest> handler) { Future<HttpServerWrapper> httpServer = future(); int serverPort = getFreePort(); LOG.info("initialising server"); vertx.createHttpServer() .requestHandler(handler::accept) .listen(serverPort, ar -> { if (ar.failed()) { httpServer.fail(ar.cause()); } else { httpServer.complete(new HttpServerWrapper(serverPort, ar.result())); } }); // this means that we can chain multiple parallel flows on this future // something that we can't do with a straight Future
// Path: src/test/java/io/dazraf/vertx/SocketTestUtils.java // public static int getFreePort() { // return getFreePort(1).get(0); // } // // Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // Path: src/test/java/io/dazraf/vertx/HttpServerWrapper.java import org.slf4j.Logger; import java.util.function.Consumer; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerRequest; import static io.dazraf.vertx.SocketTestUtils.getFreePort; import static io.dazraf.vertx.futures.Futures.when; import static io.vertx.core.Future.future; import static org.slf4j.LoggerFactory.getLogger; package io.dazraf.vertx; public class HttpServerWrapper { private static final String MESSAGE_OK = "OK"; private static final Logger LOG = getLogger(HttpServerWrapper.class); private final int serverPort; private final HttpServer httpServer; private HttpServerWrapper(int serverPort, HttpServer httpServer) { this.serverPort = serverPort; this.httpServer = httpServer; } public static Future<HttpServerWrapper> createHttpServer(Vertx vertx) { return createHttpServer(vertx, request -> request.bodyHandler(buffer -> { request.response().end(MESSAGE_OK); })); } public static Future<HttpServerWrapper> createHttpServer(Vertx vertx, Consumer<HttpServerRequest> handler) { Future<HttpServerWrapper> httpServer = future(); int serverPort = getFreePort(); LOG.info("initialising server"); vertx.createHttpServer() .requestHandler(handler::accept) .listen(serverPort, ar -> { if (ar.failed()) { httpServer.fail(ar.cause()); } else { httpServer.complete(new HttpServerWrapper(serverPort, ar.result())); } }); // this means that we can chain multiple parallel flows on this future // something that we can't do with a straight Future
return when(httpServer);
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/processors/IfProcessorTest.java
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public class TestUtils { // public static final String RESULT_MSG = "result"; // public static final int RESULT_INT = 42; // public static boolean RESULT_BOOL = true; // } // // Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/test/java/io/dazraf/vertx/futures/VertxMatcherAssert.java // public static <T> void assertThat(TestContext context, T actual, // Matcher<? super T> matcher) { // assertThat(context, "", actual, matcher); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/IfProcessor.java // public interface IfProcessor<T, R> extends FutureProcessor<T, R> { // // static <T, R> IfProcessor<T, R> ifSucceeded(FutureProcessor<T, R> processor) { // return future -> { // if (future.succeeded()) { // return processor.apply(future); // } else { // return failedFuture(future.cause()); // } // }; // } // // static <T> IfProcessor<T, T> ifFailed(FutureProcessor<T, T> processor) { // return future -> { // if (future.failed()) { // return processor.apply(future); // } else { // return succeededFuture(future.result()); // } // }; // } // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // }
import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import static io.dazraf.vertx.TestUtils.*; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.VertxMatcherAssert.assertThat; import static io.dazraf.vertx.futures.processors.IfProcessor.*; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*; import static org.hamcrest.CoreMatchers.is;
package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class IfProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); @Test public void test_givenSuccess_canExecuteHappyPath(TestContext context) { Async async = context.async();
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public class TestUtils { // public static final String RESULT_MSG = "result"; // public static final int RESULT_INT = 42; // public static boolean RESULT_BOOL = true; // } // // Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/test/java/io/dazraf/vertx/futures/VertxMatcherAssert.java // public static <T> void assertThat(TestContext context, T actual, // Matcher<? super T> matcher) { // assertThat(context, "", actual, matcher); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/IfProcessor.java // public interface IfProcessor<T, R> extends FutureProcessor<T, R> { // // static <T, R> IfProcessor<T, R> ifSucceeded(FutureProcessor<T, R> processor) { // return future -> { // if (future.succeeded()) { // return processor.apply(future); // } else { // return failedFuture(future.cause()); // } // }; // } // // static <T> IfProcessor<T, T> ifFailed(FutureProcessor<T, T> processor) { // return future -> { // if (future.failed()) { // return processor.apply(future); // } else { // return succeededFuture(future.result()); // } // }; // } // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // } // Path: src/test/java/io/dazraf/vertx/futures/processors/IfProcessorTest.java import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import static io.dazraf.vertx.TestUtils.*; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.VertxMatcherAssert.assertThat; import static io.dazraf.vertx.futures.processors.IfProcessor.*; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*; import static org.hamcrest.CoreMatchers.is; package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class IfProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); @Test public void test_givenSuccess_canExecuteHappyPath(TestContext context) { Async async = context.async();
when(succeededFuture(RESULT_MSG))
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/processors/IfProcessorTest.java
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public class TestUtils { // public static final String RESULT_MSG = "result"; // public static final int RESULT_INT = 42; // public static boolean RESULT_BOOL = true; // } // // Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/test/java/io/dazraf/vertx/futures/VertxMatcherAssert.java // public static <T> void assertThat(TestContext context, T actual, // Matcher<? super T> matcher) { // assertThat(context, "", actual, matcher); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/IfProcessor.java // public interface IfProcessor<T, R> extends FutureProcessor<T, R> { // // static <T, R> IfProcessor<T, R> ifSucceeded(FutureProcessor<T, R> processor) { // return future -> { // if (future.succeeded()) { // return processor.apply(future); // } else { // return failedFuture(future.cause()); // } // }; // } // // static <T> IfProcessor<T, T> ifFailed(FutureProcessor<T, T> processor) { // return future -> { // if (future.failed()) { // return processor.apply(future); // } else { // return succeededFuture(future.result()); // } // }; // } // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // }
import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import static io.dazraf.vertx.TestUtils.*; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.VertxMatcherAssert.assertThat; import static io.dazraf.vertx.futures.processors.IfProcessor.*; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*; import static org.hamcrest.CoreMatchers.is;
package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class IfProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); @Test public void test_givenSuccess_canExecuteHappyPath(TestContext context) { Async async = context.async(); when(succeededFuture(RESULT_MSG)) .then(ifSucceeded(asyncResult -> succeededFuture(RESULT_BOOL)))
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public class TestUtils { // public static final String RESULT_MSG = "result"; // public static final int RESULT_INT = 42; // public static boolean RESULT_BOOL = true; // } // // Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/test/java/io/dazraf/vertx/futures/VertxMatcherAssert.java // public static <T> void assertThat(TestContext context, T actual, // Matcher<? super T> matcher) { // assertThat(context, "", actual, matcher); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/IfProcessor.java // public interface IfProcessor<T, R> extends FutureProcessor<T, R> { // // static <T, R> IfProcessor<T, R> ifSucceeded(FutureProcessor<T, R> processor) { // return future -> { // if (future.succeeded()) { // return processor.apply(future); // } else { // return failedFuture(future.cause()); // } // }; // } // // static <T> IfProcessor<T, T> ifFailed(FutureProcessor<T, T> processor) { // return future -> { // if (future.failed()) { // return processor.apply(future); // } else { // return succeededFuture(future.result()); // } // }; // } // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // } // Path: src/test/java/io/dazraf/vertx/futures/processors/IfProcessorTest.java import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import static io.dazraf.vertx.TestUtils.*; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.VertxMatcherAssert.assertThat; import static io.dazraf.vertx.futures.processors.IfProcessor.*; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*; import static org.hamcrest.CoreMatchers.is; package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class IfProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); @Test public void test_givenSuccess_canExecuteHappyPath(TestContext context) { Async async = context.async(); when(succeededFuture(RESULT_MSG)) .then(ifSucceeded(asyncResult -> succeededFuture(RESULT_BOOL)))
.then(run(result -> assertThat(context, result, is(RESULT_BOOL))))
dazraf/vertx-futures
src/test/java/io/dazraf/vertx/futures/processors/IfProcessorTest.java
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public class TestUtils { // public static final String RESULT_MSG = "result"; // public static final int RESULT_INT = 42; // public static boolean RESULT_BOOL = true; // } // // Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/test/java/io/dazraf/vertx/futures/VertxMatcherAssert.java // public static <T> void assertThat(TestContext context, T actual, // Matcher<? super T> matcher) { // assertThat(context, "", actual, matcher); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/IfProcessor.java // public interface IfProcessor<T, R> extends FutureProcessor<T, R> { // // static <T, R> IfProcessor<T, R> ifSucceeded(FutureProcessor<T, R> processor) { // return future -> { // if (future.succeeded()) { // return processor.apply(future); // } else { // return failedFuture(future.cause()); // } // }; // } // // static <T> IfProcessor<T, T> ifFailed(FutureProcessor<T, T> processor) { // return future -> { // if (future.failed()) { // return processor.apply(future); // } else { // return succeededFuture(future.result()); // } // }; // } // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // }
import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import static io.dazraf.vertx.TestUtils.*; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.VertxMatcherAssert.assertThat; import static io.dazraf.vertx.futures.processors.IfProcessor.*; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*; import static org.hamcrest.CoreMatchers.is;
package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class IfProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); @Test public void test_givenSuccess_canExecuteHappyPath(TestContext context) { Async async = context.async(); when(succeededFuture(RESULT_MSG)) .then(ifSucceeded(asyncResult -> succeededFuture(RESULT_BOOL))) .then(run(result -> assertThat(context, result, is(RESULT_BOOL)))) .then(run(async::complete))
// Path: src/test/java/io/dazraf/vertx/TestUtils.java // public class TestUtils { // public static final String RESULT_MSG = "result"; // public static final int RESULT_INT = 42; // public static boolean RESULT_BOOL = true; // } // // Path: src/main/java/io/dazraf/vertx/futures/Futures.java // static <T> Futures<T> when(Future<T> future) { // return FuturesImpl.when(future); // } // // Path: src/test/java/io/dazraf/vertx/futures/VertxMatcherAssert.java // public static <T> void assertThat(TestContext context, T actual, // Matcher<? super T> matcher) { // assertThat(context, "", actual, matcher); // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/IfProcessor.java // public interface IfProcessor<T, R> extends FutureProcessor<T, R> { // // static <T, R> IfProcessor<T, R> ifSucceeded(FutureProcessor<T, R> processor) { // return future -> { // if (future.succeeded()) { // return processor.apply(future); // } else { // return failedFuture(future.cause()); // } // }; // } // // static <T> IfProcessor<T, T> ifFailed(FutureProcessor<T, T> processor) { // return future -> { // if (future.failed()) { // return processor.apply(future); // } else { // return succeededFuture(future.result()); // } // }; // } // } // // Path: src/main/java/io/dazraf/vertx/futures/processors/RunProcessor.java // public interface RunProcessor<T> extends FutureProcessor<T, T> { // // Logger LOG = getLogger(RunProcessor.class); // // /** // * Observe the state of the chain. Any exceptions from the consumer will cause the chain to fail. // * @param consumer // * @param <T> // * @return // */ // static <T> RunProcessor<T> runOnResponse(Handler<AsyncResult<T>> consumer) { // return future -> { // Future<T> result = Future.future(); // try { // consumer.handle(future); // result.completer().handle(future); // } catch (Throwable error) { // LOG.error("consumer function failed", error); // result.fail(error); // } // return result; // }; // } // // static <T> RunProcessor<T> run(Runnable runnable) { // return runOnResponse(success(runnable)); // } // // static <T> RunProcessor<T> run(Consumer<T> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2> RunProcessor<Tuple2<T1, T2>> run(Consumer2<T1, T2> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3> RunProcessor<Tuple3<T1, T2, T3>> run(Consumer3<T1, T2, T3> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4> RunProcessor<Tuple4<T1, T2, T3, T4>> run(Consumer4<T1, T2, T3, T4> consumer) { // return runOnResponse(success(consumer)); // } // // static <T1, T2, T3, T4, T5> RunProcessor<Tuple5<T1, T2, T3, T4, T5>> run(Consumer5<T1, T2, T3, T4, T5> consumer) { // return runOnResponse(success(consumer)); // } // // static <T> RunProcessor<T> runOnFail(Consumer<Throwable> consumer) { // return runOnResponse(failure(consumer)); // } // // } // Path: src/test/java/io/dazraf/vertx/futures/processors/IfProcessorTest.java import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import static io.dazraf.vertx.TestUtils.*; import static io.dazraf.vertx.futures.Futures.when; import static io.dazraf.vertx.futures.VertxMatcherAssert.assertThat; import static io.dazraf.vertx.futures.processors.IfProcessor.*; import static io.dazraf.vertx.futures.processors.RunProcessor.*; import static io.vertx.core.Future.*; import static org.hamcrest.CoreMatchers.is; package io.dazraf.vertx.futures.processors; @RunWith(VertxUnitRunner.class) public class IfProcessorTest { @ClassRule public static final RunTestOnContext vertxContext = new RunTestOnContext(); @Test public void test_givenSuccess_canExecuteHappyPath(TestContext context) { Async async = context.async(); when(succeededFuture(RESULT_MSG)) .then(ifSucceeded(asyncResult -> succeededFuture(RESULT_BOOL))) .then(run(result -> assertThat(context, result, is(RESULT_BOOL)))) .then(run(async::complete))
.then(RunProcessor.runOnFail(context::fail));
dazraf/vertx-futures
src/main/java/io/dazraf/vertx/tuple/Tuple2.java
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer2.java // @FunctionalInterface // public interface Consumer2<T1, T2> extends ConsumerN { // void accept(T1 t1, T2 t2); // } // // Path: src/main/java/io/dazraf/vertx/function/Function2.java // @FunctionalInterface // public interface Function2<T1, T2, R> extends FunctionN { // R apply(T1 t1, T2 t2); // }
import io.dazraf.vertx.consumer.Consumer2; import io.dazraf.vertx.function.Function2; import io.vertx.core.CompositeFuture;
package io.dazraf.vertx.tuple; /** * A tuple of two values of type {@link T1} and {@link T2} * @param <T1> The type of the first value in the tuple * @param <T2> The type of the second value in the tuple */ public class Tuple2<T1, T2> extends Tuple<Tuple2<T1, T2>> { private final T1 t1; private final T2 t2; /** * Construct using values for the two types * @param t1 the value of the first type * @param t2 the value of the second type */ public Tuple2(T1 t1, T2 t2) { this.t1 = t1; this.t2 = t2; } /** * Construct from a <i>completed</i> future * @param compositeFuture a composite future that should contain two values of types that are assignable to this types generic parameters */ public Tuple2(CompositeFuture compositeFuture) { assert(compositeFuture.succeeded()); this.t1 = compositeFuture.result(0); this.t2 = compositeFuture.result(1); } /** * Retrieve the first value * @return the value of the first type */ public T1 getT1() { return t1; } /** * Retrieve the second value * @return the value of the second type */ public T2 getT2() { return t2; } /** * Calls a {@link Consumer2} function with the two values of this tuple. Any exceptions are propagated up the stack. * @param consumer The consumer function, that will be called with two values from this tuple. */
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer2.java // @FunctionalInterface // public interface Consumer2<T1, T2> extends ConsumerN { // void accept(T1 t1, T2 t2); // } // // Path: src/main/java/io/dazraf/vertx/function/Function2.java // @FunctionalInterface // public interface Function2<T1, T2, R> extends FunctionN { // R apply(T1 t1, T2 t2); // } // Path: src/main/java/io/dazraf/vertx/tuple/Tuple2.java import io.dazraf.vertx.consumer.Consumer2; import io.dazraf.vertx.function.Function2; import io.vertx.core.CompositeFuture; package io.dazraf.vertx.tuple; /** * A tuple of two values of type {@link T1} and {@link T2} * @param <T1> The type of the first value in the tuple * @param <T2> The type of the second value in the tuple */ public class Tuple2<T1, T2> extends Tuple<Tuple2<T1, T2>> { private final T1 t1; private final T2 t2; /** * Construct using values for the two types * @param t1 the value of the first type * @param t2 the value of the second type */ public Tuple2(T1 t1, T2 t2) { this.t1 = t1; this.t2 = t2; } /** * Construct from a <i>completed</i> future * @param compositeFuture a composite future that should contain two values of types that are assignable to this types generic parameters */ public Tuple2(CompositeFuture compositeFuture) { assert(compositeFuture.succeeded()); this.t1 = compositeFuture.result(0); this.t2 = compositeFuture.result(1); } /** * Retrieve the first value * @return the value of the first type */ public T1 getT1() { return t1; } /** * Retrieve the second value * @return the value of the second type */ public T2 getT2() { return t2; } /** * Calls a {@link Consumer2} function with the two values of this tuple. Any exceptions are propagated up the stack. * @param consumer The consumer function, that will be called with two values from this tuple. */
public void accept(Consumer2<T1, T2> consumer) {
dazraf/vertx-futures
src/main/java/io/dazraf/vertx/tuple/Tuple2.java
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer2.java // @FunctionalInterface // public interface Consumer2<T1, T2> extends ConsumerN { // void accept(T1 t1, T2 t2); // } // // Path: src/main/java/io/dazraf/vertx/function/Function2.java // @FunctionalInterface // public interface Function2<T1, T2, R> extends FunctionN { // R apply(T1 t1, T2 t2); // }
import io.dazraf.vertx.consumer.Consumer2; import io.dazraf.vertx.function.Function2; import io.vertx.core.CompositeFuture;
package io.dazraf.vertx.tuple; /** * A tuple of two values of type {@link T1} and {@link T2} * @param <T1> The type of the first value in the tuple * @param <T2> The type of the second value in the tuple */ public class Tuple2<T1, T2> extends Tuple<Tuple2<T1, T2>> { private final T1 t1; private final T2 t2; /** * Construct using values for the two types * @param t1 the value of the first type * @param t2 the value of the second type */ public Tuple2(T1 t1, T2 t2) { this.t1 = t1; this.t2 = t2; } /** * Construct from a <i>completed</i> future * @param compositeFuture a composite future that should contain two values of types that are assignable to this types generic parameters */ public Tuple2(CompositeFuture compositeFuture) { assert(compositeFuture.succeeded()); this.t1 = compositeFuture.result(0); this.t2 = compositeFuture.result(1); } /** * Retrieve the first value * @return the value of the first type */ public T1 getT1() { return t1; } /** * Retrieve the second value * @return the value of the second type */ public T2 getT2() { return t2; } /** * Calls a {@link Consumer2} function with the two values of this tuple. Any exceptions are propagated up the stack. * @param consumer The consumer function, that will be called with two values from this tuple. */ public void accept(Consumer2<T1, T2> consumer) { consumer.accept(t1, t2); } /** * Calls a {@link Function2} function with the two values of the tuple and returns the result of that function. * Any exceptions are propagated up the stack. * @param function the function, that will be called with the two values from this tuple and returns a result of type {@link R} * @param <R> The type of the result returned from <code>#function</code> * @return The result from calling the function */
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer2.java // @FunctionalInterface // public interface Consumer2<T1, T2> extends ConsumerN { // void accept(T1 t1, T2 t2); // } // // Path: src/main/java/io/dazraf/vertx/function/Function2.java // @FunctionalInterface // public interface Function2<T1, T2, R> extends FunctionN { // R apply(T1 t1, T2 t2); // } // Path: src/main/java/io/dazraf/vertx/tuple/Tuple2.java import io.dazraf.vertx.consumer.Consumer2; import io.dazraf.vertx.function.Function2; import io.vertx.core.CompositeFuture; package io.dazraf.vertx.tuple; /** * A tuple of two values of type {@link T1} and {@link T2} * @param <T1> The type of the first value in the tuple * @param <T2> The type of the second value in the tuple */ public class Tuple2<T1, T2> extends Tuple<Tuple2<T1, T2>> { private final T1 t1; private final T2 t2; /** * Construct using values for the two types * @param t1 the value of the first type * @param t2 the value of the second type */ public Tuple2(T1 t1, T2 t2) { this.t1 = t1; this.t2 = t2; } /** * Construct from a <i>completed</i> future * @param compositeFuture a composite future that should contain two values of types that are assignable to this types generic parameters */ public Tuple2(CompositeFuture compositeFuture) { assert(compositeFuture.succeeded()); this.t1 = compositeFuture.result(0); this.t2 = compositeFuture.result(1); } /** * Retrieve the first value * @return the value of the first type */ public T1 getT1() { return t1; } /** * Retrieve the second value * @return the value of the second type */ public T2 getT2() { return t2; } /** * Calls a {@link Consumer2} function with the two values of this tuple. Any exceptions are propagated up the stack. * @param consumer The consumer function, that will be called with two values from this tuple. */ public void accept(Consumer2<T1, T2> consumer) { consumer.accept(t1, t2); } /** * Calls a {@link Function2} function with the two values of the tuple and returns the result of that function. * Any exceptions are propagated up the stack. * @param function the function, that will be called with the two values from this tuple and returns a result of type {@link R} * @param <R> The type of the result returned from <code>#function</code> * @return The result from calling the function */
public <R> R apply(Function2<T1, T2, R> function) {
dazraf/vertx-futures
src/main/java/io/dazraf/vertx/tuple/Tuple4.java
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer4.java // @FunctionalInterface // public interface Consumer4<T1, T2, T3, T4> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3, T4 t4); // } // // Path: src/main/java/io/dazraf/vertx/function/Function4.java // @FunctionalInterface // public interface Function4<T1, T2, T3, T4, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3, T4 t4); // }
import io.dazraf.vertx.consumer.Consumer4; import io.dazraf.vertx.function.Function4; import io.vertx.core.CompositeFuture;
* * @return the value of the second type */ public T2 getT2() { return t2; } /** * Retrieve the third value * * @return the value of the third type */ public T3 getT3() { return t3; } /** * Retrieve the fourth value * * @return the value for the fourth type */ public T4 getT4() { return t4; } /** * Calls a {@link Consumer4} function with the four values of this tuple. Any exceptions are propagated up the stack. * * @param consumer The consumer function, that will be called with four values from this tuple. */
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer4.java // @FunctionalInterface // public interface Consumer4<T1, T2, T3, T4> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3, T4 t4); // } // // Path: src/main/java/io/dazraf/vertx/function/Function4.java // @FunctionalInterface // public interface Function4<T1, T2, T3, T4, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3, T4 t4); // } // Path: src/main/java/io/dazraf/vertx/tuple/Tuple4.java import io.dazraf.vertx.consumer.Consumer4; import io.dazraf.vertx.function.Function4; import io.vertx.core.CompositeFuture; * * @return the value of the second type */ public T2 getT2() { return t2; } /** * Retrieve the third value * * @return the value of the third type */ public T3 getT3() { return t3; } /** * Retrieve the fourth value * * @return the value for the fourth type */ public T4 getT4() { return t4; } /** * Calls a {@link Consumer4} function with the four values of this tuple. Any exceptions are propagated up the stack. * * @param consumer The consumer function, that will be called with four values from this tuple. */
public void accept(Consumer4<T1, T2, T3, T4> consumer) {
dazraf/vertx-futures
src/main/java/io/dazraf/vertx/tuple/Tuple4.java
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer4.java // @FunctionalInterface // public interface Consumer4<T1, T2, T3, T4> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3, T4 t4); // } // // Path: src/main/java/io/dazraf/vertx/function/Function4.java // @FunctionalInterface // public interface Function4<T1, T2, T3, T4, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3, T4 t4); // }
import io.dazraf.vertx.consumer.Consumer4; import io.dazraf.vertx.function.Function4; import io.vertx.core.CompositeFuture;
public T3 getT3() { return t3; } /** * Retrieve the fourth value * * @return the value for the fourth type */ public T4 getT4() { return t4; } /** * Calls a {@link Consumer4} function with the four values of this tuple. Any exceptions are propagated up the stack. * * @param consumer The consumer function, that will be called with four values from this tuple. */ public void accept(Consumer4<T1, T2, T3, T4> consumer) { consumer.accept(t1, t2, t3, t4); } /** * Calls a {@link Function4} function with the four values of the tuple and returns the result of that function. * Any exceptions are propagated up the stack. * * @param function the function, that will be called with four values from this tuple and returns a result of type {@link R} * @param <R> The type of the result returned from <code>#function</code> * @return The result from calling the function */
// Path: src/main/java/io/dazraf/vertx/consumer/Consumer4.java // @FunctionalInterface // public interface Consumer4<T1, T2, T3, T4> extends ConsumerN { // void accept(T1 t1, T2 t2, T3 t3, T4 t4); // } // // Path: src/main/java/io/dazraf/vertx/function/Function4.java // @FunctionalInterface // public interface Function4<T1, T2, T3, T4, R> extends FunctionN { // R apply(T1 t1, T2 t2, T3 t3, T4 t4); // } // Path: src/main/java/io/dazraf/vertx/tuple/Tuple4.java import io.dazraf.vertx.consumer.Consumer4; import io.dazraf.vertx.function.Function4; import io.vertx.core.CompositeFuture; public T3 getT3() { return t3; } /** * Retrieve the fourth value * * @return the value for the fourth type */ public T4 getT4() { return t4; } /** * Calls a {@link Consumer4} function with the four values of this tuple. Any exceptions are propagated up the stack. * * @param consumer The consumer function, that will be called with four values from this tuple. */ public void accept(Consumer4<T1, T2, T3, T4> consumer) { consumer.accept(t1, t2, t3, t4); } /** * Calls a {@link Function4} function with the four values of the tuple and returns the result of that function. * Any exceptions are propagated up the stack. * * @param function the function, that will be called with four values from this tuple and returns a result of type {@link R} * @param <R> The type of the result returned from <code>#function</code> * @return The result from calling the function */
public <R> R apply(Function4<T1, T2, T3, T4, R> function) {