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
quartzweb/quartz-web
src/main/java/com/github/quartzweb/service/strategy/QuartzWebServiceContext.java
// Path: src/main/java/com/github/quartzweb/service/JSONResult.java // public class JSONResult { // // /** // * 返回结果code // */ // private int resultCode; // // /** // * 返回结果 // */ // private Object content; // // /** // * 返回json结果-成功(1) // */ // public static final int RESULT_CODE_SUCCESS = 1; // // /** // * 返回json结果-失败(-1) // */ // public static final int RESULT_CODE_ERROR = -1; // // public JSONResult(int resultCode, Object content) { // this.resultCode = resultCode; // this.content = content; // } // // /** // * 创建一个json结果 // * @param resultCode // * @param content // * @return // */ // public static JSONResult build(int resultCode, Object content){ // return new JSONResult(resultCode, content); // } // // public String json() { // Map<String, Object> dataMap = new LinkedHashMap<String, Object>(); // dataMap.put("resultCode", this.resultCode); // dataMap.put("content", this.content); // return JSONUtils.toJSONString(dataMap); // } // // // public static String returnJSON(int resultCode, Object content) { // Map<String, Object> dataMap = new LinkedHashMap<String, Object>(); // dataMap.put("resultCode", resultCode); // dataMap.put("content", content); // return JSONUtils.toJSONString(dataMap); // } // }
import com.github.quartzweb.service.JSONResult;
/** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.service.strategy; /** * @author quxiucheng [[email protected]] */ public class QuartzWebServiceContext { private ServiceStrategy serviceStrategy; public QuartzWebServiceContext(ServiceStrategy serviceStrategy) { this.serviceStrategy = serviceStrategy; }
// Path: src/main/java/com/github/quartzweb/service/JSONResult.java // public class JSONResult { // // /** // * 返回结果code // */ // private int resultCode; // // /** // * 返回结果 // */ // private Object content; // // /** // * 返回json结果-成功(1) // */ // public static final int RESULT_CODE_SUCCESS = 1; // // /** // * 返回json结果-失败(-1) // */ // public static final int RESULT_CODE_ERROR = -1; // // public JSONResult(int resultCode, Object content) { // this.resultCode = resultCode; // this.content = content; // } // // /** // * 创建一个json结果 // * @param resultCode // * @param content // * @return // */ // public static JSONResult build(int resultCode, Object content){ // return new JSONResult(resultCode, content); // } // // public String json() { // Map<String, Object> dataMap = new LinkedHashMap<String, Object>(); // dataMap.put("resultCode", this.resultCode); // dataMap.put("content", this.content); // return JSONUtils.toJSONString(dataMap); // } // // // public static String returnJSON(int resultCode, Object content) { // Map<String, Object> dataMap = new LinkedHashMap<String, Object>(); // dataMap.put("resultCode", resultCode); // dataMap.put("content", content); // return JSONUtils.toJSONString(dataMap); // } // } // Path: src/main/java/com/github/quartzweb/service/strategy/QuartzWebServiceContext.java import com.github.quartzweb.service.JSONResult; /** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.service.strategy; /** * @author quxiucheng [[email protected]] */ public class QuartzWebServiceContext { private ServiceStrategy serviceStrategy; public QuartzWebServiceContext(ServiceStrategy serviceStrategy) { this.serviceStrategy = serviceStrategy; }
public JSONResult service(ServiceStrategyURL serviceStrategyURL, ServiceStrategyParameter parameter){
quartzweb/quartz-web
src/main/java/com/github/quartzweb/service/JSONResult.java
// Path: src/main/java/com/github/quartzweb/utils/json/JSONUtils.java // public class JSONUtils { // // public static String toJSONString(Object o) { // JSONWriter writer = new JSONWriter(); // writer.writeObject(o); // return writer.toString(); // } // // public static Object parse(String text) { // JSONParser parser = new JSONParser(text); // return parser.parse(); // } // }
import java.util.Map; import com.github.quartzweb.utils.json.JSONUtils; import java.util.LinkedHashMap;
/** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.service; /** * @author quxiucheng [[email protected]] */ public class JSONResult { /** * 返回结果code */ private int resultCode; /** * 返回结果 */ private Object content; /** * 返回json结果-成功(1) */ public static final int RESULT_CODE_SUCCESS = 1; /** * 返回json结果-失败(-1) */ public static final int RESULT_CODE_ERROR = -1; public JSONResult(int resultCode, Object content) { this.resultCode = resultCode; this.content = content; } /** * 创建一个json结果 * @param resultCode * @param content * @return */ public static JSONResult build(int resultCode, Object content){ return new JSONResult(resultCode, content); } public String json() { Map<String, Object> dataMap = new LinkedHashMap<String, Object>(); dataMap.put("resultCode", this.resultCode); dataMap.put("content", this.content);
// Path: src/main/java/com/github/quartzweb/utils/json/JSONUtils.java // public class JSONUtils { // // public static String toJSONString(Object o) { // JSONWriter writer = new JSONWriter(); // writer.writeObject(o); // return writer.toString(); // } // // public static Object parse(String text) { // JSONParser parser = new JSONParser(text); // return parser.parse(); // } // } // Path: src/main/java/com/github/quartzweb/service/JSONResult.java import java.util.Map; import com.github.quartzweb.utils.json.JSONUtils; import java.util.LinkedHashMap; /** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.service; /** * @author quxiucheng [[email protected]] */ public class JSONResult { /** * 返回结果code */ private int resultCode; /** * 返回结果 */ private Object content; /** * 返回json结果-成功(1) */ public static final int RESULT_CODE_SUCCESS = 1; /** * 返回json结果-失败(-1) */ public static final int RESULT_CODE_ERROR = -1; public JSONResult(int resultCode, Object content) { this.resultCode = resultCode; this.content = content; } /** * 创建一个json结果 * @param resultCode * @param content * @return */ public static JSONResult build(int resultCode, Object content){ return new JSONResult(resultCode, content); } public String json() { Map<String, Object> dataMap = new LinkedHashMap<String, Object>(); dataMap.put("resultCode", this.resultCode); dataMap.put("content", this.content);
return JSONUtils.toJSONString(dataMap);
quartzweb/quartz-web
src/main/java/com/github/quartzweb/utils/json/JSONWriter.java
// Path: src/main/java/com/github/quartzweb/utils/ExceptionUtils.java // public class ExceptionUtils { // // /** // * 将异常转化为信息 // * @param ex 异常 // * @return // */ // public static String getStackTrace(Throwable ex) { // StringWriter buf = new StringWriter(); // ex.printStackTrace(new PrintWriter(buf)); // return buf.toString(); // } // // }
import com.github.quartzweb.utils.ExceptionUtils; import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularData; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Map;
} } } //throw new IllegalArgumentException("not support type : " + o.getClass()); } public void writeDate(Date date) { if (date == null) { writeNull(); return; } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); writeString(dateFormat.format(date)); } public void writeError(Throwable error) { if (error == null) { writeNull(); return; } write("{\"Class\":"); writeString(error.getClass().getName()); write(",\"Message\":"); writeString(error.getMessage()); write(",\"StackTrace\":");
// Path: src/main/java/com/github/quartzweb/utils/ExceptionUtils.java // public class ExceptionUtils { // // /** // * 将异常转化为信息 // * @param ex 异常 // * @return // */ // public static String getStackTrace(Throwable ex) { // StringWriter buf = new StringWriter(); // ex.printStackTrace(new PrintWriter(buf)); // return buf.toString(); // } // // } // Path: src/main/java/com/github/quartzweb/utils/json/JSONWriter.java import com.github.quartzweb.utils.ExceptionUtils; import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularData; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Map; } } } //throw new IllegalArgumentException("not support type : " + o.getClass()); } public void writeDate(Date date) { if (date == null) { writeNull(); return; } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); writeString(dateFormat.format(date)); } public void writeError(Throwable error) { if (error == null) { writeNull(); return; } write("{\"Class\":"); writeString(error.getClass().getName()); write(",\"Message\":"); writeString(error.getMessage()); write(",\"StackTrace\":");
writeString(ExceptionUtils.getStackTrace(error));
quartzweb/quartz-web
src/main/java/com/github/quartzweb/http/QuartzWebServlet.java
// Path: src/main/java/com/github/quartzweb/service/QuartzWebService.java // public class QuartzWebService { // // private final static QuartzWebService instance = new QuartzWebService(); // // public static QuartzWebService getInstance() { // return instance; // } // // /** // * 业务策略工厂 // */ // private ServiceStrategyFactory serviceStrategyFactory = new DefaultServiceStrategyFactory(); // // // /** // * {@inheritDoc} // */ // public String service(String path, HttpServletRequest request, HttpServletResponse response) { // // try { // // LOG.debug("request:" + LOG.buildLogMessage(request)); // ServiceStrategy serviceStrategy = serviceStrategyFactory.createStrategy(path); // ServiceStrategyParameter parameter = serviceStrategy.newServiceStrategyParameterInstance(); // parameter.translate(request); // ServiceStrategyURL serviceStrategyURL = new DefaultServiceStrategyURL(path); // QuartzWebServiceContext context = new QuartzWebServiceContext(serviceStrategy); // String json = context.service(serviceStrategyURL, parameter).json(); // LOG.debug("json result:" + json.toLowerCase()); // return json; // } catch (Exception e) { // //e.printStackTrace(); // LOG.debug("service error:", e); // return JSONResult.build(JSONResult.RESULT_CODE_ERROR, e.getMessage()).json(); // } // // } // // // /** // * 获取 业务策略工厂 // * @return serviceStrategyFactory 业务策略工厂 // */ // public ServiceStrategyFactory getServiceStrategyFactory() { // return this.serviceStrategyFactory; // } // // /** // * 设置 业务策略工厂 // * @param serviceStrategyFactory 业务策略工厂 // */ // public void setServiceStrategyFactory(ServiceStrategyFactory serviceStrategyFactory) { // this.serviceStrategyFactory = serviceStrategyFactory; // } // } // // Path: src/main/java/com/github/quartzweb/utils/StringUtils.java // public class StringUtils { // // /** // * 判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equals(String a, String b) { // if (a == null) { // return b == null; // } // return a.equals(b); // } // // /** // * 忽略大小写判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equalsIgnoreCase(String a, String b) { // if (a == null) { // return b == null; // } // return a.equalsIgnoreCase(b); // } // // /** // * 判断字符串是否为空(NULL或空串"") // * @param value 字符串 // * @return true为空,false不为空 // */ // public static boolean isEmpty(CharSequence value) { // if (value == null || value.length() == 0) { // return true; // } // return false; // } // // /** // * 是否为整数 // * @param str // * @return // */ // public static boolean isInteger(String str) { // Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); // return pattern.matcher(str).matches(); // } // // /** // * 判断是否为大于某个数字的整数 // * @param str // * @param integer // * @return // */ // public static boolean isIntegerGTNumber(String str,Integer integer) { // // 是整数 // if (isInteger(str)) { // int source = Integer.parseInt(str); // return source > integer; // } else { // return false; // } // } // }
import com.github.quartzweb.service.QuartzWebService; import com.github.quartzweb.utils.StringUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.http; /** * 负责处理业务servlet * @author quxiucheng [[email protected]] */ public class QuartzWebServlet extends SecurityServlet { public static final String PARAM_RESOURCE_PATH = "resourcePath";
// Path: src/main/java/com/github/quartzweb/service/QuartzWebService.java // public class QuartzWebService { // // private final static QuartzWebService instance = new QuartzWebService(); // // public static QuartzWebService getInstance() { // return instance; // } // // /** // * 业务策略工厂 // */ // private ServiceStrategyFactory serviceStrategyFactory = new DefaultServiceStrategyFactory(); // // // /** // * {@inheritDoc} // */ // public String service(String path, HttpServletRequest request, HttpServletResponse response) { // // try { // // LOG.debug("request:" + LOG.buildLogMessage(request)); // ServiceStrategy serviceStrategy = serviceStrategyFactory.createStrategy(path); // ServiceStrategyParameter parameter = serviceStrategy.newServiceStrategyParameterInstance(); // parameter.translate(request); // ServiceStrategyURL serviceStrategyURL = new DefaultServiceStrategyURL(path); // QuartzWebServiceContext context = new QuartzWebServiceContext(serviceStrategy); // String json = context.service(serviceStrategyURL, parameter).json(); // LOG.debug("json result:" + json.toLowerCase()); // return json; // } catch (Exception e) { // //e.printStackTrace(); // LOG.debug("service error:", e); // return JSONResult.build(JSONResult.RESULT_CODE_ERROR, e.getMessage()).json(); // } // // } // // // /** // * 获取 业务策略工厂 // * @return serviceStrategyFactory 业务策略工厂 // */ // public ServiceStrategyFactory getServiceStrategyFactory() { // return this.serviceStrategyFactory; // } // // /** // * 设置 业务策略工厂 // * @param serviceStrategyFactory 业务策略工厂 // */ // public void setServiceStrategyFactory(ServiceStrategyFactory serviceStrategyFactory) { // this.serviceStrategyFactory = serviceStrategyFactory; // } // } // // Path: src/main/java/com/github/quartzweb/utils/StringUtils.java // public class StringUtils { // // /** // * 判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equals(String a, String b) { // if (a == null) { // return b == null; // } // return a.equals(b); // } // // /** // * 忽略大小写判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equalsIgnoreCase(String a, String b) { // if (a == null) { // return b == null; // } // return a.equalsIgnoreCase(b); // } // // /** // * 判断字符串是否为空(NULL或空串"") // * @param value 字符串 // * @return true为空,false不为空 // */ // public static boolean isEmpty(CharSequence value) { // if (value == null || value.length() == 0) { // return true; // } // return false; // } // // /** // * 是否为整数 // * @param str // * @return // */ // public static boolean isInteger(String str) { // Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); // return pattern.matcher(str).matches(); // } // // /** // * 判断是否为大于某个数字的整数 // * @param str // * @param integer // * @return // */ // public static boolean isIntegerGTNumber(String str,Integer integer) { // // 是整数 // if (isInteger(str)) { // int source = Integer.parseInt(str); // return source > integer; // } else { // return false; // } // } // } // Path: src/main/java/com/github/quartzweb/http/QuartzWebServlet.java import com.github.quartzweb.service.QuartzWebService; import com.github.quartzweb.utils.StringUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.http; /** * 负责处理业务servlet * @author quxiucheng [[email protected]] */ public class QuartzWebServlet extends SecurityServlet { public static final String PARAM_RESOURCE_PATH = "resourcePath";
private QuartzWebService quartzWebService = QuartzWebService.getInstance();
quartzweb/quartz-web
src/main/java/com/github/quartzweb/http/QuartzWebServlet.java
// Path: src/main/java/com/github/quartzweb/service/QuartzWebService.java // public class QuartzWebService { // // private final static QuartzWebService instance = new QuartzWebService(); // // public static QuartzWebService getInstance() { // return instance; // } // // /** // * 业务策略工厂 // */ // private ServiceStrategyFactory serviceStrategyFactory = new DefaultServiceStrategyFactory(); // // // /** // * {@inheritDoc} // */ // public String service(String path, HttpServletRequest request, HttpServletResponse response) { // // try { // // LOG.debug("request:" + LOG.buildLogMessage(request)); // ServiceStrategy serviceStrategy = serviceStrategyFactory.createStrategy(path); // ServiceStrategyParameter parameter = serviceStrategy.newServiceStrategyParameterInstance(); // parameter.translate(request); // ServiceStrategyURL serviceStrategyURL = new DefaultServiceStrategyURL(path); // QuartzWebServiceContext context = new QuartzWebServiceContext(serviceStrategy); // String json = context.service(serviceStrategyURL, parameter).json(); // LOG.debug("json result:" + json.toLowerCase()); // return json; // } catch (Exception e) { // //e.printStackTrace(); // LOG.debug("service error:", e); // return JSONResult.build(JSONResult.RESULT_CODE_ERROR, e.getMessage()).json(); // } // // } // // // /** // * 获取 业务策略工厂 // * @return serviceStrategyFactory 业务策略工厂 // */ // public ServiceStrategyFactory getServiceStrategyFactory() { // return this.serviceStrategyFactory; // } // // /** // * 设置 业务策略工厂 // * @param serviceStrategyFactory 业务策略工厂 // */ // public void setServiceStrategyFactory(ServiceStrategyFactory serviceStrategyFactory) { // this.serviceStrategyFactory = serviceStrategyFactory; // } // } // // Path: src/main/java/com/github/quartzweb/utils/StringUtils.java // public class StringUtils { // // /** // * 判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equals(String a, String b) { // if (a == null) { // return b == null; // } // return a.equals(b); // } // // /** // * 忽略大小写判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equalsIgnoreCase(String a, String b) { // if (a == null) { // return b == null; // } // return a.equalsIgnoreCase(b); // } // // /** // * 判断字符串是否为空(NULL或空串"") // * @param value 字符串 // * @return true为空,false不为空 // */ // public static boolean isEmpty(CharSequence value) { // if (value == null || value.length() == 0) { // return true; // } // return false; // } // // /** // * 是否为整数 // * @param str // * @return // */ // public static boolean isInteger(String str) { // Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); // return pattern.matcher(str).matches(); // } // // /** // * 判断是否为大于某个数字的整数 // * @param str // * @param integer // * @return // */ // public static boolean isIntegerGTNumber(String str,Integer integer) { // // 是整数 // if (isInteger(str)) { // int source = Integer.parseInt(str); // return source > integer; // } else { // return false; // } // } // }
import com.github.quartzweb.service.QuartzWebService; import com.github.quartzweb.utils.StringUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.http; /** * 负责处理业务servlet * @author quxiucheng [[email protected]] */ public class QuartzWebServlet extends SecurityServlet { public static final String PARAM_RESOURCE_PATH = "resourcePath"; private QuartzWebService quartzWebService = QuartzWebService.getInstance(); /** * 设置资源路径 * @throws ServletException */ public void init() throws ServletException { super.init(); // 用户是否有配置新的资源路径 String paraResourcePath = getInitParameter(PARAM_RESOURCE_PATH);
// Path: src/main/java/com/github/quartzweb/service/QuartzWebService.java // public class QuartzWebService { // // private final static QuartzWebService instance = new QuartzWebService(); // // public static QuartzWebService getInstance() { // return instance; // } // // /** // * 业务策略工厂 // */ // private ServiceStrategyFactory serviceStrategyFactory = new DefaultServiceStrategyFactory(); // // // /** // * {@inheritDoc} // */ // public String service(String path, HttpServletRequest request, HttpServletResponse response) { // // try { // // LOG.debug("request:" + LOG.buildLogMessage(request)); // ServiceStrategy serviceStrategy = serviceStrategyFactory.createStrategy(path); // ServiceStrategyParameter parameter = serviceStrategy.newServiceStrategyParameterInstance(); // parameter.translate(request); // ServiceStrategyURL serviceStrategyURL = new DefaultServiceStrategyURL(path); // QuartzWebServiceContext context = new QuartzWebServiceContext(serviceStrategy); // String json = context.service(serviceStrategyURL, parameter).json(); // LOG.debug("json result:" + json.toLowerCase()); // return json; // } catch (Exception e) { // //e.printStackTrace(); // LOG.debug("service error:", e); // return JSONResult.build(JSONResult.RESULT_CODE_ERROR, e.getMessage()).json(); // } // // } // // // /** // * 获取 业务策略工厂 // * @return serviceStrategyFactory 业务策略工厂 // */ // public ServiceStrategyFactory getServiceStrategyFactory() { // return this.serviceStrategyFactory; // } // // /** // * 设置 业务策略工厂 // * @param serviceStrategyFactory 业务策略工厂 // */ // public void setServiceStrategyFactory(ServiceStrategyFactory serviceStrategyFactory) { // this.serviceStrategyFactory = serviceStrategyFactory; // } // } // // Path: src/main/java/com/github/quartzweb/utils/StringUtils.java // public class StringUtils { // // /** // * 判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equals(String a, String b) { // if (a == null) { // return b == null; // } // return a.equals(b); // } // // /** // * 忽略大小写判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equalsIgnoreCase(String a, String b) { // if (a == null) { // return b == null; // } // return a.equalsIgnoreCase(b); // } // // /** // * 判断字符串是否为空(NULL或空串"") // * @param value 字符串 // * @return true为空,false不为空 // */ // public static boolean isEmpty(CharSequence value) { // if (value == null || value.length() == 0) { // return true; // } // return false; // } // // /** // * 是否为整数 // * @param str // * @return // */ // public static boolean isInteger(String str) { // Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); // return pattern.matcher(str).matches(); // } // // /** // * 判断是否为大于某个数字的整数 // * @param str // * @param integer // * @return // */ // public static boolean isIntegerGTNumber(String str,Integer integer) { // // 是整数 // if (isInteger(str)) { // int source = Integer.parseInt(str); // return source > integer; // } else { // return false; // } // } // } // Path: src/main/java/com/github/quartzweb/http/QuartzWebServlet.java import com.github.quartzweb.service.QuartzWebService; import com.github.quartzweb.utils.StringUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.http; /** * 负责处理业务servlet * @author quxiucheng [[email protected]] */ public class QuartzWebServlet extends SecurityServlet { public static final String PARAM_RESOURCE_PATH = "resourcePath"; private QuartzWebService quartzWebService = QuartzWebService.getInstance(); /** * 设置资源路径 * @throws ServletException */ public void init() throws ServletException { super.init(); // 用户是否有配置新的资源路径 String paraResourcePath = getInitParameter(PARAM_RESOURCE_PATH);
if (!StringUtils.isEmpty(paraResourcePath)) {
quartzweb/quartz-web
src/main/java/com/github/quartzweb/service/strategy/BasicServiceStrategyParameter.java
// Path: src/main/java/com/github/quartzweb/exception/UnsupportedTranslateException.java // public class UnsupportedTranslateException extends RuntimeException { // // public UnsupportedTranslateException() { // } // // public UnsupportedTranslateException(String message) { // super(message); // } // // public UnsupportedTranslateException(String message, Throwable cause) { // super(message, cause); // } // // public UnsupportedTranslateException(Throwable cause) { // super(cause); // } // // }
import com.github.quartzweb.exception.UnsupportedTranslateException;
/** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.service.strategy; /** * @author quxiucheng [[email protected]] */ public class BasicServiceStrategyParameter implements ServiceStrategyParameter { @Override
// Path: src/main/java/com/github/quartzweb/exception/UnsupportedTranslateException.java // public class UnsupportedTranslateException extends RuntimeException { // // public UnsupportedTranslateException() { // } // // public UnsupportedTranslateException(String message) { // super(message); // } // // public UnsupportedTranslateException(String message, Throwable cause) { // super(message, cause); // } // // public UnsupportedTranslateException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/com/github/quartzweb/service/strategy/BasicServiceStrategyParameter.java import com.github.quartzweb.exception.UnsupportedTranslateException; /** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.service.strategy; /** * @author quxiucheng [[email protected]] */ public class BasicServiceStrategyParameter implements ServiceStrategyParameter { @Override
public void translate(Object object) throws UnsupportedTranslateException {
quartzweb/quartz-web
src/main/java/com/github/quartzweb/service/strategy/ValidateServiceStrategyParameter.java
// Path: src/main/java/com/github/quartzweb/exception/UnsupportedTranslateException.java // public class UnsupportedTranslateException extends RuntimeException { // // public UnsupportedTranslateException() { // } // // public UnsupportedTranslateException(String message) { // super(message); // } // // public UnsupportedTranslateException(String message, Throwable cause) { // super(message, cause); // } // // public UnsupportedTranslateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/github/quartzweb/service/HttpParameterNameConstants.java // public abstract class HttpParameterNameConstants { // // /** // * 关于Scheduler // */ // public static class Scheduler { // // /** Scheduler - schedule名称 */ // public static final String NAME = "schedulerName"; // // /** Scheduler - 延时秒数 - 单位(秒) */ // public static final String DELAYED = "delayed"; // // } // // // /** // * 关于Job操作 // */ // public static class Job { // /** Job操作 - job名称 */ // public static final String NAME = "jobName"; // // /** Job操作 - job分组 */ // public static final String GROUP = "jobGroup"; // // /** Job操作 - jobDataMap数据 -key值 */ // public static final String DATA_MAP_KEY_PREFIX = "jobDataMapKey_"; // // /** Job操作 - jobDataMap数据 -value值 */ // public static final String DATA_MAP_VALUE_PREFIX = "jobDataMapValue_"; // // /** Job操作 - JobClass,*/ // public static final String JOB_CLASS = "jobClass"; // // /** Job操作 - Job类型*/ // public static final String JOB_TYPE = "jobType"; // // /** Job操作 - job描述 */ // public static final String DESCRIPTION = "description"; // // /** Job操作 - JobClass参数名称前缀 */ // public static final String JOB_CLASS_PARAM_TYPE_NAME_PREFIX = "jobClassParamType_"; // // /** Job操作 - JobClass参数值前缀 */ // public static final String JOB_CLASS_PARAM_TYPE_VALUE_PREFIX = "jobClassParamTypeValue_"; // // /** Job操作 - 执行方法类型 */ // public static final String METHOD_INVOKER_TYPE = "methodInvokerType"; // // /** Job操作 - 执行方法名称 */ // public static final String JOB_CLASS_METHOD_NAME = "jobClassMethodName"; // /** Job操作 - 执行method类型前缀*/ // public static final String JOB_CLASS_METHOD_PARAM_TYPE_NAME_PREFIX = "jobClassMethodParamType_"; // // /** Job操作 - 执行method参数值前缀 */ // public static final String JOB_CLASS_METHOD_PARAM_TYPE_VALUE_PREFIX = "jobClassMethodParamTypeValue_"; // // } // // // public static class Trigger { // // /** Trigger操作 - trigger名称 */ // public static final String NAME = "triggerName"; // // // /** HTTP参数名称 - Trigger操作 - job分组 */ // public static final String GROUP = "triggerGroup"; // // /** trigger描述 */ // public static final String DESCRIPTION = "description"; // // /** 优先级 */ // public static final String PRIORITY = "priority"; // // /** cron表达式 */ // public static final String CRONEXPRESSION = "cronExpression"; // // /** trigger 开始时间 */ // public static final String START_DATE = "startDate"; // // /** trigger 结束时间 */ // public static final String END_DATE = "endDate"; // // } // // // public static class Validate{ // /** 对比是否为子类的Class名称 */ // public static final String ASSIGNABLE_CLASS_NAME= "assignableClassName"; // // /** Class名称 */ // public static final String CLASS_NAME= "className"; // // /** cron表达式 */ // public static final String CRON_EXPRESSION= "cronExpression"; // } // // // }
import javax.servlet.http.HttpServletRequest; import com.github.quartzweb.exception.UnsupportedTranslateException; import com.github.quartzweb.service.HttpParameterNameConstants;
public void setSchedulerName(String schedulerName) { this.schedulerName = schedulerName; } public String getCronExpression() { return cronExpression; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public String getTriggerName() { return triggerName; } public void setTriggerName(String triggerName) { this.triggerName = triggerName; } public String getTriggerGroup() { return triggerGroup; } public void setTriggerGroup(String triggerGroup) { this.triggerGroup = triggerGroup; } @Override
// Path: src/main/java/com/github/quartzweb/exception/UnsupportedTranslateException.java // public class UnsupportedTranslateException extends RuntimeException { // // public UnsupportedTranslateException() { // } // // public UnsupportedTranslateException(String message) { // super(message); // } // // public UnsupportedTranslateException(String message, Throwable cause) { // super(message, cause); // } // // public UnsupportedTranslateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/github/quartzweb/service/HttpParameterNameConstants.java // public abstract class HttpParameterNameConstants { // // /** // * 关于Scheduler // */ // public static class Scheduler { // // /** Scheduler - schedule名称 */ // public static final String NAME = "schedulerName"; // // /** Scheduler - 延时秒数 - 单位(秒) */ // public static final String DELAYED = "delayed"; // // } // // // /** // * 关于Job操作 // */ // public static class Job { // /** Job操作 - job名称 */ // public static final String NAME = "jobName"; // // /** Job操作 - job分组 */ // public static final String GROUP = "jobGroup"; // // /** Job操作 - jobDataMap数据 -key值 */ // public static final String DATA_MAP_KEY_PREFIX = "jobDataMapKey_"; // // /** Job操作 - jobDataMap数据 -value值 */ // public static final String DATA_MAP_VALUE_PREFIX = "jobDataMapValue_"; // // /** Job操作 - JobClass,*/ // public static final String JOB_CLASS = "jobClass"; // // /** Job操作 - Job类型*/ // public static final String JOB_TYPE = "jobType"; // // /** Job操作 - job描述 */ // public static final String DESCRIPTION = "description"; // // /** Job操作 - JobClass参数名称前缀 */ // public static final String JOB_CLASS_PARAM_TYPE_NAME_PREFIX = "jobClassParamType_"; // // /** Job操作 - JobClass参数值前缀 */ // public static final String JOB_CLASS_PARAM_TYPE_VALUE_PREFIX = "jobClassParamTypeValue_"; // // /** Job操作 - 执行方法类型 */ // public static final String METHOD_INVOKER_TYPE = "methodInvokerType"; // // /** Job操作 - 执行方法名称 */ // public static final String JOB_CLASS_METHOD_NAME = "jobClassMethodName"; // /** Job操作 - 执行method类型前缀*/ // public static final String JOB_CLASS_METHOD_PARAM_TYPE_NAME_PREFIX = "jobClassMethodParamType_"; // // /** Job操作 - 执行method参数值前缀 */ // public static final String JOB_CLASS_METHOD_PARAM_TYPE_VALUE_PREFIX = "jobClassMethodParamTypeValue_"; // // } // // // public static class Trigger { // // /** Trigger操作 - trigger名称 */ // public static final String NAME = "triggerName"; // // // /** HTTP参数名称 - Trigger操作 - job分组 */ // public static final String GROUP = "triggerGroup"; // // /** trigger描述 */ // public static final String DESCRIPTION = "description"; // // /** 优先级 */ // public static final String PRIORITY = "priority"; // // /** cron表达式 */ // public static final String CRONEXPRESSION = "cronExpression"; // // /** trigger 开始时间 */ // public static final String START_DATE = "startDate"; // // /** trigger 结束时间 */ // public static final String END_DATE = "endDate"; // // } // // // public static class Validate{ // /** 对比是否为子类的Class名称 */ // public static final String ASSIGNABLE_CLASS_NAME= "assignableClassName"; // // /** Class名称 */ // public static final String CLASS_NAME= "className"; // // /** cron表达式 */ // public static final String CRON_EXPRESSION= "cronExpression"; // } // // // } // Path: src/main/java/com/github/quartzweb/service/strategy/ValidateServiceStrategyParameter.java import javax.servlet.http.HttpServletRequest; import com.github.quartzweb.exception.UnsupportedTranslateException; import com.github.quartzweb.service.HttpParameterNameConstants; public void setSchedulerName(String schedulerName) { this.schedulerName = schedulerName; } public String getCronExpression() { return cronExpression; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public String getTriggerName() { return triggerName; } public void setTriggerName(String triggerName) { this.triggerName = triggerName; } public String getTriggerGroup() { return triggerGroup; } public void setTriggerGroup(String triggerGroup) { this.triggerGroup = triggerGroup; } @Override
public void translate(Object object) throws UnsupportedTranslateException {
quartzweb/quartz-web
src/main/java/com/github/quartzweb/service/strategy/ValidateServiceStrategyParameter.java
// Path: src/main/java/com/github/quartzweb/exception/UnsupportedTranslateException.java // public class UnsupportedTranslateException extends RuntimeException { // // public UnsupportedTranslateException() { // } // // public UnsupportedTranslateException(String message) { // super(message); // } // // public UnsupportedTranslateException(String message, Throwable cause) { // super(message, cause); // } // // public UnsupportedTranslateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/github/quartzweb/service/HttpParameterNameConstants.java // public abstract class HttpParameterNameConstants { // // /** // * 关于Scheduler // */ // public static class Scheduler { // // /** Scheduler - schedule名称 */ // public static final String NAME = "schedulerName"; // // /** Scheduler - 延时秒数 - 单位(秒) */ // public static final String DELAYED = "delayed"; // // } // // // /** // * 关于Job操作 // */ // public static class Job { // /** Job操作 - job名称 */ // public static final String NAME = "jobName"; // // /** Job操作 - job分组 */ // public static final String GROUP = "jobGroup"; // // /** Job操作 - jobDataMap数据 -key值 */ // public static final String DATA_MAP_KEY_PREFIX = "jobDataMapKey_"; // // /** Job操作 - jobDataMap数据 -value值 */ // public static final String DATA_MAP_VALUE_PREFIX = "jobDataMapValue_"; // // /** Job操作 - JobClass,*/ // public static final String JOB_CLASS = "jobClass"; // // /** Job操作 - Job类型*/ // public static final String JOB_TYPE = "jobType"; // // /** Job操作 - job描述 */ // public static final String DESCRIPTION = "description"; // // /** Job操作 - JobClass参数名称前缀 */ // public static final String JOB_CLASS_PARAM_TYPE_NAME_PREFIX = "jobClassParamType_"; // // /** Job操作 - JobClass参数值前缀 */ // public static final String JOB_CLASS_PARAM_TYPE_VALUE_PREFIX = "jobClassParamTypeValue_"; // // /** Job操作 - 执行方法类型 */ // public static final String METHOD_INVOKER_TYPE = "methodInvokerType"; // // /** Job操作 - 执行方法名称 */ // public static final String JOB_CLASS_METHOD_NAME = "jobClassMethodName"; // /** Job操作 - 执行method类型前缀*/ // public static final String JOB_CLASS_METHOD_PARAM_TYPE_NAME_PREFIX = "jobClassMethodParamType_"; // // /** Job操作 - 执行method参数值前缀 */ // public static final String JOB_CLASS_METHOD_PARAM_TYPE_VALUE_PREFIX = "jobClassMethodParamTypeValue_"; // // } // // // public static class Trigger { // // /** Trigger操作 - trigger名称 */ // public static final String NAME = "triggerName"; // // // /** HTTP参数名称 - Trigger操作 - job分组 */ // public static final String GROUP = "triggerGroup"; // // /** trigger描述 */ // public static final String DESCRIPTION = "description"; // // /** 优先级 */ // public static final String PRIORITY = "priority"; // // /** cron表达式 */ // public static final String CRONEXPRESSION = "cronExpression"; // // /** trigger 开始时间 */ // public static final String START_DATE = "startDate"; // // /** trigger 结束时间 */ // public static final String END_DATE = "endDate"; // // } // // // public static class Validate{ // /** 对比是否为子类的Class名称 */ // public static final String ASSIGNABLE_CLASS_NAME= "assignableClassName"; // // /** Class名称 */ // public static final String CLASS_NAME= "className"; // // /** cron表达式 */ // public static final String CRON_EXPRESSION= "cronExpression"; // } // // // }
import javax.servlet.http.HttpServletRequest; import com.github.quartzweb.exception.UnsupportedTranslateException; import com.github.quartzweb.service.HttpParameterNameConstants;
public String getCronExpression() { return cronExpression; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public String getTriggerName() { return triggerName; } public void setTriggerName(String triggerName) { this.triggerName = triggerName; } public String getTriggerGroup() { return triggerGroup; } public void setTriggerGroup(String triggerGroup) { this.triggerGroup = triggerGroup; } @Override public void translate(Object object) throws UnsupportedTranslateException { if (object instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) object;
// Path: src/main/java/com/github/quartzweb/exception/UnsupportedTranslateException.java // public class UnsupportedTranslateException extends RuntimeException { // // public UnsupportedTranslateException() { // } // // public UnsupportedTranslateException(String message) { // super(message); // } // // public UnsupportedTranslateException(String message, Throwable cause) { // super(message, cause); // } // // public UnsupportedTranslateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/github/quartzweb/service/HttpParameterNameConstants.java // public abstract class HttpParameterNameConstants { // // /** // * 关于Scheduler // */ // public static class Scheduler { // // /** Scheduler - schedule名称 */ // public static final String NAME = "schedulerName"; // // /** Scheduler - 延时秒数 - 单位(秒) */ // public static final String DELAYED = "delayed"; // // } // // // /** // * 关于Job操作 // */ // public static class Job { // /** Job操作 - job名称 */ // public static final String NAME = "jobName"; // // /** Job操作 - job分组 */ // public static final String GROUP = "jobGroup"; // // /** Job操作 - jobDataMap数据 -key值 */ // public static final String DATA_MAP_KEY_PREFIX = "jobDataMapKey_"; // // /** Job操作 - jobDataMap数据 -value值 */ // public static final String DATA_MAP_VALUE_PREFIX = "jobDataMapValue_"; // // /** Job操作 - JobClass,*/ // public static final String JOB_CLASS = "jobClass"; // // /** Job操作 - Job类型*/ // public static final String JOB_TYPE = "jobType"; // // /** Job操作 - job描述 */ // public static final String DESCRIPTION = "description"; // // /** Job操作 - JobClass参数名称前缀 */ // public static final String JOB_CLASS_PARAM_TYPE_NAME_PREFIX = "jobClassParamType_"; // // /** Job操作 - JobClass参数值前缀 */ // public static final String JOB_CLASS_PARAM_TYPE_VALUE_PREFIX = "jobClassParamTypeValue_"; // // /** Job操作 - 执行方法类型 */ // public static final String METHOD_INVOKER_TYPE = "methodInvokerType"; // // /** Job操作 - 执行方法名称 */ // public static final String JOB_CLASS_METHOD_NAME = "jobClassMethodName"; // /** Job操作 - 执行method类型前缀*/ // public static final String JOB_CLASS_METHOD_PARAM_TYPE_NAME_PREFIX = "jobClassMethodParamType_"; // // /** Job操作 - 执行method参数值前缀 */ // public static final String JOB_CLASS_METHOD_PARAM_TYPE_VALUE_PREFIX = "jobClassMethodParamTypeValue_"; // // } // // // public static class Trigger { // // /** Trigger操作 - trigger名称 */ // public static final String NAME = "triggerName"; // // // /** HTTP参数名称 - Trigger操作 - job分组 */ // public static final String GROUP = "triggerGroup"; // // /** trigger描述 */ // public static final String DESCRIPTION = "description"; // // /** 优先级 */ // public static final String PRIORITY = "priority"; // // /** cron表达式 */ // public static final String CRONEXPRESSION = "cronExpression"; // // /** trigger 开始时间 */ // public static final String START_DATE = "startDate"; // // /** trigger 结束时间 */ // public static final String END_DATE = "endDate"; // // } // // // public static class Validate{ // /** 对比是否为子类的Class名称 */ // public static final String ASSIGNABLE_CLASS_NAME= "assignableClassName"; // // /** Class名称 */ // public static final String CLASS_NAME= "className"; // // /** cron表达式 */ // public static final String CRON_EXPRESSION= "cronExpression"; // } // // // } // Path: src/main/java/com/github/quartzweb/service/strategy/ValidateServiceStrategyParameter.java import javax.servlet.http.HttpServletRequest; import com.github.quartzweb.exception.UnsupportedTranslateException; import com.github.quartzweb.service.HttpParameterNameConstants; public String getCronExpression() { return cronExpression; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public String getTriggerName() { return triggerName; } public void setTriggerName(String triggerName) { this.triggerName = triggerName; } public String getTriggerGroup() { return triggerGroup; } public void setTriggerGroup(String triggerGroup) { this.triggerGroup = triggerGroup; } @Override public void translate(Object object) throws UnsupportedTranslateException { if (object instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) object;
this.setClassName(request.getParameter(HttpParameterNameConstants.Validate.CLASS_NAME));
quartzweb/quartz-web
src/main/java/com/github/quartzweb/service/QuartzWebURL.java
// Path: src/main/java/com/github/quartzweb/service/strategy/ServiceStrategyURL.java // public interface ServiceStrategyURL { // // /** // * 获取URL // * @return // */ // public String getURL(); // // } // // Path: src/main/java/com/github/quartzweb/utils/StringUtils.java // public class StringUtils { // // /** // * 判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equals(String a, String b) { // if (a == null) { // return b == null; // } // return a.equals(b); // } // // /** // * 忽略大小写判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equalsIgnoreCase(String a, String b) { // if (a == null) { // return b == null; // } // return a.equalsIgnoreCase(b); // } // // /** // * 判断字符串是否为空(NULL或空串"") // * @param value 字符串 // * @return true为空,false不为空 // */ // public static boolean isEmpty(CharSequence value) { // if (value == null || value.length() == 0) { // return true; // } // return false; // } // // /** // * 是否为整数 // * @param str // * @return // */ // public static boolean isInteger(String str) { // Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); // return pattern.matcher(str).matches(); // } // // /** // * 判断是否为大于某个数字的整数 // * @param str // * @param integer // * @return // */ // public static boolean isIntegerGTNumber(String str,Integer integer) { // // 是整数 // if (isInteger(str)) { // int source = Integer.parseInt(str); // return source > integer; // } else { // return false; // } // } // }
import com.github.quartzweb.service.strategy.ServiceStrategyURL; import com.github.quartzweb.utils.StringUtils;
/** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.service; /** * @author quxiucheng [[email protected]] */ public class QuartzWebURL { public enum BasicURL implements ServiceStrategyURL { BASIC("/api/basic.json"); private String url; BasicURL(String url) { this.url = url; } public String getURL() { return url; } public static boolean lookup(String url) {
// Path: src/main/java/com/github/quartzweb/service/strategy/ServiceStrategyURL.java // public interface ServiceStrategyURL { // // /** // * 获取URL // * @return // */ // public String getURL(); // // } // // Path: src/main/java/com/github/quartzweb/utils/StringUtils.java // public class StringUtils { // // /** // * 判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equals(String a, String b) { // if (a == null) { // return b == null; // } // return a.equals(b); // } // // /** // * 忽略大小写判断两个字符串是否相等 // * @param a 字符 // * @param b 字符 // * @return true相等,false不相等 // */ // public static boolean equalsIgnoreCase(String a, String b) { // if (a == null) { // return b == null; // } // return a.equalsIgnoreCase(b); // } // // /** // * 判断字符串是否为空(NULL或空串"") // * @param value 字符串 // * @return true为空,false不为空 // */ // public static boolean isEmpty(CharSequence value) { // if (value == null || value.length() == 0) { // return true; // } // return false; // } // // /** // * 是否为整数 // * @param str // * @return // */ // public static boolean isInteger(String str) { // Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); // return pattern.matcher(str).matches(); // } // // /** // * 判断是否为大于某个数字的整数 // * @param str // * @param integer // * @return // */ // public static boolean isIntegerGTNumber(String str,Integer integer) { // // 是整数 // if (isInteger(str)) { // int source = Integer.parseInt(str); // return source > integer; // } else { // return false; // } // } // } // Path: src/main/java/com/github/quartzweb/service/QuartzWebURL.java import com.github.quartzweb.service.strategy.ServiceStrategyURL; import com.github.quartzweb.utils.StringUtils; /** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.service; /** * @author quxiucheng [[email protected]] */ public class QuartzWebURL { public enum BasicURL implements ServiceStrategyURL { BASIC("/api/basic.json"); private String url; BasicURL(String url) { this.url = url; } public String getURL() { return url; } public static boolean lookup(String url) {
if(StringUtils.isEmpty(url)){
emboss/krypt-core-java
src/org/jruby/ext/krypt/provider/RubyNativeProvider.java
// Path: src/org/jruby/ext/krypt/digest/RubyNativeDigest.java // public class RubyNativeDigest extends RubyObject { // // private static RubyClass cNativeDigest; // // public RubyNativeDigest(Ruby runtime, Digest digest) { // super(runtime, cNativeDigest); // this.digest = digest; // } // // private Digest digest; // // @JRubyMethod // public IRubyObject reset(ThreadContext ctx) { // this.digest.reset(); // return this; // } // // @JRubyMethod(name={"update","<<"}) // public IRubyObject update(ThreadContext ctx, IRubyObject data) { // try { // byte[] bytes = data.asString().getBytes(); // this.digest.update(bytes, 0, bytes.length); // return this; // } catch (Exception ex) { // throw Errors.newDigestError(ctx.getRuntime(), "Error while updating digest: " + ex.getMessage()); // } // } // // @JRubyMethod(optional=1) // public IRubyObject digest(ThreadContext ctx, IRubyObject[] args) { // Ruby runtime = ctx.getRuntime(); // if (args.length == 0) // return digestFinalize(runtime); // else // return digestData(runtime, args[0]); // } // // @JRubyMethod(optional=1) // public IRubyObject hexdigest(ThreadContext ctx, IRubyObject[] args) { // IRubyObject result = digest(ctx, args); // byte[] encoded = Hex.encode(result.asString().getBytes()); // return RubyString.newUsAsciiStringNoCopy(ctx.getRuntime(), new ByteList(encoded, false)); // } // // @JRubyMethod // public IRubyObject name(ThreadContext ctx) { // return ctx.getRuntime().newString(this.digest.getName()); // } // // @JRubyMethod // public IRubyObject digest_length(ThreadContext ctx) { // return RubyNumeric.int2fix(ctx.getRuntime(), this.digest.getDigestLength()); // } // // @JRubyMethod // public IRubyObject block_length(ThreadContext ctx) { // return RubyNumeric.int2fix(ctx.getRuntime(), this.digest.getBlockLength()); // } // // private IRubyObject digestFinalize(Ruby runtime) { // try { // byte[] result = digest.digest(); // return runtime.newString(new ByteList(result, false)); // } catch (Exception ex) { // throw Errors.newDigestError(runtime, "Error while finalizing digest: " + ex.getMessage()); // } // } // // private IRubyObject digestData(Ruby runtime, IRubyObject rbdata) { // try { // byte[] data = rbdata.asString().getBytes(); // byte[] result = digest.digest(data); // return runtime.newString(new ByteList(result, false)); // } catch (Exception ex) { // throw Errors.newDigestError(runtime, "Error while computing digest: " + ex.getMessage()); // } // } // // public static void createDigest(Ruby runtime, RubyModule krypt) { // RubyModule mDigest = (RubyModule)krypt.getConstant("Digest"); // cNativeDigest = mDigest.defineClassUnder("NativeDigest", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR); // cNativeDigest.defineAnnotatedMethods(RubyNativeDigest.class); // } // }
import org.jruby.RubyObject; import org.jruby.anno.JRubyMethod; import org.jruby.ext.krypt.digest.RubyNativeDigest; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.RubyModule;
} @JRubyMethod(required = 1, rest = true) public IRubyObject new_service(ThreadContext ctx, IRubyObject[] args) { IRubyObject serviceClass = args[0]; if (serviceClass == mDigest) { return newDigest(ctx, stripFirst(args)); } return ctx.getRuntime().getNil(); } @JRubyMethod public IRubyObject finalize(ThreadContext ctx) { /* do nothing */ provider.cleanUp(); return ctx.getRuntime().getNil(); } private IRubyObject newDigest(ThreadContext ctx, IRubyObject[] args) { Ruby runtime = ctx.getRuntime(); if (args == null) return runtime.getNil(); String nameOrOid = args[0].convertToString().asJavaString(); Digest digest = provider.newDigestByName(nameOrOid); if (digest == null) digest = provider.newDigestByOid(nameOrOid); if (digest == null) return runtime.getNil(); else
// Path: src/org/jruby/ext/krypt/digest/RubyNativeDigest.java // public class RubyNativeDigest extends RubyObject { // // private static RubyClass cNativeDigest; // // public RubyNativeDigest(Ruby runtime, Digest digest) { // super(runtime, cNativeDigest); // this.digest = digest; // } // // private Digest digest; // // @JRubyMethod // public IRubyObject reset(ThreadContext ctx) { // this.digest.reset(); // return this; // } // // @JRubyMethod(name={"update","<<"}) // public IRubyObject update(ThreadContext ctx, IRubyObject data) { // try { // byte[] bytes = data.asString().getBytes(); // this.digest.update(bytes, 0, bytes.length); // return this; // } catch (Exception ex) { // throw Errors.newDigestError(ctx.getRuntime(), "Error while updating digest: " + ex.getMessage()); // } // } // // @JRubyMethod(optional=1) // public IRubyObject digest(ThreadContext ctx, IRubyObject[] args) { // Ruby runtime = ctx.getRuntime(); // if (args.length == 0) // return digestFinalize(runtime); // else // return digestData(runtime, args[0]); // } // // @JRubyMethod(optional=1) // public IRubyObject hexdigest(ThreadContext ctx, IRubyObject[] args) { // IRubyObject result = digest(ctx, args); // byte[] encoded = Hex.encode(result.asString().getBytes()); // return RubyString.newUsAsciiStringNoCopy(ctx.getRuntime(), new ByteList(encoded, false)); // } // // @JRubyMethod // public IRubyObject name(ThreadContext ctx) { // return ctx.getRuntime().newString(this.digest.getName()); // } // // @JRubyMethod // public IRubyObject digest_length(ThreadContext ctx) { // return RubyNumeric.int2fix(ctx.getRuntime(), this.digest.getDigestLength()); // } // // @JRubyMethod // public IRubyObject block_length(ThreadContext ctx) { // return RubyNumeric.int2fix(ctx.getRuntime(), this.digest.getBlockLength()); // } // // private IRubyObject digestFinalize(Ruby runtime) { // try { // byte[] result = digest.digest(); // return runtime.newString(new ByteList(result, false)); // } catch (Exception ex) { // throw Errors.newDigestError(runtime, "Error while finalizing digest: " + ex.getMessage()); // } // } // // private IRubyObject digestData(Ruby runtime, IRubyObject rbdata) { // try { // byte[] data = rbdata.asString().getBytes(); // byte[] result = digest.digest(data); // return runtime.newString(new ByteList(result, false)); // } catch (Exception ex) { // throw Errors.newDigestError(runtime, "Error while computing digest: " + ex.getMessage()); // } // } // // public static void createDigest(Ruby runtime, RubyModule krypt) { // RubyModule mDigest = (RubyModule)krypt.getConstant("Digest"); // cNativeDigest = mDigest.defineClassUnder("NativeDigest", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR); // cNativeDigest.defineAnnotatedMethods(RubyNativeDigest.class); // } // } // Path: src/org/jruby/ext/krypt/provider/RubyNativeProvider.java import org.jruby.RubyObject; import org.jruby.anno.JRubyMethod; import org.jruby.ext.krypt.digest.RubyNativeDigest; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.RubyModule; } @JRubyMethod(required = 1, rest = true) public IRubyObject new_service(ThreadContext ctx, IRubyObject[] args) { IRubyObject serviceClass = args[0]; if (serviceClass == mDigest) { return newDigest(ctx, stripFirst(args)); } return ctx.getRuntime().getNil(); } @JRubyMethod public IRubyObject finalize(ThreadContext ctx) { /* do nothing */ provider.cleanUp(); return ctx.getRuntime().getNil(); } private IRubyObject newDigest(ThreadContext ctx, IRubyObject[] args) { Ruby runtime = ctx.getRuntime(); if (args == null) return runtime.getNil(); String nameOrOid = args[0].convertToString().asJavaString(); Digest digest = provider.newDigestByName(nameOrOid); if (digest == null) digest = provider.newDigestByOid(nameOrOid); if (digest == null) return runtime.getNil(); else
return new RubyNativeDigest(runtime, digest);
emboss/krypt-core-java
src/KryptcoreService.java
// Path: src/org/jruby/ext/krypt/KryptCoreService.java // public class KryptCoreService { // // public static void create(Ruby runtime) { // RubyModule krypt = runtime.getOrCreateModule("Krypt"); // RubyClass kryptError = krypt.getClass("Error"); // // RubyHelper.createHelper(runtime, krypt); // // RubyAsn1.createAsn1(runtime, krypt, kryptError); // RubyPem.createPem(runtime, krypt, kryptError); // RubyHex.createHex(runtime, krypt, kryptError); // RubyBase64.createBase64(runtime, krypt, kryptError); // // RubyNativeDigest.createDigest(runtime, krypt); // RubyNativeProvider.createProvider(runtime, krypt); // } // }
import java.io.IOException; import org.jruby.Ruby; import org.jruby.ext.krypt.KryptCoreService; import org.jruby.runtime.load.BasicLibraryService;
/* * krypt-core API - Java version * * Copyright (c) 2011-2013 * Hiroshi Nakamura <[email protected]> * Martin Bosslet <[email protected]> * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * * @author <a href="mailto:[email protected]">Martin Bosslet</a> */ public class KryptcoreService implements BasicLibraryService { @Override public boolean basicLoad(Ruby runtime) throws IOException {
// Path: src/org/jruby/ext/krypt/KryptCoreService.java // public class KryptCoreService { // // public static void create(Ruby runtime) { // RubyModule krypt = runtime.getOrCreateModule("Krypt"); // RubyClass kryptError = krypt.getClass("Error"); // // RubyHelper.createHelper(runtime, krypt); // // RubyAsn1.createAsn1(runtime, krypt, kryptError); // RubyPem.createPem(runtime, krypt, kryptError); // RubyHex.createHex(runtime, krypt, kryptError); // RubyBase64.createBase64(runtime, krypt, kryptError); // // RubyNativeDigest.createDigest(runtime, krypt); // RubyNativeProvider.createProvider(runtime, krypt); // } // } // Path: src/KryptcoreService.java import java.io.IOException; import org.jruby.Ruby; import org.jruby.ext.krypt.KryptCoreService; import org.jruby.runtime.load.BasicLibraryService; /* * krypt-core API - Java version * * Copyright (c) 2011-2013 * Hiroshi Nakamura <[email protected]> * Martin Bosslet <[email protected]> * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * * @author <a href="mailto:[email protected]">Martin Bosslet</a> */ public class KryptcoreService implements BasicLibraryService { @Override public boolean basicLoad(Ruby runtime) throws IOException {
KryptCoreService.create(runtime);
emboss/krypt-core-java
src/impl/krypt/asn1/parser/DefiniteInputStream.java
// Path: src/impl/krypt/asn1/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException(Throwable cause) { // super(cause); // } // // public ParseException(String message, Throwable cause) { // super(message, cause); // } // // public ParseException(String message) { // super(message); // } // // public ParseException() { // } // // }
import java.io.InputStream; import impl.krypt.asn1.ParseException; import java.io.FilterInputStream; import java.io.IOException;
@Override public int read() throws IOException { if (read == length) return -1; int b = super.read(); read++; return b; } @Override public void close() throws IOException { //do nothing } @Override public int read(byte[] b, int off, int len) throws IOException { if (read == length) return -1; int toRead, actuallyRead; if (length - read < len) toRead = length - read; else toRead = len; actuallyRead = super.read(b, off, toRead); if (actuallyRead == -1)
// Path: src/impl/krypt/asn1/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException(Throwable cause) { // super(cause); // } // // public ParseException(String message, Throwable cause) { // super(message, cause); // } // // public ParseException(String message) { // super(message); // } // // public ParseException() { // } // // } // Path: src/impl/krypt/asn1/parser/DefiniteInputStream.java import java.io.InputStream; import impl.krypt.asn1.ParseException; import java.io.FilterInputStream; import java.io.IOException; @Override public int read() throws IOException { if (read == length) return -1; int b = super.read(); read++; return b; } @Override public void close() throws IOException { //do nothing } @Override public int read(byte[] b, int off, int len) throws IOException { if (read == length) return -1; int toRead, actuallyRead; if (length - read < len) toRead = length - read; else toRead = len; actuallyRead = super.read(b, off, toRead); if (actuallyRead == -1)
throw new ParseException("Premature end of value detected.");
emboss/krypt-core-java
src/org/jruby/ext/krypt/helper/RubyHelper.java
// Path: src/org/jruby/ext/krypt/Errors.java // public class Errors { // // private Errors() { } // // public static RaiseException newKryptError(Ruby rt, String message) { // return newError(rt, "Krypt::Error", message); // } // // public static RaiseException newParseError(Ruby rt, String message) { // return newError(rt, "Krypt::ASN1::ParseError", message); // } // // public static RaiseException newSerializeError(Ruby rt, String message) { // return newError(rt, "Krypt::ASN1::SerializeError", message); // } // // public static RaiseException newASN1Error(Ruby rt, String message) { // return newError(rt, "Krypt::ASN1::ASN1Error", message); // } // // public static RaiseException newPEMError(Ruby rt, String message) { // return newError(rt, "Krypt::PEM::PEMError", message); // } // // public static RaiseException newHexError(Ruby rt, String message) { // return newError(rt, "Krypt::Hex::HexError", message); // } // // public static RaiseException newBase64Error(Ruby rt, String message) { // return newError(rt, "Krypt::Base64::Base64Error", message); // } // // public static RaiseException newDigestError(Ruby rt, String message) { // return newError(rt, "Krypt::Digest::DigestError", message); // } // // public static RaiseException newError(Ruby rt, String path, String message) { // return new RaiseException(rt, getClassFromPath(rt, path), message, true); // } // // public static RubyClass getClassFromPath(Ruby rt, String path) { // return (RubyClass)rt.getClassFromPath(path); // } // }
import org.jruby.Ruby; import org.jruby.RubyModule; import org.jruby.RubyNumeric; import org.jruby.anno.JRubyMethod; import org.jruby.ext.krypt.Errors; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * krypt-core API - Java version * * Copyright (c) 2011-2013 * Hiroshi Nakamura <[email protected]> * Martin Bosslet <[email protected]> * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.jruby.ext.krypt.helper; /** * * @author <a href="mailto:[email protected]">Martin Bosslet</a> */ public class RubyHelper { private RubyHelper() {} public static class RubyString { @JRubyMethod(meta = true) public static IRubyObject buffer(ThreadContext ctx, IRubyObject recv, IRubyObject size) { return ctx.getRuntime().newString(new ByteList(new byte[RubyNumeric.num2int(size)], false)); } @JRubyMethod(meta = true) public static IRubyObject xor(ThreadContext ctx, IRubyObject recv, IRubyObject s1, IRubyObject s2) { ByteList tmp1 = s1.asString().getByteList(); ByteList tmp2 = s2.asString().getByteList(); byte[] src1 = tmp1.getUnsafeBytes(); byte[] src2 = tmp2.getUnsafeBytes(); int begin1 = tmp1.getBegin(); int end1 = tmp1.getRealSize(); int begin2 = tmp2.getBegin(); int end2 = tmp2.getRealSize(); int len = end1 - begin1; if ((end2 - begin2) != len)
// Path: src/org/jruby/ext/krypt/Errors.java // public class Errors { // // private Errors() { } // // public static RaiseException newKryptError(Ruby rt, String message) { // return newError(rt, "Krypt::Error", message); // } // // public static RaiseException newParseError(Ruby rt, String message) { // return newError(rt, "Krypt::ASN1::ParseError", message); // } // // public static RaiseException newSerializeError(Ruby rt, String message) { // return newError(rt, "Krypt::ASN1::SerializeError", message); // } // // public static RaiseException newASN1Error(Ruby rt, String message) { // return newError(rt, "Krypt::ASN1::ASN1Error", message); // } // // public static RaiseException newPEMError(Ruby rt, String message) { // return newError(rt, "Krypt::PEM::PEMError", message); // } // // public static RaiseException newHexError(Ruby rt, String message) { // return newError(rt, "Krypt::Hex::HexError", message); // } // // public static RaiseException newBase64Error(Ruby rt, String message) { // return newError(rt, "Krypt::Base64::Base64Error", message); // } // // public static RaiseException newDigestError(Ruby rt, String message) { // return newError(rt, "Krypt::Digest::DigestError", message); // } // // public static RaiseException newError(Ruby rt, String path, String message) { // return new RaiseException(rt, getClassFromPath(rt, path), message, true); // } // // public static RubyClass getClassFromPath(Ruby rt, String path) { // return (RubyClass)rt.getClassFromPath(path); // } // } // Path: src/org/jruby/ext/krypt/helper/RubyHelper.java import org.jruby.Ruby; import org.jruby.RubyModule; import org.jruby.RubyNumeric; import org.jruby.anno.JRubyMethod; import org.jruby.ext.krypt.Errors; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * krypt-core API - Java version * * Copyright (c) 2011-2013 * Hiroshi Nakamura <[email protected]> * Martin Bosslet <[email protected]> * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.jruby.ext.krypt.helper; /** * * @author <a href="mailto:[email protected]">Martin Bosslet</a> */ public class RubyHelper { private RubyHelper() {} public static class RubyString { @JRubyMethod(meta = true) public static IRubyObject buffer(ThreadContext ctx, IRubyObject recv, IRubyObject size) { return ctx.getRuntime().newString(new ByteList(new byte[RubyNumeric.num2int(size)], false)); } @JRubyMethod(meta = true) public static IRubyObject xor(ThreadContext ctx, IRubyObject recv, IRubyObject s1, IRubyObject s2) { ByteList tmp1 = s1.asString().getByteList(); ByteList tmp2 = s2.asString().getByteList(); byte[] src1 = tmp1.getUnsafeBytes(); byte[] src2 = tmp2.getUnsafeBytes(); int begin1 = tmp1.getBegin(); int end1 = tmp1.getRealSize(); int begin2 = tmp2.getBegin(); int end2 = tmp2.getRealSize(); int len = end1 - begin1; if ((end2 - begin2) != len)
throw Errors.newKryptError(ctx.getRuntime(), "String sizes don't match");
emboss/krypt-core-java
src/impl/krypt/asn1/ParserFactory.java
// Path: src/impl/krypt/asn1/parser/PullHeaderParser.java // public class PullHeaderParser implements Parser { // // private static final int MAX_TAG = Integer.MAX_VALUE >> 7; // private static final int MAX_LENGTH = Integer.MAX_VALUE >> 8; // // public PullHeaderParser() { } // // @Override // public ParsedHeader next(InputStream in) { // if (in == null) throw new NullPointerException(); // // int read = nextInt(in); // if (read == -1) // return null; // byte b = (byte)read; // Tag tag = parseTag(b, in); // Length length = parseLength(in); // // if (length.isInfiniteLength() && !tag.isConstructed()) // throw new ParseException("Infinite length values must be constructed"); // // return new ParsedHeaderImpl(tag, length, in, this); // } // // private byte nextByte(InputStream in) { // int read = nextInt(in); // if (read == -1) // throw new ParseException("EOF reached."); // return (byte)read; // } // // private int nextInt(InputStream in) { // try { // return in.read(); // } // catch (IOException ex) { // throw new ParseException(ex); // } // } // // private static boolean matchMask(byte test, byte mask) { // return ((byte)(test & mask)) == mask; // } // // private Tag parseTag(byte b, InputStream in) { // if (matchMask(b, Header.COMPLEX_TAG_MASK)) // return parseComplexTag(b, in); // else // return parsePrimitiveTag(b); // } // // private Tag parsePrimitiveTag(byte b) { // int tag = b & Header.COMPLEX_TAG_MASK; // boolean isConstructed = matchMask(b, Header.CONSTRUCTED_MASK); // TagClass tc = TagClass.of((byte)(b & TagClass.PRIVATE.getMask())); // return new Tag(tag, tc, isConstructed, new byte[] { b }); // } // // private Tag parseComplexTag(byte b, InputStream in) { // boolean isConstructed = matchMask(b, Header.CONSTRUCTED_MASK); // TagClass tc = TagClass.of((byte)(b & TagClass.PRIVATE.getMask())); // int tag = 0; // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // baos.write(b & 0xff); // b = nextByte(in); // if (b == Header.INFINITE_LENGTH_MASK) // throw new ParseException("Bits 7 to 1 of the first subsequent octet shall not be 0 for complex tag encodings"); // // while (matchMask(b, Header.INFINITE_LENGTH_MASK)) { // if (tag > (MAX_TAG)) // throw new ParseException("Complex tag too long."); // tag <<= 7; // tag |= (b & 0x7f); // baos.write(b & 0xff); // b = nextByte(in); // } // // //final byte // tag <<= 7; // tag |= (b & 0x7f); // baos.write(b & 0xff); // // return new Tag(tag, tc, isConstructed, baos.toByteArray()); // } // // private Length parseLength(InputStream in) { // byte b = nextByte(in); // // if (b == Header.INFINITE_LENGTH_MASK) // return new Length(0, true, new byte[] { b }); // else if (matchMask(b, Header.INFINITE_LENGTH_MASK)) // return parseComplexDefiniteLength(b, in); // else // return new Length(b & 0xff, false, new byte[] { b }); // } // // private Length parseComplexDefiniteLength(byte b, InputStream in) { // int len = 0; // int numOctets = b & 0x7f; // int off = 0; // // if ((b & 0xff) == 0xff) // throw new ParseException("Initial octet of complex definite length shall not be 0xFF"); // // // byte[] encoding = new byte[numOctets+1]; // encoding[off++] = b; // // for (int i=numOctets; i > 0; i--) { // if (numOctets > MAX_LENGTH) // throw new ParseException("Definite value length too long."); // b = nextByte(in); // len <<= 8; // len |= (b & 0xff); // encoding[off++] = b; // } // // return new Length(len, false, encoding); // } // }
import impl.krypt.asn1.parser.PullHeaderParser;
/* * krypt-core API - Java version * * Copyright (c) 2011-2013 * Hiroshi Nakamura <[email protected]> * Martin Bosslet <[email protected]> * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package impl.krypt.asn1; /** * * @author <a href="mailto:[email protected]">Martin Bosslet</a> */ public class ParserFactory { public Parser newHeaderParser() {
// Path: src/impl/krypt/asn1/parser/PullHeaderParser.java // public class PullHeaderParser implements Parser { // // private static final int MAX_TAG = Integer.MAX_VALUE >> 7; // private static final int MAX_LENGTH = Integer.MAX_VALUE >> 8; // // public PullHeaderParser() { } // // @Override // public ParsedHeader next(InputStream in) { // if (in == null) throw new NullPointerException(); // // int read = nextInt(in); // if (read == -1) // return null; // byte b = (byte)read; // Tag tag = parseTag(b, in); // Length length = parseLength(in); // // if (length.isInfiniteLength() && !tag.isConstructed()) // throw new ParseException("Infinite length values must be constructed"); // // return new ParsedHeaderImpl(tag, length, in, this); // } // // private byte nextByte(InputStream in) { // int read = nextInt(in); // if (read == -1) // throw new ParseException("EOF reached."); // return (byte)read; // } // // private int nextInt(InputStream in) { // try { // return in.read(); // } // catch (IOException ex) { // throw new ParseException(ex); // } // } // // private static boolean matchMask(byte test, byte mask) { // return ((byte)(test & mask)) == mask; // } // // private Tag parseTag(byte b, InputStream in) { // if (matchMask(b, Header.COMPLEX_TAG_MASK)) // return parseComplexTag(b, in); // else // return parsePrimitiveTag(b); // } // // private Tag parsePrimitiveTag(byte b) { // int tag = b & Header.COMPLEX_TAG_MASK; // boolean isConstructed = matchMask(b, Header.CONSTRUCTED_MASK); // TagClass tc = TagClass.of((byte)(b & TagClass.PRIVATE.getMask())); // return new Tag(tag, tc, isConstructed, new byte[] { b }); // } // // private Tag parseComplexTag(byte b, InputStream in) { // boolean isConstructed = matchMask(b, Header.CONSTRUCTED_MASK); // TagClass tc = TagClass.of((byte)(b & TagClass.PRIVATE.getMask())); // int tag = 0; // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // baos.write(b & 0xff); // b = nextByte(in); // if (b == Header.INFINITE_LENGTH_MASK) // throw new ParseException("Bits 7 to 1 of the first subsequent octet shall not be 0 for complex tag encodings"); // // while (matchMask(b, Header.INFINITE_LENGTH_MASK)) { // if (tag > (MAX_TAG)) // throw new ParseException("Complex tag too long."); // tag <<= 7; // tag |= (b & 0x7f); // baos.write(b & 0xff); // b = nextByte(in); // } // // //final byte // tag <<= 7; // tag |= (b & 0x7f); // baos.write(b & 0xff); // // return new Tag(tag, tc, isConstructed, baos.toByteArray()); // } // // private Length parseLength(InputStream in) { // byte b = nextByte(in); // // if (b == Header.INFINITE_LENGTH_MASK) // return new Length(0, true, new byte[] { b }); // else if (matchMask(b, Header.INFINITE_LENGTH_MASK)) // return parseComplexDefiniteLength(b, in); // else // return new Length(b & 0xff, false, new byte[] { b }); // } // // private Length parseComplexDefiniteLength(byte b, InputStream in) { // int len = 0; // int numOctets = b & 0x7f; // int off = 0; // // if ((b & 0xff) == 0xff) // throw new ParseException("Initial octet of complex definite length shall not be 0xFF"); // // // byte[] encoding = new byte[numOctets+1]; // encoding[off++] = b; // // for (int i=numOctets; i > 0; i--) { // if (numOctets > MAX_LENGTH) // throw new ParseException("Definite value length too long."); // b = nextByte(in); // len <<= 8; // len |= (b & 0xff); // encoding[off++] = b; // } // // return new Length(len, false, encoding); // } // } // Path: src/impl/krypt/asn1/ParserFactory.java import impl.krypt.asn1.parser.PullHeaderParser; /* * krypt-core API - Java version * * Copyright (c) 2011-2013 * Hiroshi Nakamura <[email protected]> * Martin Bosslet <[email protected]> * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package impl.krypt.asn1; /** * * @author <a href="mailto:[email protected]">Martin Bosslet</a> */ public class ParserFactory { public Parser newHeaderParser() {
return new PullHeaderParser();
apatry/neo4j-lucene4-index
src/test/java/org/neo4j/index/impl/lucene/BatchInsertionIT.java
// Path: src/main/java/org/neo4j/index/impl/lucene/LuceneIndexImplementation.java // public static final Map<String, String> EXACT_CONFIG = // Collections.unmodifiableMap( MapUtil.stringMap( // IndexManager.PROVIDER, SERVICE_NAME, KEY_TYPE, "exact" ) );
import org.junit.Test; import org.neo4j.graphdb.index.BatchInserterIndex; import org.neo4j.graphdb.index.BatchInserterIndexProvider; import org.neo4j.kernel.impl.batchinsert.BatchInserter; import org.neo4j.kernel.impl.batchinsert.BatchInserterImpl; import org.neo4j.kernel.impl.util.FileUtils; import static java.lang.System.currentTimeMillis; import static org.neo4j.helpers.collection.IteratorUtil.count; import static org.neo4j.helpers.collection.MapUtil.map; import static org.neo4j.index.impl.lucene.LuceneIndexImplementation.EXACT_CONFIG; import java.io.File; import java.util.Iterator; import java.util.Map; import org.junit.Before; import org.junit.Ignore;
/** * Copyright (c) 2002-2014 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.index.impl.lucene; public class BatchInsertionIT { private static final String PATH = "target/var/batch"; @Before public void cleanDirectory() throws Exception { FileUtils.deleteRecursively( new File( PATH ) ); } @Ignore @Test public void testInsertionSpeed() { BatchInserter inserter = new BatchInserterImpl( new File( PATH, "3" ).getAbsolutePath() ); BatchInserterIndexProvider provider = new LuceneBatchInserterIndexProvider( inserter );
// Path: src/main/java/org/neo4j/index/impl/lucene/LuceneIndexImplementation.java // public static final Map<String, String> EXACT_CONFIG = // Collections.unmodifiableMap( MapUtil.stringMap( // IndexManager.PROVIDER, SERVICE_NAME, KEY_TYPE, "exact" ) ); // Path: src/test/java/org/neo4j/index/impl/lucene/BatchInsertionIT.java import org.junit.Test; import org.neo4j.graphdb.index.BatchInserterIndex; import org.neo4j.graphdb.index.BatchInserterIndexProvider; import org.neo4j.kernel.impl.batchinsert.BatchInserter; import org.neo4j.kernel.impl.batchinsert.BatchInserterImpl; import org.neo4j.kernel.impl.util.FileUtils; import static java.lang.System.currentTimeMillis; import static org.neo4j.helpers.collection.IteratorUtil.count; import static org.neo4j.helpers.collection.MapUtil.map; import static org.neo4j.index.impl.lucene.LuceneIndexImplementation.EXACT_CONFIG; import java.io.File; import java.util.Iterator; import java.util.Map; import org.junit.Before; import org.junit.Ignore; /** * Copyright (c) 2002-2014 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.index.impl.lucene; public class BatchInsertionIT { private static final String PATH = "target/var/batch"; @Before public void cleanDirectory() throws Exception { FileUtils.deleteRecursively( new File( PATH ) ); } @Ignore @Test public void testInsertionSpeed() { BatchInserter inserter = new BatchInserterImpl( new File( PATH, "3" ).getAbsolutePath() ); BatchInserterIndexProvider provider = new LuceneBatchInserterIndexProvider( inserter );
BatchInserterIndex index = provider.nodeIndex( "yeah", EXACT_CONFIG );
apatry/neo4j-lucene4-index
src/test/java/org/neo4j/index/impl/lucene/TestLuceneDataSource.java
// Path: src/test/java/org/apache/lucene/index/IndexWriterAccessor.java // public class IndexWriterAccessor // { // public static boolean isClosed(IndexWriter writer) // { // return writer.isClosed(); // } // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.Map; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterAccessor; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.factory.GraphDatabaseSettings; import org.neo4j.graphdb.index.IndexManager; import org.neo4j.helpers.collection.MapUtil; import org.neo4j.kernel.DefaultFileSystemAbstraction; import org.neo4j.kernel.configuration.Config; import org.neo4j.kernel.configuration.ConfigurationDefaults; import org.neo4j.kernel.impl.index.IndexStore; import org.neo4j.kernel.impl.nioneo.store.FileSystemAbstraction; import org.neo4j.kernel.impl.transaction.PlaceboTm; import org.neo4j.kernel.impl.transaction.xaframework.DefaultLogBufferFactory; import org.neo4j.kernel.impl.transaction.xaframework.LogPruneStrategies; import org.neo4j.kernel.impl.transaction.xaframework.RecoveryVerifier; import org.neo4j.kernel.impl.transaction.xaframework.TxIdGenerator; import org.neo4j.kernel.impl.transaction.xaframework.XaFactory; import org.neo4j.kernel.impl.util.FileUtils; import org.neo4j.kernel.impl.util.StringLogger;
@Test public void testShouldReturnIndexSearcherFromLRUCache() throws InstantiationException, IOException { Config config = new Config( new ConfigurationDefaults(GraphDatabaseSettings.class ).apply( config()) ); dataSource = new LuceneDataSource( config, indexStore, new DefaultFileSystemAbstraction(), new XaFactory( config, TxIdGenerator.DEFAULT, new PlaceboTm(), new DefaultLogBufferFactory(), new DefaultFileSystemAbstraction(), StringLogger.DEV_NULL, RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING ) ); dataSource.start(); IndexIdentifier identifier = identifier( "foo" ); IndexReference searcher = dataSource.getIndexSearcher( identifier ); assertSame( searcher, dataSource.getIndexSearcher( identifier ) ); searcher.close(); } @Test public void testClosesOldestIndexWriterWhenCacheSizeIsExceeded() throws InstantiationException { addIndex( "bar" ); addIndex( "baz" ); Map<String,String> config = config(); config.put( GraphDatabaseSettings.lucene_searcher_cache_size.name(), "2"); Config config1 = new Config( new ConfigurationDefaults(GraphDatabaseSettings.class ).apply( config) ); dataSource = new LuceneDataSource( config1, indexStore, new DefaultFileSystemAbstraction(), new XaFactory(config1, TxIdGenerator.DEFAULT, new PlaceboTm(), new DefaultLogBufferFactory(), new DefaultFileSystemAbstraction(), StringLogger.DEV_NULL, RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING ) ); dataSource.start(); IndexIdentifier fooIdentifier = identifier( "foo" ); IndexIdentifier barIdentifier = identifier( "bar" ); IndexIdentifier bazIdentifier = identifier( "baz" ); IndexWriter fooIndexWriter = dataSource.getIndexSearcher( fooIdentifier ).getWriter(); dataSource.getIndexSearcher( barIdentifier );
// Path: src/test/java/org/apache/lucene/index/IndexWriterAccessor.java // public class IndexWriterAccessor // { // public static boolean isClosed(IndexWriter writer) // { // return writer.isClosed(); // } // } // Path: src/test/java/org/neo4j/index/impl/lucene/TestLuceneDataSource.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.Map; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterAccessor; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.factory.GraphDatabaseSettings; import org.neo4j.graphdb.index.IndexManager; import org.neo4j.helpers.collection.MapUtil; import org.neo4j.kernel.DefaultFileSystemAbstraction; import org.neo4j.kernel.configuration.Config; import org.neo4j.kernel.configuration.ConfigurationDefaults; import org.neo4j.kernel.impl.index.IndexStore; import org.neo4j.kernel.impl.nioneo.store.FileSystemAbstraction; import org.neo4j.kernel.impl.transaction.PlaceboTm; import org.neo4j.kernel.impl.transaction.xaframework.DefaultLogBufferFactory; import org.neo4j.kernel.impl.transaction.xaframework.LogPruneStrategies; import org.neo4j.kernel.impl.transaction.xaframework.RecoveryVerifier; import org.neo4j.kernel.impl.transaction.xaframework.TxIdGenerator; import org.neo4j.kernel.impl.transaction.xaframework.XaFactory; import org.neo4j.kernel.impl.util.FileUtils; import org.neo4j.kernel.impl.util.StringLogger; @Test public void testShouldReturnIndexSearcherFromLRUCache() throws InstantiationException, IOException { Config config = new Config( new ConfigurationDefaults(GraphDatabaseSettings.class ).apply( config()) ); dataSource = new LuceneDataSource( config, indexStore, new DefaultFileSystemAbstraction(), new XaFactory( config, TxIdGenerator.DEFAULT, new PlaceboTm(), new DefaultLogBufferFactory(), new DefaultFileSystemAbstraction(), StringLogger.DEV_NULL, RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING ) ); dataSource.start(); IndexIdentifier identifier = identifier( "foo" ); IndexReference searcher = dataSource.getIndexSearcher( identifier ); assertSame( searcher, dataSource.getIndexSearcher( identifier ) ); searcher.close(); } @Test public void testClosesOldestIndexWriterWhenCacheSizeIsExceeded() throws InstantiationException { addIndex( "bar" ); addIndex( "baz" ); Map<String,String> config = config(); config.put( GraphDatabaseSettings.lucene_searcher_cache_size.name(), "2"); Config config1 = new Config( new ConfigurationDefaults(GraphDatabaseSettings.class ).apply( config) ); dataSource = new LuceneDataSource( config1, indexStore, new DefaultFileSystemAbstraction(), new XaFactory(config1, TxIdGenerator.DEFAULT, new PlaceboTm(), new DefaultLogBufferFactory(), new DefaultFileSystemAbstraction(), StringLogger.DEV_NULL, RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING ) ); dataSource.start(); IndexIdentifier fooIdentifier = identifier( "foo" ); IndexIdentifier barIdentifier = identifier( "bar" ); IndexIdentifier bazIdentifier = identifier( "baz" ); IndexWriter fooIndexWriter = dataSource.getIndexSearcher( fooIdentifier ).getWriter(); dataSource.getIndexSearcher( barIdentifier );
assertFalse( IndexWriterAccessor.isClosed( fooIndexWriter ) );
apatry/neo4j-lucene4-index
src/main/java/org/neo4j/index/lucene/unsafe/batchinsert/LuceneBatchInserterIndexProvider.java
// Path: src/main/java/org/neo4j/index/impl/lucene/LuceneBatchInserterIndexProviderNewImpl.java // public class LuceneBatchInserterIndexProviderNewImpl implements BatchInserterIndexProvider // { // private final BatchInserter inserter; // private final Map<IndexIdentifier, LuceneBatchInserterIndex> indexes = // new HashMap<IndexIdentifier, LuceneBatchInserterIndex>(); // final IndexStore indexStore; // final EntityType nodeEntityType; // final EntityType relationshipEntityType; // // public LuceneBatchInserterIndexProviderNewImpl( final BatchInserter inserter ) // { // this.inserter = inserter; // this.indexStore = ((BatchInserterImpl) inserter).getIndexStore(); // this.nodeEntityType = new EntityType() // { // @Override // public Document newDocument( Object entityId ) // { // return IndexType.newBaseDocument( (Long) entityId ); // } // // @Override // public Class<? extends PropertyContainer> getType() // { // return Node.class; // } // }; // this.relationshipEntityType = new EntityType() // { // @Override // public Document newDocument( Object entityId ) // { // RelationshipId relId = null; // if ( entityId instanceof Long ) // { // BatchRelationship relationship = inserter // .getRelationshipById( (Long) entityId ); // relId = new RelationshipId( relationship.getId(), relationship.getStartNode(), // relationship.getEndNode() ); // } // else if ( entityId instanceof RelationshipId ) // { // relId = (RelationshipId) entityId; // } // else // { // throw new IllegalArgumentException( "Ids of type " + entityId.getClass() // + " are not supported." ); // } // Document doc = IndexType.newBaseDocument( relId.id ); // doc.add( new Field( LuceneIndex.KEY_START_NODE_ID, "" + relId.startNode, // Store.YES, org.apache.lucene.document.Field.Index.NOT_ANALYZED ) ); // doc.add( new Field( LuceneIndex.KEY_END_NODE_ID, "" + relId.endNode, // Store.YES, org.apache.lucene.document.Field.Index.NOT_ANALYZED ) ); // return doc; // } // // @Override // public Class<? extends PropertyContainer> getType() // { // return Relationship.class; // } // }; // } // // @Override // public BatchInserterIndex nodeIndex( String indexName, Map<String, String> config ) // { // config( Node.class, indexName, config ); // return index( new IndexIdentifier( LuceneCommand.NODE, nodeEntityType, indexName ), config ); // } // // private Map<String, String> config( Class<? extends PropertyContainer> cls, // String indexName, Map<String, String> config ) // { // // TODO Doesn't look right // if ( config != null ) // { // config = MapUtil.stringMap( new HashMap<String, String>( config ), // IndexManager.PROVIDER, LuceneIndexImplementation.SERVICE_NAME ); // indexStore.setIfNecessary( cls, indexName, config ); // return config; // } // else // { // return indexStore.get( cls, indexName ); // } // } // // @Override // public BatchInserterIndex relationshipIndex( String indexName, Map<String, String> config ) // { // config( Relationship.class, indexName, config ); // return index( new IndexIdentifier( LuceneCommand.RELATIONSHIP, relationshipEntityType, indexName ), config ); // } // // private BatchInserterIndex index( IndexIdentifier identifier, Map<String, String> config ) // { // // We don't care about threads here... c'mon... it's a // // single-threaded batch inserter // LuceneBatchInserterIndex index = indexes.get( identifier ); // if ( index == null ) // { // index = new LuceneBatchInserterIndex( inserter.getStoreDir(), // identifier, // config ); // indexes.put( identifier, index ); // } // return index; // } // // @Override // public void shutdown() // { // for ( LuceneBatchInserterIndex index : indexes.values() ) // { // index.shutdown(); // } // } // }
import java.util.Map; import org.neo4j.graphdb.index.Index; import org.neo4j.index.impl.lucene.LuceneBatchInserterIndexProviderNewImpl; import org.neo4j.unsafe.batchinsert.BatchInserter; import org.neo4j.unsafe.batchinsert.BatchInserterIndex; import org.neo4j.unsafe.batchinsert.BatchInserterIndexProvider;
/** * Copyright (c) 2002-2014 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.index.lucene.unsafe.batchinsert; /** * The {@link org.neo4j.unsafe.batchinsert.BatchInserter} version of the Lucene-based indexes. Indexes * created and populated using {@link org.neo4j.unsafe.batchinsert.BatchInserterIndex}s from this provider * are compatible with the normal {@link Index}es. */ public class LuceneBatchInserterIndexProvider implements BatchInserterIndexProvider { private final BatchInserterIndexProvider provider; public LuceneBatchInserterIndexProvider( final BatchInserter inserter ) {
// Path: src/main/java/org/neo4j/index/impl/lucene/LuceneBatchInserterIndexProviderNewImpl.java // public class LuceneBatchInserterIndexProviderNewImpl implements BatchInserterIndexProvider // { // private final BatchInserter inserter; // private final Map<IndexIdentifier, LuceneBatchInserterIndex> indexes = // new HashMap<IndexIdentifier, LuceneBatchInserterIndex>(); // final IndexStore indexStore; // final EntityType nodeEntityType; // final EntityType relationshipEntityType; // // public LuceneBatchInserterIndexProviderNewImpl( final BatchInserter inserter ) // { // this.inserter = inserter; // this.indexStore = ((BatchInserterImpl) inserter).getIndexStore(); // this.nodeEntityType = new EntityType() // { // @Override // public Document newDocument( Object entityId ) // { // return IndexType.newBaseDocument( (Long) entityId ); // } // // @Override // public Class<? extends PropertyContainer> getType() // { // return Node.class; // } // }; // this.relationshipEntityType = new EntityType() // { // @Override // public Document newDocument( Object entityId ) // { // RelationshipId relId = null; // if ( entityId instanceof Long ) // { // BatchRelationship relationship = inserter // .getRelationshipById( (Long) entityId ); // relId = new RelationshipId( relationship.getId(), relationship.getStartNode(), // relationship.getEndNode() ); // } // else if ( entityId instanceof RelationshipId ) // { // relId = (RelationshipId) entityId; // } // else // { // throw new IllegalArgumentException( "Ids of type " + entityId.getClass() // + " are not supported." ); // } // Document doc = IndexType.newBaseDocument( relId.id ); // doc.add( new Field( LuceneIndex.KEY_START_NODE_ID, "" + relId.startNode, // Store.YES, org.apache.lucene.document.Field.Index.NOT_ANALYZED ) ); // doc.add( new Field( LuceneIndex.KEY_END_NODE_ID, "" + relId.endNode, // Store.YES, org.apache.lucene.document.Field.Index.NOT_ANALYZED ) ); // return doc; // } // // @Override // public Class<? extends PropertyContainer> getType() // { // return Relationship.class; // } // }; // } // // @Override // public BatchInserterIndex nodeIndex( String indexName, Map<String, String> config ) // { // config( Node.class, indexName, config ); // return index( new IndexIdentifier( LuceneCommand.NODE, nodeEntityType, indexName ), config ); // } // // private Map<String, String> config( Class<? extends PropertyContainer> cls, // String indexName, Map<String, String> config ) // { // // TODO Doesn't look right // if ( config != null ) // { // config = MapUtil.stringMap( new HashMap<String, String>( config ), // IndexManager.PROVIDER, LuceneIndexImplementation.SERVICE_NAME ); // indexStore.setIfNecessary( cls, indexName, config ); // return config; // } // else // { // return indexStore.get( cls, indexName ); // } // } // // @Override // public BatchInserterIndex relationshipIndex( String indexName, Map<String, String> config ) // { // config( Relationship.class, indexName, config ); // return index( new IndexIdentifier( LuceneCommand.RELATIONSHIP, relationshipEntityType, indexName ), config ); // } // // private BatchInserterIndex index( IndexIdentifier identifier, Map<String, String> config ) // { // // We don't care about threads here... c'mon... it's a // // single-threaded batch inserter // LuceneBatchInserterIndex index = indexes.get( identifier ); // if ( index == null ) // { // index = new LuceneBatchInserterIndex( inserter.getStoreDir(), // identifier, // config ); // indexes.put( identifier, index ); // } // return index; // } // // @Override // public void shutdown() // { // for ( LuceneBatchInserterIndex index : indexes.values() ) // { // index.shutdown(); // } // } // } // Path: src/main/java/org/neo4j/index/lucene/unsafe/batchinsert/LuceneBatchInserterIndexProvider.java import java.util.Map; import org.neo4j.graphdb.index.Index; import org.neo4j.index.impl.lucene.LuceneBatchInserterIndexProviderNewImpl; import org.neo4j.unsafe.batchinsert.BatchInserter; import org.neo4j.unsafe.batchinsert.BatchInserterIndex; import org.neo4j.unsafe.batchinsert.BatchInserterIndexProvider; /** * Copyright (c) 2002-2014 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.index.lucene.unsafe.batchinsert; /** * The {@link org.neo4j.unsafe.batchinsert.BatchInserter} version of the Lucene-based indexes. Indexes * created and populated using {@link org.neo4j.unsafe.batchinsert.BatchInserterIndex}s from this provider * are compatible with the normal {@link Index}es. */ public class LuceneBatchInserterIndexProvider implements BatchInserterIndexProvider { private final BatchInserterIndexProvider provider; public LuceneBatchInserterIndexProvider( final BatchInserter inserter ) {
provider = new LuceneBatchInserterIndexProviderNewImpl( inserter );
apatry/neo4j-lucene4-index
src/main/java/org/neo4j/index/lucene/QueryContext.java
// Path: src/main/java/org/neo4j/index/impl/lucene/LuceneUtil.java // public abstract class LuceneUtil // { // static void close( IndexWriter writer ) // { // close( (Object) writer ); // } // // static void close( IndexSearcher searcher ) // { // close( (Object) searcher ); // } // // private static void close( Object object ) // { // if ( object == null ) // { // return; // } // // try // { // if ( object instanceof IndexWriter ) // { // ((IndexWriter) object).close(); // } // else if ( object instanceof IndexSearcher ) // { // // nothing to close since lucene 4.0.0 // } // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // } // // static void strictAddDocument( IndexWriter writer, Document document ) // { // try // { // writer.addDocument( document ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // } // // static void strictRemoveDocument( IndexWriter writer, Query query ) // { // try // { // writer.deleteDocuments( query ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // } // // /** // * Will create a {@link Query} with a query for numeric ranges, that is // * values that have been indexed using {@link ValueContext#indexNumeric()}. // * It will match the type of numbers supplied to the type of values that // * are indexed in the index, f.ex. long, int, float and double. // * If both {@code from} and {@code to} is {@code null} then it will default // * to int. // * // * @param key the property key to query. // * @param from the low end of the range (inclusive) // * @param to the high end of the range (inclusive) // * @param includeFrom whether or not {@code from} (the lower bound) is inclusive // * or not. // * @param includeTo whether or not {@code to} (the higher bound) is inclusive // * or not. // * @return a {@link Query} to do numeric range queries with. // */ // public static Query rangeQuery( String key, Number from, Number to, // boolean includeFrom, boolean includeTo ) // { // if ( from instanceof Long || to instanceof Long ) // { // return NumericRangeQuery.newLongRange( key, from != null ? from.longValue() : 0, // to != null ? to.longValue() : Long.MAX_VALUE, includeFrom, includeTo ); // } // else if ( from instanceof Double || to instanceof Double ) // { // return NumericRangeQuery.newDoubleRange( key, from != null ? from.doubleValue() : 0, // to != null ? to.doubleValue() : Double.MAX_VALUE, includeFrom, includeTo ); // } // else if ( from instanceof Float || to instanceof Float ) // { // return NumericRangeQuery.newFloatRange( key, from != null ? from.floatValue() : 0, // to != null ? to.floatValue() : Float.MAX_VALUE, includeFrom, includeTo ); // } // else // { // return NumericRangeQuery.newIntRange( key, from != null ? from.intValue() : 0, // to != null ? to.intValue() : Integer.MAX_VALUE, includeFrom, includeTo ); // } // } // }
import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.NumericRangeQuery; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.index.impl.lucene.LuceneUtil;
* @param key the property key to query. * @param from the low end of the range (inclusive) * @param to the high end of the range (inclusive) * @return a {@link QueryContext} to do numeric range queries with. */ public static QueryContext numericRange( String key, Number from, Number to ) { return numericRange( key, from, to, true, true ); } /** * Will create a {@link QueryContext} with a query for numeric ranges, that is * values that have been indexed using {@link ValueContext#indexNumeric()}. * It will match the type of numbers supplied to the type of values that * are indexed in the index, f.ex. long, int, float and double. * If both {@code from} and {@code to} is {@code null} then it will default * to int. * * @param key the property key to query. * @param from the low end of the range (inclusive) * @param to the high end of the range (inclusive) * @param includeFrom whether or not {@code from} (the lower bound) is inclusive * or not. * @param includeTo whether or not {@code to} (the higher bound) is inclusive * or not. * @return a {@link QueryContext} to do numeric range queries with. */ public static QueryContext numericRange( String key, Number from, Number to, boolean includeFrom, boolean includeTo ) {
// Path: src/main/java/org/neo4j/index/impl/lucene/LuceneUtil.java // public abstract class LuceneUtil // { // static void close( IndexWriter writer ) // { // close( (Object) writer ); // } // // static void close( IndexSearcher searcher ) // { // close( (Object) searcher ); // } // // private static void close( Object object ) // { // if ( object == null ) // { // return; // } // // try // { // if ( object instanceof IndexWriter ) // { // ((IndexWriter) object).close(); // } // else if ( object instanceof IndexSearcher ) // { // // nothing to close since lucene 4.0.0 // } // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // } // // static void strictAddDocument( IndexWriter writer, Document document ) // { // try // { // writer.addDocument( document ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // } // // static void strictRemoveDocument( IndexWriter writer, Query query ) // { // try // { // writer.deleteDocuments( query ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // } // // /** // * Will create a {@link Query} with a query for numeric ranges, that is // * values that have been indexed using {@link ValueContext#indexNumeric()}. // * It will match the type of numbers supplied to the type of values that // * are indexed in the index, f.ex. long, int, float and double. // * If both {@code from} and {@code to} is {@code null} then it will default // * to int. // * // * @param key the property key to query. // * @param from the low end of the range (inclusive) // * @param to the high end of the range (inclusive) // * @param includeFrom whether or not {@code from} (the lower bound) is inclusive // * or not. // * @param includeTo whether or not {@code to} (the higher bound) is inclusive // * or not. // * @return a {@link Query} to do numeric range queries with. // */ // public static Query rangeQuery( String key, Number from, Number to, // boolean includeFrom, boolean includeTo ) // { // if ( from instanceof Long || to instanceof Long ) // { // return NumericRangeQuery.newLongRange( key, from != null ? from.longValue() : 0, // to != null ? to.longValue() : Long.MAX_VALUE, includeFrom, includeTo ); // } // else if ( from instanceof Double || to instanceof Double ) // { // return NumericRangeQuery.newDoubleRange( key, from != null ? from.doubleValue() : 0, // to != null ? to.doubleValue() : Double.MAX_VALUE, includeFrom, includeTo ); // } // else if ( from instanceof Float || to instanceof Float ) // { // return NumericRangeQuery.newFloatRange( key, from != null ? from.floatValue() : 0, // to != null ? to.floatValue() : Float.MAX_VALUE, includeFrom, includeTo ); // } // else // { // return NumericRangeQuery.newIntRange( key, from != null ? from.intValue() : 0, // to != null ? to.intValue() : Integer.MAX_VALUE, includeFrom, includeTo ); // } // } // } // Path: src/main/java/org/neo4j/index/lucene/QueryContext.java import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.NumericRangeQuery; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.index.impl.lucene.LuceneUtil; * @param key the property key to query. * @param from the low end of the range (inclusive) * @param to the high end of the range (inclusive) * @return a {@link QueryContext} to do numeric range queries with. */ public static QueryContext numericRange( String key, Number from, Number to ) { return numericRange( key, from, to, true, true ); } /** * Will create a {@link QueryContext} with a query for numeric ranges, that is * values that have been indexed using {@link ValueContext#indexNumeric()}. * It will match the type of numbers supplied to the type of values that * are indexed in the index, f.ex. long, int, float and double. * If both {@code from} and {@code to} is {@code null} then it will default * to int. * * @param key the property key to query. * @param from the low end of the range (inclusive) * @param to the high end of the range (inclusive) * @param includeFrom whether or not {@code from} (the lower bound) is inclusive * or not. * @param includeTo whether or not {@code to} (the higher bound) is inclusive * or not. * @return a {@link QueryContext} to do numeric range queries with. */ public static QueryContext numericRange( String key, Number from, Number to, boolean includeFrom, boolean includeTo ) {
return new QueryContext( LuceneUtil.rangeQuery( key, from, to, includeFrom, includeTo ) );
apatry/neo4j-lucene4-index
src/main/java/org/neo4j/index/impl/lucene/LuceneBatchInserterIndex.java
// Path: src/main/java/org/neo4j/index/lucene/ValueContext.java // public class ValueContext // { // private final Object value; // private boolean indexNumeric; // // public ValueContext( Object value ) // { // this.value = value; // } // // /** // * @return the value object specified in the constructor. // */ // public Object getValue() // { // return value; // } // // /** // * Returns a ValueContext to be used with {@link Index#add(PropertyContainer, String, Object)} // * // * @return a numeric ValueContext // */ // public ValueContext indexNumeric() // { // if ( !( this.value instanceof Number ) ) // { // throw new IllegalStateException( "Value should be a Number, is " + value + // " (" + value.getClass() + ")" ); // } // this.indexNumeric = true; // return this; // } // // /** // * Returns the string representation of the value given in the constructor, // * or the unmodified value if {@link #indexNumeric()} has been called. // * // * @return the, by the user, intended value to index. // */ // public Object getCorrectValue() // { // return this.indexNumeric ? this.value : this.value.toString(); // } // // @Override // public String toString() // { // return value.toString(); // } // // /** // * Convience method to add a numeric value to an index. // * @param value The value to add // * @return A ValueContext that can be used with {@link Index#add(PropertyContainer, String, Object)} // */ // public static ValueContext numeric(Number value) // { // return new ValueContext(value).indexNumeric(); // } // } // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // public static final Version LUCENE_VERSION = Version.LUCENE_40; // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // static Directory getDirectory( String storeDir, // IndexIdentifier identifier ) throws IOException // { // return FSDirectory.open( getFileDirectory( storeDir, identifier) ); // }
import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.TopDocs; import org.neo4j.graphdb.index.BatchInserterIndex; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.helpers.Pair; import org.neo4j.index.lucene.ValueContext; import org.neo4j.kernel.impl.cache.LruCache; import org.neo4j.kernel.impl.util.IoPrimitiveUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import static org.neo4j.index.impl.lucene.LuceneDataSource.LUCENE_VERSION; import static org.neo4j.index.impl.lucene.LuceneDataSource.getDirectory;
} @Override public void add( long entityId, Map<String, Object> properties ) { try { Document document = identifier.entityType.newDocument( entityId ); for ( Map.Entry<String, Object> entry : properties.entrySet() ) { String key = entry.getKey(); Object value = entry.getValue(); addSingleProperty(entityId, document, key, value); } writer.addDocument( document ); if ( ++updateCount == commitBatchSize ) { writer.commit(); updateCount = 0; } } catch ( IOException e ) { throw new RuntimeException( e ); } } private void addSingleProperty( long entityId, Document document, String key, Object value ) { for ( Object oneValue : IoPrimitiveUtils.asArray(value) ) {
// Path: src/main/java/org/neo4j/index/lucene/ValueContext.java // public class ValueContext // { // private final Object value; // private boolean indexNumeric; // // public ValueContext( Object value ) // { // this.value = value; // } // // /** // * @return the value object specified in the constructor. // */ // public Object getValue() // { // return value; // } // // /** // * Returns a ValueContext to be used with {@link Index#add(PropertyContainer, String, Object)} // * // * @return a numeric ValueContext // */ // public ValueContext indexNumeric() // { // if ( !( this.value instanceof Number ) ) // { // throw new IllegalStateException( "Value should be a Number, is " + value + // " (" + value.getClass() + ")" ); // } // this.indexNumeric = true; // return this; // } // // /** // * Returns the string representation of the value given in the constructor, // * or the unmodified value if {@link #indexNumeric()} has been called. // * // * @return the, by the user, intended value to index. // */ // public Object getCorrectValue() // { // return this.indexNumeric ? this.value : this.value.toString(); // } // // @Override // public String toString() // { // return value.toString(); // } // // /** // * Convience method to add a numeric value to an index. // * @param value The value to add // * @return A ValueContext that can be used with {@link Index#add(PropertyContainer, String, Object)} // */ // public static ValueContext numeric(Number value) // { // return new ValueContext(value).indexNumeric(); // } // } // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // public static final Version LUCENE_VERSION = Version.LUCENE_40; // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // static Directory getDirectory( String storeDir, // IndexIdentifier identifier ) throws IOException // { // return FSDirectory.open( getFileDirectory( storeDir, identifier) ); // } // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneBatchInserterIndex.java import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.TopDocs; import org.neo4j.graphdb.index.BatchInserterIndex; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.helpers.Pair; import org.neo4j.index.lucene.ValueContext; import org.neo4j.kernel.impl.cache.LruCache; import org.neo4j.kernel.impl.util.IoPrimitiveUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import static org.neo4j.index.impl.lucene.LuceneDataSource.LUCENE_VERSION; import static org.neo4j.index.impl.lucene.LuceneDataSource.getDirectory; } @Override public void add( long entityId, Map<String, Object> properties ) { try { Document document = identifier.entityType.newDocument( entityId ); for ( Map.Entry<String, Object> entry : properties.entrySet() ) { String key = entry.getKey(); Object value = entry.getValue(); addSingleProperty(entityId, document, key, value); } writer.addDocument( document ); if ( ++updateCount == commitBatchSize ) { writer.commit(); updateCount = 0; } } catch ( IOException e ) { throw new RuntimeException( e ); } } private void addSingleProperty( long entityId, Document document, String key, Object value ) { for ( Object oneValue : IoPrimitiveUtils.asArray(value) ) {
boolean isValueContext = oneValue instanceof ValueContext;
apatry/neo4j-lucene4-index
src/main/java/org/neo4j/index/impl/lucene/LuceneBatchInserterIndex.java
// Path: src/main/java/org/neo4j/index/lucene/ValueContext.java // public class ValueContext // { // private final Object value; // private boolean indexNumeric; // // public ValueContext( Object value ) // { // this.value = value; // } // // /** // * @return the value object specified in the constructor. // */ // public Object getValue() // { // return value; // } // // /** // * Returns a ValueContext to be used with {@link Index#add(PropertyContainer, String, Object)} // * // * @return a numeric ValueContext // */ // public ValueContext indexNumeric() // { // if ( !( this.value instanceof Number ) ) // { // throw new IllegalStateException( "Value should be a Number, is " + value + // " (" + value.getClass() + ")" ); // } // this.indexNumeric = true; // return this; // } // // /** // * Returns the string representation of the value given in the constructor, // * or the unmodified value if {@link #indexNumeric()} has been called. // * // * @return the, by the user, intended value to index. // */ // public Object getCorrectValue() // { // return this.indexNumeric ? this.value : this.value.toString(); // } // // @Override // public String toString() // { // return value.toString(); // } // // /** // * Convience method to add a numeric value to an index. // * @param value The value to add // * @return A ValueContext that can be used with {@link Index#add(PropertyContainer, String, Object)} // */ // public static ValueContext numeric(Number value) // { // return new ValueContext(value).indexNumeric(); // } // } // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // public static final Version LUCENE_VERSION = Version.LUCENE_40; // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // static Directory getDirectory( String storeDir, // IndexIdentifier identifier ) throws IOException // { // return FSDirectory.open( getFileDirectory( storeDir, identifier) ); // }
import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.TopDocs; import org.neo4j.graphdb.index.BatchInserterIndex; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.helpers.Pair; import org.neo4j.index.lucene.ValueContext; import org.neo4j.kernel.impl.cache.LruCache; import org.neo4j.kernel.impl.util.IoPrimitiveUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import static org.neo4j.index.impl.lucene.LuceneDataSource.LUCENE_VERSION; import static org.neo4j.index.impl.lucene.LuceneDataSource.getDirectory;
String key = field.name(); Object value = field.stringValue(); removeFromCache( entityId, key, value ); } } } private void removeFromCache( long entityId, String key, Object value ) { if ( this.cache == null ) { return; } String valueAsString = value.toString(); LruCache<String, Collection<Long>> cache = this.cache.get( key ); if ( cache != null ) { Collection<Long> ids = cache.get( valueAsString ); if ( ids != null ) { ids.remove( entityId ); } } } private IndexWriter instantiateWriter( String directory ) { try {
// Path: src/main/java/org/neo4j/index/lucene/ValueContext.java // public class ValueContext // { // private final Object value; // private boolean indexNumeric; // // public ValueContext( Object value ) // { // this.value = value; // } // // /** // * @return the value object specified in the constructor. // */ // public Object getValue() // { // return value; // } // // /** // * Returns a ValueContext to be used with {@link Index#add(PropertyContainer, String, Object)} // * // * @return a numeric ValueContext // */ // public ValueContext indexNumeric() // { // if ( !( this.value instanceof Number ) ) // { // throw new IllegalStateException( "Value should be a Number, is " + value + // " (" + value.getClass() + ")" ); // } // this.indexNumeric = true; // return this; // } // // /** // * Returns the string representation of the value given in the constructor, // * or the unmodified value if {@link #indexNumeric()} has been called. // * // * @return the, by the user, intended value to index. // */ // public Object getCorrectValue() // { // return this.indexNumeric ? this.value : this.value.toString(); // } // // @Override // public String toString() // { // return value.toString(); // } // // /** // * Convience method to add a numeric value to an index. // * @param value The value to add // * @return A ValueContext that can be used with {@link Index#add(PropertyContainer, String, Object)} // */ // public static ValueContext numeric(Number value) // { // return new ValueContext(value).indexNumeric(); // } // } // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // public static final Version LUCENE_VERSION = Version.LUCENE_40; // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // static Directory getDirectory( String storeDir, // IndexIdentifier identifier ) throws IOException // { // return FSDirectory.open( getFileDirectory( storeDir, identifier) ); // } // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneBatchInserterIndex.java import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.TopDocs; import org.neo4j.graphdb.index.BatchInserterIndex; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.helpers.Pair; import org.neo4j.index.lucene.ValueContext; import org.neo4j.kernel.impl.cache.LruCache; import org.neo4j.kernel.impl.util.IoPrimitiveUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import static org.neo4j.index.impl.lucene.LuceneDataSource.LUCENE_VERSION; import static org.neo4j.index.impl.lucene.LuceneDataSource.getDirectory; String key = field.name(); Object value = field.stringValue(); removeFromCache( entityId, key, value ); } } } private void removeFromCache( long entityId, String key, Object value ) { if ( this.cache == null ) { return; } String valueAsString = value.toString(); LruCache<String, Collection<Long>> cache = this.cache.get( key ); if ( cache != null ) { Collection<Long> ids = cache.get( valueAsString ); if ( ids != null ) { ids.remove( entityId ); } } } private IndexWriter instantiateWriter( String directory ) { try {
IndexWriterConfig writerConfig = new IndexWriterConfig( LUCENE_VERSION, type.analyzer );
apatry/neo4j-lucene4-index
src/main/java/org/neo4j/index/impl/lucene/LuceneBatchInserterIndex.java
// Path: src/main/java/org/neo4j/index/lucene/ValueContext.java // public class ValueContext // { // private final Object value; // private boolean indexNumeric; // // public ValueContext( Object value ) // { // this.value = value; // } // // /** // * @return the value object specified in the constructor. // */ // public Object getValue() // { // return value; // } // // /** // * Returns a ValueContext to be used with {@link Index#add(PropertyContainer, String, Object)} // * // * @return a numeric ValueContext // */ // public ValueContext indexNumeric() // { // if ( !( this.value instanceof Number ) ) // { // throw new IllegalStateException( "Value should be a Number, is " + value + // " (" + value.getClass() + ")" ); // } // this.indexNumeric = true; // return this; // } // // /** // * Returns the string representation of the value given in the constructor, // * or the unmodified value if {@link #indexNumeric()} has been called. // * // * @return the, by the user, intended value to index. // */ // public Object getCorrectValue() // { // return this.indexNumeric ? this.value : this.value.toString(); // } // // @Override // public String toString() // { // return value.toString(); // } // // /** // * Convience method to add a numeric value to an index. // * @param value The value to add // * @return A ValueContext that can be used with {@link Index#add(PropertyContainer, String, Object)} // */ // public static ValueContext numeric(Number value) // { // return new ValueContext(value).indexNumeric(); // } // } // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // public static final Version LUCENE_VERSION = Version.LUCENE_40; // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // static Directory getDirectory( String storeDir, // IndexIdentifier identifier ) throws IOException // { // return FSDirectory.open( getFileDirectory( storeDir, identifier) ); // }
import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.TopDocs; import org.neo4j.graphdb.index.BatchInserterIndex; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.helpers.Pair; import org.neo4j.index.lucene.ValueContext; import org.neo4j.kernel.impl.cache.LruCache; import org.neo4j.kernel.impl.util.IoPrimitiveUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import static org.neo4j.index.impl.lucene.LuceneDataSource.LUCENE_VERSION; import static org.neo4j.index.impl.lucene.LuceneDataSource.getDirectory;
removeFromCache( entityId, key, value ); } } } private void removeFromCache( long entityId, String key, Object value ) { if ( this.cache == null ) { return; } String valueAsString = value.toString(); LruCache<String, Collection<Long>> cache = this.cache.get( key ); if ( cache != null ) { Collection<Long> ids = cache.get( valueAsString ); if ( ids != null ) { ids.remove( entityId ); } } } private IndexWriter instantiateWriter( String directory ) { try { IndexWriterConfig writerConfig = new IndexWriterConfig( LUCENE_VERSION, type.analyzer ); writerConfig.setRAMBufferSizeMB( determineGoodBufferSize( writerConfig.getRAMBufferSizeMB() ) );
// Path: src/main/java/org/neo4j/index/lucene/ValueContext.java // public class ValueContext // { // private final Object value; // private boolean indexNumeric; // // public ValueContext( Object value ) // { // this.value = value; // } // // /** // * @return the value object specified in the constructor. // */ // public Object getValue() // { // return value; // } // // /** // * Returns a ValueContext to be used with {@link Index#add(PropertyContainer, String, Object)} // * // * @return a numeric ValueContext // */ // public ValueContext indexNumeric() // { // if ( !( this.value instanceof Number ) ) // { // throw new IllegalStateException( "Value should be a Number, is " + value + // " (" + value.getClass() + ")" ); // } // this.indexNumeric = true; // return this; // } // // /** // * Returns the string representation of the value given in the constructor, // * or the unmodified value if {@link #indexNumeric()} has been called. // * // * @return the, by the user, intended value to index. // */ // public Object getCorrectValue() // { // return this.indexNumeric ? this.value : this.value.toString(); // } // // @Override // public String toString() // { // return value.toString(); // } // // /** // * Convience method to add a numeric value to an index. // * @param value The value to add // * @return A ValueContext that can be used with {@link Index#add(PropertyContainer, String, Object)} // */ // public static ValueContext numeric(Number value) // { // return new ValueContext(value).indexNumeric(); // } // } // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // public static final Version LUCENE_VERSION = Version.LUCENE_40; // // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // static Directory getDirectory( String storeDir, // IndexIdentifier identifier ) throws IOException // { // return FSDirectory.open( getFileDirectory( storeDir, identifier) ); // } // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneBatchInserterIndex.java import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.TopDocs; import org.neo4j.graphdb.index.BatchInserterIndex; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.helpers.Pair; import org.neo4j.index.lucene.ValueContext; import org.neo4j.kernel.impl.cache.LruCache; import org.neo4j.kernel.impl.util.IoPrimitiveUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import static org.neo4j.index.impl.lucene.LuceneDataSource.LUCENE_VERSION; import static org.neo4j.index.impl.lucene.LuceneDataSource.getDirectory; removeFromCache( entityId, key, value ); } } } private void removeFromCache( long entityId, String key, Object value ) { if ( this.cache == null ) { return; } String valueAsString = value.toString(); LruCache<String, Collection<Long>> cache = this.cache.get( key ); if ( cache != null ) { Collection<Long> ids = cache.get( valueAsString ); if ( ids != null ) { ids.remove( entityId ); } } } private IndexWriter instantiateWriter( String directory ) { try { IndexWriterConfig writerConfig = new IndexWriterConfig( LUCENE_VERSION, type.analyzer ); writerConfig.setRAMBufferSizeMB( determineGoodBufferSize( writerConfig.getRAMBufferSizeMB() ) );
IndexWriter writer = new IndexWriter( getDirectory( directory, identifier ), writerConfig );
apatry/neo4j-lucene4-index
src/main/java/org/neo4j/index/impl/lucene/LuceneCommand.java
// Path: src/main/java/org/neo4j/index/impl/lucene/CommitContext.java // static class DocumentContext // { // final Document document; // final boolean exists; // final long entityId; // // DocumentContext( Document document, boolean exists, long entityId ) // { // this.document = document; // this.exists = exists; // this.entityId = entityId; // } // }
import org.neo4j.kernel.impl.transaction.xaframework.XaCommand; import org.neo4j.kernel.impl.util.IoPrimitiveUtils; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.util.HashMap; import java.util.Map; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Relationship; import org.neo4j.index.impl.lucene.CommitContext.DocumentContext; import org.neo4j.kernel.impl.transaction.xaframework.LogBuffer;
context.ensureWriterInstantiated(); context.indexType.addToDocument( context.getDocument( entityId, true ).document, key, value ); context.dataSource.invalidateCache( context.identifier, key, value ); } @Override public boolean isConsideredNormalWriteCommand() { return true; } @Override public String toString() { RelationshipId relId = (RelationshipId)entityId; return "AddRel[" + indexId + "," + relId.id + "," + key + "," + value + "," + relId.startNode + "," + relId.endNode + "]"; } } static class RemoveCommand extends LuceneCommand { RemoveCommand( IndexIdentifier indexId, byte entityType, Object entityId, String key, Object value ) { super( indexId, entityType, entityId, key, value, REMOVE_COMMAND ); } @Override void perform( CommitContext context ) { context.ensureWriterInstantiated();
// Path: src/main/java/org/neo4j/index/impl/lucene/CommitContext.java // static class DocumentContext // { // final Document document; // final boolean exists; // final long entityId; // // DocumentContext( Document document, boolean exists, long entityId ) // { // this.document = document; // this.exists = exists; // this.entityId = entityId; // } // } // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneCommand.java import org.neo4j.kernel.impl.transaction.xaframework.XaCommand; import org.neo4j.kernel.impl.util.IoPrimitiveUtils; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.util.HashMap; import java.util.Map; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Relationship; import org.neo4j.index.impl.lucene.CommitContext.DocumentContext; import org.neo4j.kernel.impl.transaction.xaframework.LogBuffer; context.ensureWriterInstantiated(); context.indexType.addToDocument( context.getDocument( entityId, true ).document, key, value ); context.dataSource.invalidateCache( context.identifier, key, value ); } @Override public boolean isConsideredNormalWriteCommand() { return true; } @Override public String toString() { RelationshipId relId = (RelationshipId)entityId; return "AddRel[" + indexId + "," + relId.id + "," + key + "," + value + "," + relId.startNode + "," + relId.endNode + "]"; } } static class RemoveCommand extends LuceneCommand { RemoveCommand( IndexIdentifier indexId, byte entityType, Object entityId, String key, Object value ) { super( indexId, entityType, entityId, key, value, REMOVE_COMMAND ); } @Override void perform( CommitContext context ) { context.ensureWriterInstantiated();
DocumentContext document = context.getDocument( entityId, false );
apatry/neo4j-lucene4-index
src/main/java/org/neo4j/index/impl/lucene/CommitContext.java
// Path: src/main/java/org/neo4j/index/impl/lucene/LuceneTransaction.java // static class CommandList // { // private final List<LuceneCommand> commands = new ArrayList<LuceneCommand>(); // private boolean containsWrites; // // void add( LuceneCommand command ) // { // this.commands.add( command ); // } // // boolean containsWrites() // { // return containsWrites; // } // // boolean isDeletion() // { // return commands.size() == 1 && commands.get( 0 ) instanceof DeleteCommand; // } // // void clear() // { // commands.clear(); // containsWrites = false; // } // // void incCounter( LuceneCommand command ) // { // if ( command.isConsideredNormalWriteCommand() ) // { // containsWrites = true; // } // } // // boolean isEmpty() // { // return commands.isEmpty(); // } // // boolean isRecovery() // { // return commands.get( 0 ).isRecovered(); // } // }
import java.util.HashMap; import java.util.Map; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexWriter; import org.neo4j.index.impl.lucene.LuceneTransaction.CommandList;
/** * Copyright (c) 2002-2014 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.index.impl.lucene; /** * This presents a context for each {@link LuceneCommand} when they are * committing its data. */ class CommitContext { final LuceneDataSource dataSource; final IndexIdentifier identifier; final IndexType indexType; final Map<Long, DocumentContext> documents = new HashMap<Long, DocumentContext>();
// Path: src/main/java/org/neo4j/index/impl/lucene/LuceneTransaction.java // static class CommandList // { // private final List<LuceneCommand> commands = new ArrayList<LuceneCommand>(); // private boolean containsWrites; // // void add( LuceneCommand command ) // { // this.commands.add( command ); // } // // boolean containsWrites() // { // return containsWrites; // } // // boolean isDeletion() // { // return commands.size() == 1 && commands.get( 0 ) instanceof DeleteCommand; // } // // void clear() // { // commands.clear(); // containsWrites = false; // } // // void incCounter( LuceneCommand command ) // { // if ( command.isConsideredNormalWriteCommand() ) // { // containsWrites = true; // } // } // // boolean isEmpty() // { // return commands.isEmpty(); // } // // boolean isRecovery() // { // return commands.get( 0 ).isRecovered(); // } // } // Path: src/main/java/org/neo4j/index/impl/lucene/CommitContext.java import java.util.HashMap; import java.util.Map; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexWriter; import org.neo4j.index.impl.lucene.LuceneTransaction.CommandList; /** * Copyright (c) 2002-2014 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.index.impl.lucene; /** * This presents a context for each {@link LuceneCommand} when they are * committing its data. */ class CommitContext { final LuceneDataSource dataSource; final IndexIdentifier identifier; final IndexType indexType; final Map<Long, DocumentContext> documents = new HashMap<Long, DocumentContext>();
final CommandList commandList;
apatry/neo4j-lucene4-index
src/test/java/org/neo4j/index/impl/lucene/CustomAnalyzer.java
// Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // public static final Version LUCENE_VERSION = Version.LUCENE_40;
import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.core.LowerCaseFilter; import org.apache.lucene.analysis.core.WhitespaceTokenizer; import java.io.Reader; import static org.neo4j.index.impl.lucene.LuceneDataSource.LUCENE_VERSION;
/** * Copyright (c) 2002-2014 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.index.impl.lucene; final class CustomAnalyzer extends Analyzer { static boolean called; @Override protected TokenStreamComponents createComponents( String fieldName, Reader reader ) { called = true;
// Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java // public static final Version LUCENE_VERSION = Version.LUCENE_40; // Path: src/test/java/org/neo4j/index/impl/lucene/CustomAnalyzer.java import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.core.LowerCaseFilter; import org.apache.lucene.analysis.core.WhitespaceTokenizer; import java.io.Reader; import static org.neo4j.index.impl.lucene.LuceneDataSource.LUCENE_VERSION; /** * Copyright (c) 2002-2014 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.index.impl.lucene; final class CustomAnalyzer extends Analyzer { static boolean called; @Override protected TokenStreamComponents createComponents( String fieldName, Reader reader ) { called = true;
Tokenizer source = new WhitespaceTokenizer( LUCENE_VERSION, reader );
apatry/neo4j-lucene4-index
src/main/java/org/neo4j/index/lucene/LuceneTimeline.java
// Path: src/main/java/org/neo4j/index/lucene/ValueContext.java // public static ValueContext numeric(Number value) // { // return new ValueContext(value).indexNumeric(); // }
import static org.apache.lucene.search.NumericRangeQuery.newLongRange; import static org.neo4j.index.lucene.ValueContext.numeric; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.graphdb.index.IndexManager; import java.util.Map; import static java.lang.Long.MAX_VALUE;
long end = endTimestampOrNull != null ? endTimestampOrNull : MAX_VALUE; return new QueryContext( newLongRange( FIELD, start, end, true, true ) ); } private QueryContext sort( QueryContext query, boolean reversed ) { return query.sort( new Sort( new SortField( FIELD, SortField.Type.LONG, reversed ) ) ); } @Override public T getLast() { return getSingle( true ); } @Override public T getFirst() { return getSingle( false ); } @Override public void remove( T entity, long timestamp ) { index.remove( entity, FIELD, timestamp ); } @Override public void add( T entity, long timestamp ) {
// Path: src/main/java/org/neo4j/index/lucene/ValueContext.java // public static ValueContext numeric(Number value) // { // return new ValueContext(value).indexNumeric(); // } // Path: src/main/java/org/neo4j/index/lucene/LuceneTimeline.java import static org.apache.lucene.search.NumericRangeQuery.newLongRange; import static org.neo4j.index.lucene.ValueContext.numeric; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.graphdb.index.IndexManager; import java.util.Map; import static java.lang.Long.MAX_VALUE; long end = endTimestampOrNull != null ? endTimestampOrNull : MAX_VALUE; return new QueryContext( newLongRange( FIELD, start, end, true, true ) ); } private QueryContext sort( QueryContext query, boolean reversed ) { return query.sort( new Sort( new SortField( FIELD, SortField.Type.LONG, reversed ) ) ); } @Override public T getLast() { return getSingle( true ); } @Override public T getFirst() { return getSingle( false ); } @Override public void remove( T entity, long timestamp ) { index.remove( entity, FIELD, timestamp ); } @Override public void add( T entity, long timestamp ) {
index.add( entity, FIELD, numeric( timestamp ) );
apatry/neo4j-lucene4-index
src/test/java/org/neo4j/index/impl/lucene/TestIndexDeletion.java
// Path: src/test/java/org/neo4j/index/Neo4jTestCase.java // public static <T> void assertContains( Collection<T> collection, // T... expectedItems ) // { // String collectionString = join( ", ", collection.toArray() ); // assertEquals( collectionString, expectedItems.length, // collection.size() ); // for ( T item : expectedItems ) // { // assertTrue( collection.contains( item ) ); // } // } // // Path: src/test/java/org/neo4j/index/impl/lucene/Contains.java // @Factory // public static <T> Contains<T> contains( T... expectedItems ) // { // return new Contains<T>( expectedItems ); // }
import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.test.ImpermanentGraphDatabase; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.neo4j.index.Neo4jTestCase.assertContains; import static org.neo4j.index.impl.lucene.Contains.contains; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass;
index.delete(); restartTx(); index = graphDb.index().forNodes( INDEX_NAME ); key = "key"; value = "my own value"; node = graphDb.createNode(); index.add( node, key, value ); workers = new ArrayList<WorkThread>(); } public void beginTx() { if ( tx == null ) { tx = graphDb.beginTx(); } } void restartTx() { finishTx( true ); beginTx(); } @Test public void shouldBeAbleToDeleteAndRecreateIndex() { restartTx();
// Path: src/test/java/org/neo4j/index/Neo4jTestCase.java // public static <T> void assertContains( Collection<T> collection, // T... expectedItems ) // { // String collectionString = join( ", ", collection.toArray() ); // assertEquals( collectionString, expectedItems.length, // collection.size() ); // for ( T item : expectedItems ) // { // assertTrue( collection.contains( item ) ); // } // } // // Path: src/test/java/org/neo4j/index/impl/lucene/Contains.java // @Factory // public static <T> Contains<T> contains( T... expectedItems ) // { // return new Contains<T>( expectedItems ); // } // Path: src/test/java/org/neo4j/index/impl/lucene/TestIndexDeletion.java import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.test.ImpermanentGraphDatabase; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.neo4j.index.Neo4jTestCase.assertContains; import static org.neo4j.index.impl.lucene.Contains.contains; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass; index.delete(); restartTx(); index = graphDb.index().forNodes( INDEX_NAME ); key = "key"; value = "my own value"; node = graphDb.createNode(); index.add( node, key, value ); workers = new ArrayList<WorkThread>(); } public void beginTx() { if ( tx == null ) { tx = graphDb.beginTx(); } } void restartTx() { finishTx( true ); beginTx(); } @Test public void shouldBeAbleToDeleteAndRecreateIndex() { restartTx();
assertContains( index.query( key, "own" ) );
apatry/neo4j-lucene4-index
src/test/java/org/neo4j/index/impl/lucene/TestIndexDeletion.java
// Path: src/test/java/org/neo4j/index/Neo4jTestCase.java // public static <T> void assertContains( Collection<T> collection, // T... expectedItems ) // { // String collectionString = join( ", ", collection.toArray() ); // assertEquals( collectionString, expectedItems.length, // collection.size() ); // for ( T item : expectedItems ) // { // assertTrue( collection.contains( item ) ); // } // } // // Path: src/test/java/org/neo4j/index/impl/lucene/Contains.java // @Factory // public static <T> Contains<T> contains( T... expectedItems ) // { // return new Contains<T>( expectedItems ); // }
import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.test.ImpermanentGraphDatabase; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.neo4j.index.Neo4jTestCase.assertContains; import static org.neo4j.index.impl.lucene.Contains.contains; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass;
firstTx.deleteIndex(); firstTx.commit(); try { secondTx.queryIndex(key, "some other value"); fail( "Should throw exception" ); } catch ( Exception e ) { /* Good */ } secondTx.rollback(); // Since $Before will start a tx, add a value and keep tx open and // workers will delete the index so this test will fail in @After // if we don't rollback this tx rollbackTx(); } @Test public void indexDeletesShouldNotByVisibleUntilCommit() throws Exception { commitTx(); WorkThread firstTx = createWorker( "First" ); WorkThread secondTx = createWorker( "Second" ); firstTx.beginTransaction(); firstTx.removeFromIndex( key, value ); IndexHits<Node> indexHits = secondTx.queryIndex( key, value );
// Path: src/test/java/org/neo4j/index/Neo4jTestCase.java // public static <T> void assertContains( Collection<T> collection, // T... expectedItems ) // { // String collectionString = join( ", ", collection.toArray() ); // assertEquals( collectionString, expectedItems.length, // collection.size() ); // for ( T item : expectedItems ) // { // assertTrue( collection.contains( item ) ); // } // } // // Path: src/test/java/org/neo4j/index/impl/lucene/Contains.java // @Factory // public static <T> Contains<T> contains( T... expectedItems ) // { // return new Contains<T>( expectedItems ); // } // Path: src/test/java/org/neo4j/index/impl/lucene/TestIndexDeletion.java import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.test.ImpermanentGraphDatabase; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.neo4j.index.Neo4jTestCase.assertContains; import static org.neo4j.index.impl.lucene.Contains.contains; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass; firstTx.deleteIndex(); firstTx.commit(); try { secondTx.queryIndex(key, "some other value"); fail( "Should throw exception" ); } catch ( Exception e ) { /* Good */ } secondTx.rollback(); // Since $Before will start a tx, add a value and keep tx open and // workers will delete the index so this test will fail in @After // if we don't rollback this tx rollbackTx(); } @Test public void indexDeletesShouldNotByVisibleUntilCommit() throws Exception { commitTx(); WorkThread firstTx = createWorker( "First" ); WorkThread secondTx = createWorker( "Second" ); firstTx.beginTransaction(); firstTx.removeFromIndex( key, value ); IndexHits<Node> indexHits = secondTx.queryIndex( key, value );
assertThat( indexHits, contains( node ) );
apatry/neo4j-lucene4-index
src/test/java/org/neo4j/index/impl/lucene/TestIndexNames.java
// Path: src/test/java/org/neo4j/index/Neo4jTestCase.java // public static <T> void assertContains( Collection<T> collection, // T... expectedItems ) // { // String collectionString = join( ", ", collection.toArray() ); // assertEquals( collectionString, expectedItems.length, // collection.size() ); // for ( T item : expectedItems ) // { // assertTrue( collection.contains( item ) ); // } // }
import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.index.Index; import org.neo4j.test.ImpermanentGraphDatabase; import static org.junit.Assert.assertEquals; import static org.neo4j.index.Neo4jTestCase.assertContains; import java.util.Arrays; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node;
{ if ( success ) { tx.success(); } tx.finish(); tx = null; } } public void beginTx() { if ( tx == null ) { tx = graphDb.beginTx(); } } void restartTx() { finishTx( true ); beginTx(); } @Test public void makeSureIndexNamesCanBeRead() { assertEquals( 0, graphDb.index().nodeIndexNames().length ); String name1 = "my-index-1"; Index<Node> nodeIndex1 = graphDb.index().forNodes( name1 );
// Path: src/test/java/org/neo4j/index/Neo4jTestCase.java // public static <T> void assertContains( Collection<T> collection, // T... expectedItems ) // { // String collectionString = join( ", ", collection.toArray() ); // assertEquals( collectionString, expectedItems.length, // collection.size() ); // for ( T item : expectedItems ) // { // assertTrue( collection.contains( item ) ); // } // } // Path: src/test/java/org/neo4j/index/impl/lucene/TestIndexNames.java import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.index.Index; import org.neo4j.test.ImpermanentGraphDatabase; import static org.junit.Assert.assertEquals; import static org.neo4j.index.Neo4jTestCase.assertContains; import java.util.Arrays; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; { if ( success ) { tx.success(); } tx.finish(); tx = null; } } public void beginTx() { if ( tx == null ) { tx = graphDb.beginTx(); } } void restartTx() { finishTx( true ); beginTx(); } @Test public void makeSureIndexNamesCanBeRead() { assertEquals( 0, graphDb.index().nodeIndexNames().length ); String name1 = "my-index-1"; Index<Node> nodeIndex1 = graphDb.index().forNodes( name1 );
assertContains( Arrays.asList( graphDb.index().nodeIndexNames() ), name1 );
apatry/neo4j-lucene4-index
src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java
// Path: src/main/java/org/neo4j/index/impl/lucene/MultipleBackupDeletionPolicy.java // static final String SNAPSHOT_ID = "backup";
import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.core.KeywordAnalyzer; import org.apache.lucene.analysis.core.LowerCaseFilter; import org.apache.lucene.analysis.core.WhitespaceTokenizer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.StringField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexCommit; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.SnapshotDeletionPolicy; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldCollector; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.Version; import org.neo4j.graphdb.DependencyResolver; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.graphdb.factory.GraphDatabaseSetting; import org.neo4j.graphdb.factory.GraphDatabaseSettings; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexManager; import org.neo4j.graphdb.index.RelationshipIndex; import org.neo4j.helpers.Pair; import org.neo4j.helpers.UTF8; import org.neo4j.helpers.collection.ClosableIterable; import org.neo4j.kernel.InternalAbstractGraphDatabase; import org.neo4j.kernel.TransactionInterceptorProviders; import org.neo4j.kernel.configuration.Config; import org.neo4j.kernel.impl.cache.LruCache; import org.neo4j.kernel.impl.index.IndexProviderStore; import org.neo4j.kernel.impl.index.IndexStore; import org.neo4j.kernel.impl.nioneo.store.FileSystemAbstraction; import org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource; import org.neo4j.kernel.impl.transaction.xaframework.LogBackedXaDataSource; import org.neo4j.kernel.impl.transaction.xaframework.TransactionInterceptorProvider; import org.neo4j.kernel.impl.transaction.xaframework.XaCommand; import org.neo4j.kernel.impl.transaction.xaframework.XaCommandFactory; import org.neo4j.kernel.impl.transaction.xaframework.XaConnection; import org.neo4j.kernel.impl.transaction.xaframework.XaContainer; import org.neo4j.kernel.impl.transaction.xaframework.XaDataSource; import org.neo4j.kernel.impl.transaction.xaframework.XaFactory; import org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog; import org.neo4j.kernel.impl.transaction.xaframework.XaTransaction; import org.neo4j.kernel.impl.transaction.xaframework.XaTransactionFactory; import java.io.File; import java.io.IOException; import java.io.Reader; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantReadWriteLock; import static org.neo4j.index.impl.lucene.MultipleBackupDeletionPolicy.SNAPSHOT_ID; import static org.neo4j.kernel.impl.nioneo.store.NeoStore.versionStringToLong;
return providerStore.getLastCommittedTx(); } @Override public void setLastCommittedTxId( long txId ) { providerStore.setLastCommittedTx( txId ); } @Override public XaContainer getXaContainer() { return this.xaContainer; } @SuppressWarnings( "unchecked" ) @Override public ClosableIterable<File> listStoreFiles( boolean includeLogicalLogs ) throws IOException { // Never include logical logs since they are of little importance final Collection<File> files = new ArrayList<File>(); final Collection<SnapshotDeletionPolicy> snapshots = new ArrayList<SnapshotDeletionPolicy>(); makeSureAllIndexesAreInstantiated(); for ( IndexReference writer : getAllIndexes() ) { SnapshotDeletionPolicy deletionPolicy = (SnapshotDeletionPolicy) writer.getWriter().getConfig().getIndexDeletionPolicy(); File indexDirectory = getFileDirectory( baseStorePath, writer.getIdentifier() ); try { // Throws IllegalStateException if no commits yet
// Path: src/main/java/org/neo4j/index/impl/lucene/MultipleBackupDeletionPolicy.java // static final String SNAPSHOT_ID = "backup"; // Path: src/main/java/org/neo4j/index/impl/lucene/LuceneDataSource.java import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.core.KeywordAnalyzer; import org.apache.lucene.analysis.core.LowerCaseFilter; import org.apache.lucene.analysis.core.WhitespaceTokenizer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.StringField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexCommit; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.SnapshotDeletionPolicy; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldCollector; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.Version; import org.neo4j.graphdb.DependencyResolver; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.graphdb.factory.GraphDatabaseSetting; import org.neo4j.graphdb.factory.GraphDatabaseSettings; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexManager; import org.neo4j.graphdb.index.RelationshipIndex; import org.neo4j.helpers.Pair; import org.neo4j.helpers.UTF8; import org.neo4j.helpers.collection.ClosableIterable; import org.neo4j.kernel.InternalAbstractGraphDatabase; import org.neo4j.kernel.TransactionInterceptorProviders; import org.neo4j.kernel.configuration.Config; import org.neo4j.kernel.impl.cache.LruCache; import org.neo4j.kernel.impl.index.IndexProviderStore; import org.neo4j.kernel.impl.index.IndexStore; import org.neo4j.kernel.impl.nioneo.store.FileSystemAbstraction; import org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource; import org.neo4j.kernel.impl.transaction.xaframework.LogBackedXaDataSource; import org.neo4j.kernel.impl.transaction.xaframework.TransactionInterceptorProvider; import org.neo4j.kernel.impl.transaction.xaframework.XaCommand; import org.neo4j.kernel.impl.transaction.xaframework.XaCommandFactory; import org.neo4j.kernel.impl.transaction.xaframework.XaConnection; import org.neo4j.kernel.impl.transaction.xaframework.XaContainer; import org.neo4j.kernel.impl.transaction.xaframework.XaDataSource; import org.neo4j.kernel.impl.transaction.xaframework.XaFactory; import org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog; import org.neo4j.kernel.impl.transaction.xaframework.XaTransaction; import org.neo4j.kernel.impl.transaction.xaframework.XaTransactionFactory; import java.io.File; import java.io.IOException; import java.io.Reader; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantReadWriteLock; import static org.neo4j.index.impl.lucene.MultipleBackupDeletionPolicy.SNAPSHOT_ID; import static org.neo4j.kernel.impl.nioneo.store.NeoStore.versionStringToLong; return providerStore.getLastCommittedTx(); } @Override public void setLastCommittedTxId( long txId ) { providerStore.setLastCommittedTx( txId ); } @Override public XaContainer getXaContainer() { return this.xaContainer; } @SuppressWarnings( "unchecked" ) @Override public ClosableIterable<File> listStoreFiles( boolean includeLogicalLogs ) throws IOException { // Never include logical logs since they are of little importance final Collection<File> files = new ArrayList<File>(); final Collection<SnapshotDeletionPolicy> snapshots = new ArrayList<SnapshotDeletionPolicy>(); makeSureAllIndexesAreInstantiated(); for ( IndexReference writer : getAllIndexes() ) { SnapshotDeletionPolicy deletionPolicy = (SnapshotDeletionPolicy) writer.getWriter().getConfig().getIndexDeletionPolicy(); File indexDirectory = getFileDirectory( baseStorePath, writer.getIdentifier() ); try { // Throws IllegalStateException if no commits yet
IndexCommit commit = deletionPolicy.snapshot( SNAPSHOT_ID );
alexvoronov/geonetworking
src/main/java/net/gcdc/plugtestcms4/DUTTableModel.java
// Path: src/main/java/net/gcdc/plugtestcms4/ping/PingStatus.java // public enum PingStatus // { // UNKNOWN, // READY, // NOT_READY // }
import java.util.List; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; import net.gcdc.plugtestcms4.ping.PingStatus;
@Override public int getColumnCount () { return 10; } @Override public Class<?> getColumnClass (int columnIndex) { if (columnIndex < 0 || columnIndex >= getColumnCount ()) return null; if (columnIndex == 0) return Boolean.class; if (columnIndex == 1) return String.class; if (columnIndex == 2) return String.class; if (columnIndex == 3) return String.class; if (columnIndex == 4) return String.class; if (columnIndex == 5) return Boolean.class; if (columnIndex == 6) return Integer.class; if (columnIndex == 7) return Boolean.class; if (columnIndex == 8) return Integer.class; if (columnIndex == 9)
// Path: src/main/java/net/gcdc/plugtestcms4/ping/PingStatus.java // public enum PingStatus // { // UNKNOWN, // READY, // NOT_READY // } // Path: src/main/java/net/gcdc/plugtestcms4/DUTTableModel.java import java.util.List; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; import net.gcdc.plugtestcms4.ping.PingStatus; @Override public int getColumnCount () { return 10; } @Override public Class<?> getColumnClass (int columnIndex) { if (columnIndex < 0 || columnIndex >= getColumnCount ()) return null; if (columnIndex == 0) return Boolean.class; if (columnIndex == 1) return String.class; if (columnIndex == 2) return String.class; if (columnIndex == 3) return String.class; if (columnIndex == 4) return String.class; if (columnIndex == 5) return Boolean.class; if (columnIndex == 6) return Integer.class; if (columnIndex == 7) return Boolean.class; if (columnIndex == 8) return Integer.class; if (columnIndex == 9)
return PingStatus.class;
alexvoronov/geonetworking
src/test/java/net/gcdc/geonetworking/UdpDuplicatorTest.java
// Path: src/main/java/net/gcdc/UdpDuplicator.java // public class UdpDuplicator { // // private static final Logger LOGGER = LoggerFactory.getLogger(UdpDuplicator.class); // // private class Client implements Runnable { // public final int localPort; // public final SocketAddress remoteAddress; // public final DatagramSocket socket; // // public Client(int localPort, SocketAddress remoteAddress) throws SocketException { // this.localPort = localPort; // this.remoteAddress = remoteAddress; // this.socket = new DatagramSocket(this.localPort); // } // // public void send(byte[] payload) throws IOException { // socket.send(new DatagramPacket(payload, payload.length, remoteAddress)); // } // // @Override // public void run() { // int length = 3000; // byte[] buffer = new byte[length]; // DatagramPacket packet = new DatagramPacket(buffer, length); // try { // while (true) { // socket.receive(packet); // byte[] payload = Arrays.copyOfRange(packet.getData(), 0, packet.getLength()); // sendAll(payload); // } // } catch (IOException e) { // // TODO Auto-generated catch block // LOGGER.info("packetsending or receiving error ", e); // } // } // } // // private final ArrayList<Client> clients = new ArrayList<>(); // // public UdpDuplicator() { // } // // public void sendAll(byte[] payload) throws IOException { // for (Client c : clients) { // c.send(payload); // } // } // // public void add(int localPort, SocketAddress remoteAddress) throws SocketException { // Client c = new Client(localPort, remoteAddress); // (new Thread(c)).start(); // clients.add(c); // } // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import net.gcdc.UdpDuplicator; import org.junit.Test;
package net.gcdc.geonetworking; public class UdpDuplicatorTest { @Test(timeout=3000) public void test() throws IOException, InterruptedException {
// Path: src/main/java/net/gcdc/UdpDuplicator.java // public class UdpDuplicator { // // private static final Logger LOGGER = LoggerFactory.getLogger(UdpDuplicator.class); // // private class Client implements Runnable { // public final int localPort; // public final SocketAddress remoteAddress; // public final DatagramSocket socket; // // public Client(int localPort, SocketAddress remoteAddress) throws SocketException { // this.localPort = localPort; // this.remoteAddress = remoteAddress; // this.socket = new DatagramSocket(this.localPort); // } // // public void send(byte[] payload) throws IOException { // socket.send(new DatagramPacket(payload, payload.length, remoteAddress)); // } // // @Override // public void run() { // int length = 3000; // byte[] buffer = new byte[length]; // DatagramPacket packet = new DatagramPacket(buffer, length); // try { // while (true) { // socket.receive(packet); // byte[] payload = Arrays.copyOfRange(packet.getData(), 0, packet.getLength()); // sendAll(payload); // } // } catch (IOException e) { // // TODO Auto-generated catch block // LOGGER.info("packetsending or receiving error ", e); // } // } // } // // private final ArrayList<Client> clients = new ArrayList<>(); // // public UdpDuplicator() { // } // // public void sendAll(byte[] payload) throws IOException { // for (Client c : clients) { // c.send(payload); // } // } // // public void add(int localPort, SocketAddress remoteAddress) throws SocketException { // Client c = new Client(localPort, remoteAddress); // (new Thread(c)).start(); // clients.add(c); // } // } // Path: src/test/java/net/gcdc/geonetworking/UdpDuplicatorTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import net.gcdc.UdpDuplicator; import org.junit.Test; package net.gcdc.geonetworking; public class UdpDuplicatorTest { @Test(timeout=3000) public void test() throws IOException, InterruptedException {
UdpDuplicator d = new UdpDuplicator();
alexvoronov/geonetworking
src/test/java/net/gcdc/geonetworking/BasicSocketTestOverUdp.java
// Path: src/main/java/net/gcdc/UdpDuplicator.java // public class UdpDuplicator { // // private static final Logger LOGGER = LoggerFactory.getLogger(UdpDuplicator.class); // // private class Client implements Runnable { // public final int localPort; // public final SocketAddress remoteAddress; // public final DatagramSocket socket; // // public Client(int localPort, SocketAddress remoteAddress) throws SocketException { // this.localPort = localPort; // this.remoteAddress = remoteAddress; // this.socket = new DatagramSocket(this.localPort); // } // // public void send(byte[] payload) throws IOException { // socket.send(new DatagramPacket(payload, payload.length, remoteAddress)); // } // // @Override // public void run() { // int length = 3000; // byte[] buffer = new byte[length]; // DatagramPacket packet = new DatagramPacket(buffer, length); // try { // while (true) { // socket.receive(packet); // byte[] payload = Arrays.copyOfRange(packet.getData(), 0, packet.getLength()); // sendAll(payload); // } // } catch (IOException e) { // // TODO Auto-generated catch block // LOGGER.info("packetsending or receiving error ", e); // } // } // } // // private final ArrayList<Client> clients = new ArrayList<>(); // // public UdpDuplicator() { // } // // public void sendAll(byte[] payload) throws IOException { // for (Client c : clients) { // c.send(payload); // } // } // // public void add(int localPort, SocketAddress remoteAddress) throws SocketException { // Client c = new Client(localPort, remoteAddress); // (new Thread(c)).start(); // clients.add(c); // } // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import net.gcdc.UdpDuplicator; import org.junit.Test; import org.threeten.bp.Instant;
package net.gcdc.geonetworking; public class BasicSocketTestOverUdp { @Test(timeout=3000) public void test() throws IOException, InterruptedException { int client1 = 4440; int server1 = 4441; int client2 = 4450; int server2 = 4451;
// Path: src/main/java/net/gcdc/UdpDuplicator.java // public class UdpDuplicator { // // private static final Logger LOGGER = LoggerFactory.getLogger(UdpDuplicator.class); // // private class Client implements Runnable { // public final int localPort; // public final SocketAddress remoteAddress; // public final DatagramSocket socket; // // public Client(int localPort, SocketAddress remoteAddress) throws SocketException { // this.localPort = localPort; // this.remoteAddress = remoteAddress; // this.socket = new DatagramSocket(this.localPort); // } // // public void send(byte[] payload) throws IOException { // socket.send(new DatagramPacket(payload, payload.length, remoteAddress)); // } // // @Override // public void run() { // int length = 3000; // byte[] buffer = new byte[length]; // DatagramPacket packet = new DatagramPacket(buffer, length); // try { // while (true) { // socket.receive(packet); // byte[] payload = Arrays.copyOfRange(packet.getData(), 0, packet.getLength()); // sendAll(payload); // } // } catch (IOException e) { // // TODO Auto-generated catch block // LOGGER.info("packetsending or receiving error ", e); // } // } // } // // private final ArrayList<Client> clients = new ArrayList<>(); // // public UdpDuplicator() { // } // // public void sendAll(byte[] payload) throws IOException { // for (Client c : clients) { // c.send(payload); // } // } // // public void add(int localPort, SocketAddress remoteAddress) throws SocketException { // Client c = new Client(localPort, remoteAddress); // (new Thread(c)).start(); // clients.add(c); // } // } // Path: src/test/java/net/gcdc/geonetworking/BasicSocketTestOverUdp.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import net.gcdc.UdpDuplicator; import org.junit.Test; import org.threeten.bp.Instant; package net.gcdc.geonetworking; public class BasicSocketTestOverUdp { @Test(timeout=3000) public void test() throws IOException, InterruptedException { int client1 = 4440; int server1 = 4441; int client2 = 4450; int server2 = 4451;
UdpDuplicator d = new UdpDuplicator();
alexvoronov/geonetworking
src/test/java/net/gcdc/geonetworking/AreaTest.java
// Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static byte[] areaParamToBytes(Position center, int distanceA, int distanceB, int degrees) { // int latBytes = (int) (center.lattitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // int lonBytes = (int) (center.longitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // // ByteBuffer expectedBuffer = getAreaByteBuffer(); // expectedBuffer.putInt(latBytes); // expectedBuffer.putInt(lonBytes); // expectedBuffer.putShort((short) distanceA); // expectedBuffer.putShort((short) distanceB); // expectedBuffer.putShort((short) degrees); // return expectedBuffer.array(); // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static void asBinaryString(byte[] bytes) { // for (byte b : bytes) { // System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1)); // } // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static ByteBuffer getAreaByteBuffer() { // return ByteBuffer.allocate(14); // }
import static net.gcdc.geonetworking.AreaTest.Support.areaParamToBytes; import static net.gcdc.geonetworking.AreaTest.Support.asBinaryString; import static net.gcdc.geonetworking.AreaTest.Support.getAreaByteBuffer; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.nio.ByteBuffer; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.Test;
} private void testAreaDistance(int distance) { Position center = new Position(51, 0); int degrees = 45; verifyArea(center, distance, distance, degrees); } private void testAreaPosition(int lat, int lon) { Position center = new Position(lat, lon); int distanceA = 100; int distanceB = 300; int degrees = 45; verifyArea(center, distanceA, distanceB, degrees); } private void verifyArea(Position center, int distanceA, int distanceB, int degrees) { Area rect = Area.rectangle(center, distanceA, distanceB, degrees); verifyAreaRectangleBytes(rect, center, distanceA, distanceB, degrees); verifyAreaRectangleReturnTypes(rect, center); verifyAreaRectangleString(rect, center, distanceA, distanceB, degrees); } private void verifyAreaRectangleReturnTypes(Area rect, Position center) { assertEquals(Area.Type.RECTANGLE, rect.type()); assertEquals(center, rect.center()); } private void verifyAreaRectangleBytes(Area rectangle, Position center, int distanceA, int distanceB, int degrees) {
// Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static byte[] areaParamToBytes(Position center, int distanceA, int distanceB, int degrees) { // int latBytes = (int) (center.lattitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // int lonBytes = (int) (center.longitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // // ByteBuffer expectedBuffer = getAreaByteBuffer(); // expectedBuffer.putInt(latBytes); // expectedBuffer.putInt(lonBytes); // expectedBuffer.putShort((short) distanceA); // expectedBuffer.putShort((short) distanceB); // expectedBuffer.putShort((short) degrees); // return expectedBuffer.array(); // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static void asBinaryString(byte[] bytes) { // for (byte b : bytes) { // System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1)); // } // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static ByteBuffer getAreaByteBuffer() { // return ByteBuffer.allocate(14); // } // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java import static net.gcdc.geonetworking.AreaTest.Support.areaParamToBytes; import static net.gcdc.geonetworking.AreaTest.Support.asBinaryString; import static net.gcdc.geonetworking.AreaTest.Support.getAreaByteBuffer; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.nio.ByteBuffer; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.Test; } private void testAreaDistance(int distance) { Position center = new Position(51, 0); int degrees = 45; verifyArea(center, distance, distance, degrees); } private void testAreaPosition(int lat, int lon) { Position center = new Position(lat, lon); int distanceA = 100; int distanceB = 300; int degrees = 45; verifyArea(center, distanceA, distanceB, degrees); } private void verifyArea(Position center, int distanceA, int distanceB, int degrees) { Area rect = Area.rectangle(center, distanceA, distanceB, degrees); verifyAreaRectangleBytes(rect, center, distanceA, distanceB, degrees); verifyAreaRectangleReturnTypes(rect, center); verifyAreaRectangleString(rect, center, distanceA, distanceB, degrees); } private void verifyAreaRectangleReturnTypes(Area rect, Position center) { assertEquals(Area.Type.RECTANGLE, rect.type()); assertEquals(center, rect.center()); } private void verifyAreaRectangleBytes(Area rectangle, Position center, int distanceA, int distanceB, int degrees) {
ByteBuffer actualByteBuffer = getAreaByteBuffer();
alexvoronov/geonetworking
src/test/java/net/gcdc/geonetworking/AreaTest.java
// Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static byte[] areaParamToBytes(Position center, int distanceA, int distanceB, int degrees) { // int latBytes = (int) (center.lattitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // int lonBytes = (int) (center.longitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // // ByteBuffer expectedBuffer = getAreaByteBuffer(); // expectedBuffer.putInt(latBytes); // expectedBuffer.putInt(lonBytes); // expectedBuffer.putShort((short) distanceA); // expectedBuffer.putShort((short) distanceB); // expectedBuffer.putShort((short) degrees); // return expectedBuffer.array(); // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static void asBinaryString(byte[] bytes) { // for (byte b : bytes) { // System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1)); // } // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static ByteBuffer getAreaByteBuffer() { // return ByteBuffer.allocate(14); // }
import static net.gcdc.geonetworking.AreaTest.Support.areaParamToBytes; import static net.gcdc.geonetworking.AreaTest.Support.asBinaryString; import static net.gcdc.geonetworking.AreaTest.Support.getAreaByteBuffer; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.nio.ByteBuffer; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.Test;
int degrees = 45; verifyArea(center, distance, distance, degrees); } private void testAreaPosition(int lat, int lon) { Position center = new Position(lat, lon); int distanceA = 100; int distanceB = 300; int degrees = 45; verifyArea(center, distanceA, distanceB, degrees); } private void verifyArea(Position center, int distanceA, int distanceB, int degrees) { Area rect = Area.rectangle(center, distanceA, distanceB, degrees); verifyAreaRectangleBytes(rect, center, distanceA, distanceB, degrees); verifyAreaRectangleReturnTypes(rect, center); verifyAreaRectangleString(rect, center, distanceA, distanceB, degrees); } private void verifyAreaRectangleReturnTypes(Area rect, Position center) { assertEquals(Area.Type.RECTANGLE, rect.type()); assertEquals(center, rect.center()); } private void verifyAreaRectangleBytes(Area rectangle, Position center, int distanceA, int distanceB, int degrees) { ByteBuffer actualByteBuffer = getAreaByteBuffer(); rectangle.putTo(actualByteBuffer); byte[] actual = actualByteBuffer.array();
// Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static byte[] areaParamToBytes(Position center, int distanceA, int distanceB, int degrees) { // int latBytes = (int) (center.lattitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // int lonBytes = (int) (center.longitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // // ByteBuffer expectedBuffer = getAreaByteBuffer(); // expectedBuffer.putInt(latBytes); // expectedBuffer.putInt(lonBytes); // expectedBuffer.putShort((short) distanceA); // expectedBuffer.putShort((short) distanceB); // expectedBuffer.putShort((short) degrees); // return expectedBuffer.array(); // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static void asBinaryString(byte[] bytes) { // for (byte b : bytes) { // System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1)); // } // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static ByteBuffer getAreaByteBuffer() { // return ByteBuffer.allocate(14); // } // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java import static net.gcdc.geonetworking.AreaTest.Support.areaParamToBytes; import static net.gcdc.geonetworking.AreaTest.Support.asBinaryString; import static net.gcdc.geonetworking.AreaTest.Support.getAreaByteBuffer; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.nio.ByteBuffer; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.Test; int degrees = 45; verifyArea(center, distance, distance, degrees); } private void testAreaPosition(int lat, int lon) { Position center = new Position(lat, lon); int distanceA = 100; int distanceB = 300; int degrees = 45; verifyArea(center, distanceA, distanceB, degrees); } private void verifyArea(Position center, int distanceA, int distanceB, int degrees) { Area rect = Area.rectangle(center, distanceA, distanceB, degrees); verifyAreaRectangleBytes(rect, center, distanceA, distanceB, degrees); verifyAreaRectangleReturnTypes(rect, center); verifyAreaRectangleString(rect, center, distanceA, distanceB, degrees); } private void verifyAreaRectangleReturnTypes(Area rect, Position center) { assertEquals(Area.Type.RECTANGLE, rect.type()); assertEquals(center, rect.center()); } private void verifyAreaRectangleBytes(Area rectangle, Position center, int distanceA, int distanceB, int degrees) { ByteBuffer actualByteBuffer = getAreaByteBuffer(); rectangle.putTo(actualByteBuffer); byte[] actual = actualByteBuffer.array();
byte[] expected = areaParamToBytes(center, distanceA, distanceB, degrees);
alexvoronov/geonetworking
src/test/java/net/gcdc/geonetworking/AreaTest.java
// Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static byte[] areaParamToBytes(Position center, int distanceA, int distanceB, int degrees) { // int latBytes = (int) (center.lattitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // int lonBytes = (int) (center.longitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // // ByteBuffer expectedBuffer = getAreaByteBuffer(); // expectedBuffer.putInt(latBytes); // expectedBuffer.putInt(lonBytes); // expectedBuffer.putShort((short) distanceA); // expectedBuffer.putShort((short) distanceB); // expectedBuffer.putShort((short) degrees); // return expectedBuffer.array(); // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static void asBinaryString(byte[] bytes) { // for (byte b : bytes) { // System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1)); // } // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static ByteBuffer getAreaByteBuffer() { // return ByteBuffer.allocate(14); // }
import static net.gcdc.geonetworking.AreaTest.Support.areaParamToBytes; import static net.gcdc.geonetworking.AreaTest.Support.asBinaryString; import static net.gcdc.geonetworking.AreaTest.Support.getAreaByteBuffer; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.nio.ByteBuffer; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.Test;
private void testAreaPosition(int lat, int lon) { Position center = new Position(lat, lon); int distanceA = 100; int distanceB = 300; int degrees = 45; verifyArea(center, distanceA, distanceB, degrees); } private void verifyArea(Position center, int distanceA, int distanceB, int degrees) { Area rect = Area.rectangle(center, distanceA, distanceB, degrees); verifyAreaRectangleBytes(rect, center, distanceA, distanceB, degrees); verifyAreaRectangleReturnTypes(rect, center); verifyAreaRectangleString(rect, center, distanceA, distanceB, degrees); } private void verifyAreaRectangleReturnTypes(Area rect, Position center) { assertEquals(Area.Type.RECTANGLE, rect.type()); assertEquals(center, rect.center()); } private void verifyAreaRectangleBytes(Area rectangle, Position center, int distanceA, int distanceB, int degrees) { ByteBuffer actualByteBuffer = getAreaByteBuffer(); rectangle.putTo(actualByteBuffer); byte[] actual = actualByteBuffer.array(); byte[] expected = areaParamToBytes(center, distanceA, distanceB, degrees); if (LOGGING) { System.out.println("Expected:");
// Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static byte[] areaParamToBytes(Position center, int distanceA, int distanceB, int degrees) { // int latBytes = (int) (center.lattitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // int lonBytes = (int) (center.longitudeDegrees() * TENTH_MICRODEGREE_MULTIPLIER); // // ByteBuffer expectedBuffer = getAreaByteBuffer(); // expectedBuffer.putInt(latBytes); // expectedBuffer.putInt(lonBytes); // expectedBuffer.putShort((short) distanceA); // expectedBuffer.putShort((short) distanceB); // expectedBuffer.putShort((short) degrees); // return expectedBuffer.array(); // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static void asBinaryString(byte[] bytes) { // for (byte b : bytes) { // System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1)); // } // } // // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java // static ByteBuffer getAreaByteBuffer() { // return ByteBuffer.allocate(14); // } // Path: src/test/java/net/gcdc/geonetworking/AreaTest.java import static net.gcdc.geonetworking.AreaTest.Support.areaParamToBytes; import static net.gcdc.geonetworking.AreaTest.Support.asBinaryString; import static net.gcdc.geonetworking.AreaTest.Support.getAreaByteBuffer; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.nio.ByteBuffer; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.Test; private void testAreaPosition(int lat, int lon) { Position center = new Position(lat, lon); int distanceA = 100; int distanceB = 300; int degrees = 45; verifyArea(center, distanceA, distanceB, degrees); } private void verifyArea(Position center, int distanceA, int distanceB, int degrees) { Area rect = Area.rectangle(center, distanceA, distanceB, degrees); verifyAreaRectangleBytes(rect, center, distanceA, distanceB, degrees); verifyAreaRectangleReturnTypes(rect, center); verifyAreaRectangleString(rect, center, distanceA, distanceB, degrees); } private void verifyAreaRectangleReturnTypes(Area rect, Position center) { assertEquals(Area.Type.RECTANGLE, rect.type()); assertEquals(center, rect.center()); } private void verifyAreaRectangleBytes(Area rectangle, Position center, int distanceA, int distanceB, int degrees) { ByteBuffer actualByteBuffer = getAreaByteBuffer(); rectangle.putTo(actualByteBuffer); byte[] actual = actualByteBuffer.array(); byte[] expected = areaParamToBytes(center, distanceA, distanceB, degrees); if (LOGGING) { System.out.println("Expected:");
asBinaryString(expected);
AdoptOpenJDK/mjprof
src/test/java/com/performizeit/mjprof/plugins/mappers/MergedCalleesTest.java
// Path: src/main/java/com/performizeit/mjprof/parser/ThreadDump.java // public class ThreadDump { // protected JStackHeader header; // ArrayList<ThreadInfo> stacks = new ArrayList<>(); // int JNIglobalReferences = -1; // // public static String JNI_GLOBAL_REFS = "JNI global references:"; // // public JStackHeader getHeader() { // return header; // } // // public ThreadDump(String stringRep) { // String[] splitTraces = stringRep.split("\n\""); // Assuming that thread stack trace starts with a new line followed by " // // header = new JStackHeader(splitTraces[0]); // for (int i = 1; i < splitTraces.length; i++) { // if (splitTraces[i].startsWith(JNI_GLOBAL_REFS)) { // try { // JNIglobalReferences = Integer.parseInt(splitTraces[i].substring(splitTraces[i].indexOf(":") + 2).trim()); // } catch (NumberFormatException e) { // // do nothing so we missed the JNI global references I do not know what to do with it. // } // // } else { // stacks.add(new ThreadInfo("\"" + splitTraces[i])); // } // } // } // // public ThreadDump() { // super(); // } // // public ArrayList<ThreadInfo> getStacks() { // return stacks; // } // // public void addThreadInfo(ThreadInfo ti) { // stacks.add(ti); // } // // public void setStacks(ArrayList<ThreadInfo> stacks) { // this.stacks = stacks; // } // // @Override // public String toString() { // StringBuilder s = new StringBuilder(); // s.append(header).append("\n\n"); // // for (ThreadInfo stack : stacks) { // s.append(stack.toString()).append("\n"); // } // // return s.toString(); // } // // // public void setHeader(String header) { // this.header = new JStackHeader(header); // } // // public void setHeader(JStackHeader header) { // this.header = header; // } // // public ArrayList<ThreadInfo> cloneStacks() { // ArrayList<ThreadInfo> newStcks = new ArrayList<>(); // for (ThreadInfo stk : getStacks()) { // newStcks.add(stk); // } // return newStcks; // } // // public int getJNIglobalReferences() { // return JNIglobalReferences; // } // // public void setJNIglobalReferences(int JNIglobalReferences) { // this.JNIglobalReferences = JNIglobalReferences; // } // }
import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import org.junit.Test; import com.performizeit.mjprof.parser.ThreadDump;
package com.performizeit.mjprof.plugins.mappers; public class MergedCalleesTest { @Test public void testName() throws Exception { MergedCallees g = new MergedCallees("org.eclipse.core.internal.jobs.WorkerPool.test"); // MergedCallees g = new MergedCallees("java.lang.Object.wait"); // MergedCallees g = new MergedCallees("org.eclipse.core.internal.jobs.WorkerPool.startJob"); // GroupByProp g = new GroupByProp("org.eclipse.core.internal.jobs.WorkerPool.test"); // ThreadDump dump = new ThreadDump(readFromFile("src/test/res/test1.txt"));
// Path: src/main/java/com/performizeit/mjprof/parser/ThreadDump.java // public class ThreadDump { // protected JStackHeader header; // ArrayList<ThreadInfo> stacks = new ArrayList<>(); // int JNIglobalReferences = -1; // // public static String JNI_GLOBAL_REFS = "JNI global references:"; // // public JStackHeader getHeader() { // return header; // } // // public ThreadDump(String stringRep) { // String[] splitTraces = stringRep.split("\n\""); // Assuming that thread stack trace starts with a new line followed by " // // header = new JStackHeader(splitTraces[0]); // for (int i = 1; i < splitTraces.length; i++) { // if (splitTraces[i].startsWith(JNI_GLOBAL_REFS)) { // try { // JNIglobalReferences = Integer.parseInt(splitTraces[i].substring(splitTraces[i].indexOf(":") + 2).trim()); // } catch (NumberFormatException e) { // // do nothing so we missed the JNI global references I do not know what to do with it. // } // // } else { // stacks.add(new ThreadInfo("\"" + splitTraces[i])); // } // } // } // // public ThreadDump() { // super(); // } // // public ArrayList<ThreadInfo> getStacks() { // return stacks; // } // // public void addThreadInfo(ThreadInfo ti) { // stacks.add(ti); // } // // public void setStacks(ArrayList<ThreadInfo> stacks) { // this.stacks = stacks; // } // // @Override // public String toString() { // StringBuilder s = new StringBuilder(); // s.append(header).append("\n\n"); // // for (ThreadInfo stack : stacks) { // s.append(stack.toString()).append("\n"); // } // // return s.toString(); // } // // // public void setHeader(String header) { // this.header = new JStackHeader(header); // } // // public void setHeader(JStackHeader header) { // this.header = header; // } // // public ArrayList<ThreadInfo> cloneStacks() { // ArrayList<ThreadInfo> newStcks = new ArrayList<>(); // for (ThreadInfo stk : getStacks()) { // newStcks.add(stk); // } // return newStcks; // } // // public int getJNIglobalReferences() { // return JNIglobalReferences; // } // // public void setJNIglobalReferences(int JNIglobalReferences) { // this.JNIglobalReferences = JNIglobalReferences; // } // } // Path: src/test/java/com/performizeit/mjprof/plugins/mappers/MergedCalleesTest.java import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import org.junit.Test; import com.performizeit.mjprof.parser.ThreadDump; package com.performizeit.mjprof.plugins.mappers; public class MergedCalleesTest { @Test public void testName() throws Exception { MergedCallees g = new MergedCallees("org.eclipse.core.internal.jobs.WorkerPool.test"); // MergedCallees g = new MergedCallees("java.lang.Object.wait"); // MergedCallees g = new MergedCallees("org.eclipse.core.internal.jobs.WorkerPool.startJob"); // GroupByProp g = new GroupByProp("org.eclipse.core.internal.jobs.WorkerPool.test"); // ThreadDump dump = new ThreadDump(readFromFile("src/test/res/test1.txt"));
ThreadDump dump = new ThreadDump(readFromFile("src/test/res/test2.txt"));
AdoptOpenJDK/mjprof
src/main/java/com/performizeit/mjprof/plugins/dataSource/JstackDataSourcePlugin.java
// Path: src/main/java/com/performizeit/mjprof/parser/ThreadDump.java // public class ThreadDump { // protected JStackHeader header; // ArrayList<ThreadInfo> stacks = new ArrayList<>(); // int JNIglobalReferences = -1; // // public static String JNI_GLOBAL_REFS = "JNI global references:"; // // public JStackHeader getHeader() { // return header; // } // // public ThreadDump(String stringRep) { // String[] splitTraces = stringRep.split("\n\""); // Assuming that thread stack trace starts with a new line followed by " // // header = new JStackHeader(splitTraces[0]); // for (int i = 1; i < splitTraces.length; i++) { // if (splitTraces[i].startsWith(JNI_GLOBAL_REFS)) { // try { // JNIglobalReferences = Integer.parseInt(splitTraces[i].substring(splitTraces[i].indexOf(":") + 2).trim()); // } catch (NumberFormatException e) { // // do nothing so we missed the JNI global references I do not know what to do with it. // } // // } else { // stacks.add(new ThreadInfo("\"" + splitTraces[i])); // } // } // } // // public ThreadDump() { // super(); // } // // public ArrayList<ThreadInfo> getStacks() { // return stacks; // } // // public void addThreadInfo(ThreadInfo ti) { // stacks.add(ti); // } // // public void setStacks(ArrayList<ThreadInfo> stacks) { // this.stacks = stacks; // } // // @Override // public String toString() { // StringBuilder s = new StringBuilder(); // s.append(header).append("\n\n"); // // for (ThreadInfo stack : stacks) { // s.append(stack.toString()).append("\n"); // } // // return s.toString(); // } // // // public void setHeader(String header) { // this.header = new JStackHeader(header); // } // // public void setHeader(JStackHeader header) { // this.header = header; // } // // public ArrayList<ThreadInfo> cloneStacks() { // ArrayList<ThreadInfo> newStcks = new ArrayList<>(); // for (ThreadInfo stk : getStacks()) { // newStcks.add(stk); // } // return newStcks; // } // // public int getJNIglobalReferences() { // return JNIglobalReferences; // } // // public void setJNIglobalReferences(int JNIglobalReferences) { // this.JNIglobalReferences = JNIglobalReferences; // } // } // // Path: src/main/java/com/performizeit/plumbing/GeneratorHandler.java // public interface GeneratorHandler<E> { // E generate(); // boolean isDone(); // void sleepBetweenIteration(); // }
import com.performizeit.mjprof.plugin.types.DataSource; import com.performizeit.mjprof.api.Plugin; import com.performizeit.mjprof.api.Param; import com.performizeit.mjprof.parser.ThreadDump; import com.performizeit.plumbing.GeneratorHandler; import com.sun.tools.attach.VirtualMachine; import com.sun.tools.attach.AttachNotSupportedException; import sun.jvmstat.monitor.*; import sun.tools.attach.HotSpotVirtualMachine; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.util.ArrayList;
package com.performizeit.mjprof.plugins.dataSource; @SuppressWarnings("unused") @Plugin(name = "jstack", params = {@Param(type = String.class, value = "pid|mainClassName"), @Param(type = int.class, value = "count", optional = true, defaultValue = "1"), @Param(type = int.class, value = "sleep", optional = true, defaultValue = "5000")}, description = "Generates dumps using jstack")
// Path: src/main/java/com/performizeit/mjprof/parser/ThreadDump.java // public class ThreadDump { // protected JStackHeader header; // ArrayList<ThreadInfo> stacks = new ArrayList<>(); // int JNIglobalReferences = -1; // // public static String JNI_GLOBAL_REFS = "JNI global references:"; // // public JStackHeader getHeader() { // return header; // } // // public ThreadDump(String stringRep) { // String[] splitTraces = stringRep.split("\n\""); // Assuming that thread stack trace starts with a new line followed by " // // header = new JStackHeader(splitTraces[0]); // for (int i = 1; i < splitTraces.length; i++) { // if (splitTraces[i].startsWith(JNI_GLOBAL_REFS)) { // try { // JNIglobalReferences = Integer.parseInt(splitTraces[i].substring(splitTraces[i].indexOf(":") + 2).trim()); // } catch (NumberFormatException e) { // // do nothing so we missed the JNI global references I do not know what to do with it. // } // // } else { // stacks.add(new ThreadInfo("\"" + splitTraces[i])); // } // } // } // // public ThreadDump() { // super(); // } // // public ArrayList<ThreadInfo> getStacks() { // return stacks; // } // // public void addThreadInfo(ThreadInfo ti) { // stacks.add(ti); // } // // public void setStacks(ArrayList<ThreadInfo> stacks) { // this.stacks = stacks; // } // // @Override // public String toString() { // StringBuilder s = new StringBuilder(); // s.append(header).append("\n\n"); // // for (ThreadInfo stack : stacks) { // s.append(stack.toString()).append("\n"); // } // // return s.toString(); // } // // // public void setHeader(String header) { // this.header = new JStackHeader(header); // } // // public void setHeader(JStackHeader header) { // this.header = header; // } // // public ArrayList<ThreadInfo> cloneStacks() { // ArrayList<ThreadInfo> newStcks = new ArrayList<>(); // for (ThreadInfo stk : getStacks()) { // newStcks.add(stk); // } // return newStcks; // } // // public int getJNIglobalReferences() { // return JNIglobalReferences; // } // // public void setJNIglobalReferences(int JNIglobalReferences) { // this.JNIglobalReferences = JNIglobalReferences; // } // } // // Path: src/main/java/com/performizeit/plumbing/GeneratorHandler.java // public interface GeneratorHandler<E> { // E generate(); // boolean isDone(); // void sleepBetweenIteration(); // } // Path: src/main/java/com/performizeit/mjprof/plugins/dataSource/JstackDataSourcePlugin.java import com.performizeit.mjprof.plugin.types.DataSource; import com.performizeit.mjprof.api.Plugin; import com.performizeit.mjprof.api.Param; import com.performizeit.mjprof.parser.ThreadDump; import com.performizeit.plumbing.GeneratorHandler; import com.sun.tools.attach.VirtualMachine; import com.sun.tools.attach.AttachNotSupportedException; import sun.jvmstat.monitor.*; import sun.tools.attach.HotSpotVirtualMachine; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.util.ArrayList; package com.performizeit.mjprof.plugins.dataSource; @SuppressWarnings("unused") @Plugin(name = "jstack", params = {@Param(type = String.class, value = "pid|mainClassName"), @Param(type = int.class, value = "count", optional = true, defaultValue = "1"), @Param(type = int.class, value = "sleep", optional = true, defaultValue = "5000")}, description = "Generates dumps using jstack")
public class JstackDataSourcePlugin implements DataSource, GeneratorHandler<ThreadDump> {
AdoptOpenJDK/mjprof
src/main/java/com/performizeit/mjprof/plugins/dataSource/JstackDataSourcePlugin.java
// Path: src/main/java/com/performizeit/mjprof/parser/ThreadDump.java // public class ThreadDump { // protected JStackHeader header; // ArrayList<ThreadInfo> stacks = new ArrayList<>(); // int JNIglobalReferences = -1; // // public static String JNI_GLOBAL_REFS = "JNI global references:"; // // public JStackHeader getHeader() { // return header; // } // // public ThreadDump(String stringRep) { // String[] splitTraces = stringRep.split("\n\""); // Assuming that thread stack trace starts with a new line followed by " // // header = new JStackHeader(splitTraces[0]); // for (int i = 1; i < splitTraces.length; i++) { // if (splitTraces[i].startsWith(JNI_GLOBAL_REFS)) { // try { // JNIglobalReferences = Integer.parseInt(splitTraces[i].substring(splitTraces[i].indexOf(":") + 2).trim()); // } catch (NumberFormatException e) { // // do nothing so we missed the JNI global references I do not know what to do with it. // } // // } else { // stacks.add(new ThreadInfo("\"" + splitTraces[i])); // } // } // } // // public ThreadDump() { // super(); // } // // public ArrayList<ThreadInfo> getStacks() { // return stacks; // } // // public void addThreadInfo(ThreadInfo ti) { // stacks.add(ti); // } // // public void setStacks(ArrayList<ThreadInfo> stacks) { // this.stacks = stacks; // } // // @Override // public String toString() { // StringBuilder s = new StringBuilder(); // s.append(header).append("\n\n"); // // for (ThreadInfo stack : stacks) { // s.append(stack.toString()).append("\n"); // } // // return s.toString(); // } // // // public void setHeader(String header) { // this.header = new JStackHeader(header); // } // // public void setHeader(JStackHeader header) { // this.header = header; // } // // public ArrayList<ThreadInfo> cloneStacks() { // ArrayList<ThreadInfo> newStcks = new ArrayList<>(); // for (ThreadInfo stk : getStacks()) { // newStcks.add(stk); // } // return newStcks; // } // // public int getJNIglobalReferences() { // return JNIglobalReferences; // } // // public void setJNIglobalReferences(int JNIglobalReferences) { // this.JNIglobalReferences = JNIglobalReferences; // } // } // // Path: src/main/java/com/performizeit/plumbing/GeneratorHandler.java // public interface GeneratorHandler<E> { // E generate(); // boolean isDone(); // void sleepBetweenIteration(); // }
import com.performizeit.mjprof.plugin.types.DataSource; import com.performizeit.mjprof.api.Plugin; import com.performizeit.mjprof.api.Param; import com.performizeit.mjprof.parser.ThreadDump; import com.performizeit.plumbing.GeneratorHandler; import com.sun.tools.attach.VirtualMachine; import com.sun.tools.attach.AttachNotSupportedException; import sun.jvmstat.monitor.*; import sun.tools.attach.HotSpotVirtualMachine; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.util.ArrayList;
package com.performizeit.mjprof.plugins.dataSource; @SuppressWarnings("unused") @Plugin(name = "jstack", params = {@Param(type = String.class, value = "pid|mainClassName"), @Param(type = int.class, value = "count", optional = true, defaultValue = "1"), @Param(type = int.class, value = "sleep", optional = true, defaultValue = "5000")}, description = "Generates dumps using jstack")
// Path: src/main/java/com/performizeit/mjprof/parser/ThreadDump.java // public class ThreadDump { // protected JStackHeader header; // ArrayList<ThreadInfo> stacks = new ArrayList<>(); // int JNIglobalReferences = -1; // // public static String JNI_GLOBAL_REFS = "JNI global references:"; // // public JStackHeader getHeader() { // return header; // } // // public ThreadDump(String stringRep) { // String[] splitTraces = stringRep.split("\n\""); // Assuming that thread stack trace starts with a new line followed by " // // header = new JStackHeader(splitTraces[0]); // for (int i = 1; i < splitTraces.length; i++) { // if (splitTraces[i].startsWith(JNI_GLOBAL_REFS)) { // try { // JNIglobalReferences = Integer.parseInt(splitTraces[i].substring(splitTraces[i].indexOf(":") + 2).trim()); // } catch (NumberFormatException e) { // // do nothing so we missed the JNI global references I do not know what to do with it. // } // // } else { // stacks.add(new ThreadInfo("\"" + splitTraces[i])); // } // } // } // // public ThreadDump() { // super(); // } // // public ArrayList<ThreadInfo> getStacks() { // return stacks; // } // // public void addThreadInfo(ThreadInfo ti) { // stacks.add(ti); // } // // public void setStacks(ArrayList<ThreadInfo> stacks) { // this.stacks = stacks; // } // // @Override // public String toString() { // StringBuilder s = new StringBuilder(); // s.append(header).append("\n\n"); // // for (ThreadInfo stack : stacks) { // s.append(stack.toString()).append("\n"); // } // // return s.toString(); // } // // // public void setHeader(String header) { // this.header = new JStackHeader(header); // } // // public void setHeader(JStackHeader header) { // this.header = header; // } // // public ArrayList<ThreadInfo> cloneStacks() { // ArrayList<ThreadInfo> newStcks = new ArrayList<>(); // for (ThreadInfo stk : getStacks()) { // newStcks.add(stk); // } // return newStcks; // } // // public int getJNIglobalReferences() { // return JNIglobalReferences; // } // // public void setJNIglobalReferences(int JNIglobalReferences) { // this.JNIglobalReferences = JNIglobalReferences; // } // } // // Path: src/main/java/com/performizeit/plumbing/GeneratorHandler.java // public interface GeneratorHandler<E> { // E generate(); // boolean isDone(); // void sleepBetweenIteration(); // } // Path: src/main/java/com/performizeit/mjprof/plugins/dataSource/JstackDataSourcePlugin.java import com.performizeit.mjprof.plugin.types.DataSource; import com.performizeit.mjprof.api.Plugin; import com.performizeit.mjprof.api.Param; import com.performizeit.mjprof.parser.ThreadDump; import com.performizeit.plumbing.GeneratorHandler; import com.sun.tools.attach.VirtualMachine; import com.sun.tools.attach.AttachNotSupportedException; import sun.jvmstat.monitor.*; import sun.tools.attach.HotSpotVirtualMachine; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.util.ArrayList; package com.performizeit.mjprof.plugins.dataSource; @SuppressWarnings("unused") @Plugin(name = "jstack", params = {@Param(type = String.class, value = "pid|mainClassName"), @Param(type = int.class, value = "count", optional = true, defaultValue = "1"), @Param(type = int.class, value = "sleep", optional = true, defaultValue = "5000")}, description = "Generates dumps using jstack")
public class JstackDataSourcePlugin implements DataSource, GeneratorHandler<ThreadDump> {
AdoptOpenJDK/mjprof
src/test/java/com/performizeit/mjprof/MJProfTest.java
// Path: src/main/java/com/performizeit/mjprof/monads/MJStep.java // public class MJStep { // String stepName; // List<String> stepArgs; // // public MJStep(String stepString) { // // stepArgs = new ArrayList<String>(); // // if (!stepString.contains("/")) { // stepName = stepString; // } else { // int firstSlash = stepString.indexOf('/'); // int lastSlash = stepString.lastIndexOf('/'); // stepName = stepString.substring(0, firstSlash); // if (firstSlash < lastSlash) { // String params = stepString.substring(firstSlash + 1, lastSlash); // if (params.trim().length() > 0) { // params = params.replaceAll(",,", "__DOUBLE_COMMA__xxxxxxx"); // for (String q : params.split(",")) { // addStepArg(q.replaceAll("__DOUBLE_COMMA__xxxxxxx", ",")); // } // } // } // // } // } // // public String getStepName() { // return stepName; // } // // public List<String> getStepArgs() { // return stepArgs; // } // // public String getStepArg(int i) { // return stepArgs.get(i); // } // // public void addStepArg(String arg) { // stepArgs.add(arg); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(stepName).append("/"); // for (String stepV : stepArgs) { // sb.append(stepV).append(","); // } // sb.append("/"); // return sb.toString(); // } // }
import com.performizeit.mjprof.monads.MJStep; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull;
/* This file is part of mjprof. mjprof is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mjprof is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with mjprof. If not, see <http://www.gnu.org/licenses/>. */ package com.performizeit.mjprof; public class MJProfTest { @Test public void argWhichContainsPeriod() throws Exception { String args = "contains/key.k,val.val/";
// Path: src/main/java/com/performizeit/mjprof/monads/MJStep.java // public class MJStep { // String stepName; // List<String> stepArgs; // // public MJStep(String stepString) { // // stepArgs = new ArrayList<String>(); // // if (!stepString.contains("/")) { // stepName = stepString; // } else { // int firstSlash = stepString.indexOf('/'); // int lastSlash = stepString.lastIndexOf('/'); // stepName = stepString.substring(0, firstSlash); // if (firstSlash < lastSlash) { // String params = stepString.substring(firstSlash + 1, lastSlash); // if (params.trim().length() > 0) { // params = params.replaceAll(",,", "__DOUBLE_COMMA__xxxxxxx"); // for (String q : params.split(",")) { // addStepArg(q.replaceAll("__DOUBLE_COMMA__xxxxxxx", ",")); // } // } // } // // } // } // // public String getStepName() { // return stepName; // } // // public List<String> getStepArgs() { // return stepArgs; // } // // public String getStepArg(int i) { // return stepArgs.get(i); // } // // public void addStepArg(String arg) { // stepArgs.add(arg); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(stepName).append("/"); // for (String stepV : stepArgs) { // sb.append(stepV).append(","); // } // sb.append("/"); // return sb.toString(); // } // } // Path: src/test/java/com/performizeit/mjprof/MJProfTest.java import com.performizeit.mjprof.monads.MJStep; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /* This file is part of mjprof. mjprof is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mjprof is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with mjprof. If not, see <http://www.gnu.org/licenses/>. */ package com.performizeit.mjprof; public class MJProfTest { @Test public void argWhichContainsPeriod() throws Exception { String args = "contains/key.k,val.val/";
ArrayList<MJStep> steps = MJProf.parseCommandLine(args);
SeaCloudsEU/SeaCloudsPlatform
planner/core/src/main/java/eu/seaclouds/platform/planner/core/application/ApplicationFacadeDecoratorApplicator.java
// Path: planner/core/src/main/java/eu/seaclouds/platform/planner/core/application/decorators/SeaCloudsMonitoringInitializerPolicyDecorator.java // public class SeaCloudsMonitoringInitializerPolicyDecorator implements ApplicationFacadeDecorator { // // static Logger log = LoggerFactory.getLogger(SeaCloudsMonitoringInitializerPolicyDecorator.class); // // public static final String SEACLOUDS_APPLICATION_CONFIGURATION_POLICY = // "configuration"; // public static final String SEACLOUDS_MONITORING_POLICY = // "eu.seaclouds.policy.SeaCloudsMonitoringInitializationPolicies"; // public static final String SEACLOUDS_DC_ENDPOINT = "seacloudsdc.endpoint"; // public static final String TARGET_NODES = "targetEntities"; // // private static final String TARGET_PROPERTY = "language"; // // private ApplicationFacade applicationFacade; // private DamGeneratorConfigBag configBag; // // @Override // public void apply(ApplicationFacade applicationFacade) { // this.applicationFacade = applicationFacade; // configBag = applicationFacade.getConfigBag(); // // addSeaCloudsMonitoringGroup(); // } // // private void addSeaCloudsMonitoringGroup() { // Map<String, Object> policyGroupValue = getPolicyGroupValues(); // // applicationFacade.addGroup( // DamGenerator.SEACLOUDS_MONITORING_INITIALIZATION, // policyGroupValue); // } // // public Map<String, Object> getPolicyGroupValues() { // // Map<String, Object> seaCloudsPolicyConfiguration = MutableMap.of(); // seaCloudsPolicyConfiguration.put(DamGenerator.TYPE, SEACLOUDS_MONITORING_POLICY); // seaCloudsPolicyConfiguration.put(SEACLOUDS_DC_ENDPOINT, configBag.getSeacloudsDcEndPoint()); // seaCloudsPolicyConfiguration.put(TARGET_NODES, // applicationFacade.filterNodeTemplatesByPropertyAndValues(TARGET_PROPERTY, getAllowedTargetValues())); // // Map<String, Object> seaCloudsPolicy = MutableMap.of(); // seaCloudsPolicy.put(SEACLOUDS_APPLICATION_CONFIGURATION_POLICY, seaCloudsPolicyConfiguration); // // Map<String, Object> seaCloudsApplicationGroup = MutableMap.of(); // seaCloudsApplicationGroup.put(DamGenerator.MEMBERS, ImmutableList.of()); // seaCloudsApplicationGroup.put(DamGenerator.POLICIES, ImmutableList.of(seaCloudsPolicy)); // // return seaCloudsApplicationGroup; // } // // private List<Object> getAllowedTargetValues(){ // return ImmutableList.<Object>of("JAVA", "PHP"); // } // // // // // }
import eu.seaclouds.platform.planner.core.application.decorators.MissingPolicyTypesDecorator; import eu.seaclouds.platform.planner.core.application.decorators.MonitoringInformationDecorator; import eu.seaclouds.platform.planner.core.application.decorators.SeaCloudsManagementPolicyDecorator; import eu.seaclouds.platform.planner.core.application.decorators.SeaCloudsMonitoringInitializerPolicyDecorator; import eu.seaclouds.platform.planner.core.application.decorators.SlaInformationDecorator;
package eu.seaclouds.platform.planner.core.application; public class ApplicationFacadeDecoratorApplicator { public void applyDecorators(ApplicationFacade applicationFacade) { new MonitoringInformationDecorator().apply(applicationFacade); new SlaInformationDecorator().apply(applicationFacade); new SeaCloudsManagementPolicyDecorator().apply(applicationFacade);
// Path: planner/core/src/main/java/eu/seaclouds/platform/planner/core/application/decorators/SeaCloudsMonitoringInitializerPolicyDecorator.java // public class SeaCloudsMonitoringInitializerPolicyDecorator implements ApplicationFacadeDecorator { // // static Logger log = LoggerFactory.getLogger(SeaCloudsMonitoringInitializerPolicyDecorator.class); // // public static final String SEACLOUDS_APPLICATION_CONFIGURATION_POLICY = // "configuration"; // public static final String SEACLOUDS_MONITORING_POLICY = // "eu.seaclouds.policy.SeaCloudsMonitoringInitializationPolicies"; // public static final String SEACLOUDS_DC_ENDPOINT = "seacloudsdc.endpoint"; // public static final String TARGET_NODES = "targetEntities"; // // private static final String TARGET_PROPERTY = "language"; // // private ApplicationFacade applicationFacade; // private DamGeneratorConfigBag configBag; // // @Override // public void apply(ApplicationFacade applicationFacade) { // this.applicationFacade = applicationFacade; // configBag = applicationFacade.getConfigBag(); // // addSeaCloudsMonitoringGroup(); // } // // private void addSeaCloudsMonitoringGroup() { // Map<String, Object> policyGroupValue = getPolicyGroupValues(); // // applicationFacade.addGroup( // DamGenerator.SEACLOUDS_MONITORING_INITIALIZATION, // policyGroupValue); // } // // public Map<String, Object> getPolicyGroupValues() { // // Map<String, Object> seaCloudsPolicyConfiguration = MutableMap.of(); // seaCloudsPolicyConfiguration.put(DamGenerator.TYPE, SEACLOUDS_MONITORING_POLICY); // seaCloudsPolicyConfiguration.put(SEACLOUDS_DC_ENDPOINT, configBag.getSeacloudsDcEndPoint()); // seaCloudsPolicyConfiguration.put(TARGET_NODES, // applicationFacade.filterNodeTemplatesByPropertyAndValues(TARGET_PROPERTY, getAllowedTargetValues())); // // Map<String, Object> seaCloudsPolicy = MutableMap.of(); // seaCloudsPolicy.put(SEACLOUDS_APPLICATION_CONFIGURATION_POLICY, seaCloudsPolicyConfiguration); // // Map<String, Object> seaCloudsApplicationGroup = MutableMap.of(); // seaCloudsApplicationGroup.put(DamGenerator.MEMBERS, ImmutableList.of()); // seaCloudsApplicationGroup.put(DamGenerator.POLICIES, ImmutableList.of(seaCloudsPolicy)); // // return seaCloudsApplicationGroup; // } // // private List<Object> getAllowedTargetValues(){ // return ImmutableList.<Object>of("JAVA", "PHP"); // } // // // // // } // Path: planner/core/src/main/java/eu/seaclouds/platform/planner/core/application/ApplicationFacadeDecoratorApplicator.java import eu.seaclouds.platform.planner.core.application.decorators.MissingPolicyTypesDecorator; import eu.seaclouds.platform.planner.core.application.decorators.MonitoringInformationDecorator; import eu.seaclouds.platform.planner.core.application.decorators.SeaCloudsManagementPolicyDecorator; import eu.seaclouds.platform.planner.core.application.decorators.SeaCloudsMonitoringInitializerPolicyDecorator; import eu.seaclouds.platform.planner.core.application.decorators.SlaInformationDecorator; package eu.seaclouds.platform.planner.core.application; public class ApplicationFacadeDecoratorApplicator { public void applyDecorators(ApplicationFacade applicationFacade) { new MonitoringInformationDecorator().apply(applicationFacade); new SlaInformationDecorator().apply(applicationFacade); new SeaCloudsManagementPolicyDecorator().apply(applicationFacade);
new SeaCloudsMonitoringInitializerPolicyDecorator().apply(applicationFacade);
SeaCloudsEU/SeaCloudsPlatform
dashboard/src/test/java/eu/seaclouds/platform/dashboard/proxy/SlaProxyTest.java
// Path: dashboard/src/test/java/eu/seaclouds/platform/dashboard/utils/TestFixtures.java // public interface TestFixtures { // String APPLICATION_ID = "DUkgr9Vb"; // // Deployer fixtures // String TOSCA_DAM_PATH = "fixtures/tosca-dam.yml"; // String APPLICATION_PATH = "fixtures/application.json"; // String TASK_SUMMARY_DEPLOY_PATH = "fixtures/task-summary-deploy.json"; // String TASK_SUMMARY_DELETE_PATH = "fixtures/task-summary-delete.json"; // String ENTITIES_PATH = "fixtures/entities.json"; // String SENSORS_SUMMARIES_PATH = "fixtures/sensors.json"; // // // // SLA fixtures // String AGREEMENT_PATH_JSON = "fixtures/agreement.json"; // String AGREEMENT_STATUS_PATH_JSON = "fixtures/agreement-status.json"; // String VIOLATIONS_JSON_PATH = "fixtures/violations.json"; // String PENALTIES_JSON_PATH = "fixtures/penalties.json"; // // // Monitor fixtures // String MONITORING_RULES_PATH = "fixtures/monitoring-rules.xml"; // // // Planner fixtures // String ADPS_PATH = "fixtures/adps.json"; // String ADP_PATH = "fixtures/adp.yml"; // String AAM_PATH = "fixtures/aam.yml"; // String DESIGNER_TOPOLOGY = "fixtures/designer-topology.json"; // String APPLICATION_TREE = "fixtures/application-tree.json"; // }
import java.util.List; import java.util.UUID; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import com.squareup.okhttp.mockwebserver.MockResponse; import eu.atos.sla.parser.data.GuaranteeTermsStatus; import eu.atos.sla.parser.data.Penalty; import eu.atos.sla.parser.data.wsag.Agreement; import eu.atos.sla.parser.data.wsag.GuaranteeTerm; import eu.seaclouds.platform.dashboard.util.ObjectMapperHelpers; import eu.seaclouds.platform.dashboard.utils.TestFixtures; import eu.seaclouds.platform.dashboard.utils.TestUtils; import org.testng.annotations.Test; import javax.ws.rs.core.MediaType;
/* * Copyright 2014 SeaClouds * Contact: SeaClouds * * 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 eu.seaclouds.platform.dashboard.proxy; public class SlaProxyTest extends AbstractProxyTest<SlaProxy> { private final String RANDOM_STRING = UUID.randomUUID().toString(); @Override public SlaProxy getProxy() { return getSupport().getConfiguration().getSlaProxy(); } @Test public void testAddAgreement() throws Exception {
// Path: dashboard/src/test/java/eu/seaclouds/platform/dashboard/utils/TestFixtures.java // public interface TestFixtures { // String APPLICATION_ID = "DUkgr9Vb"; // // Deployer fixtures // String TOSCA_DAM_PATH = "fixtures/tosca-dam.yml"; // String APPLICATION_PATH = "fixtures/application.json"; // String TASK_SUMMARY_DEPLOY_PATH = "fixtures/task-summary-deploy.json"; // String TASK_SUMMARY_DELETE_PATH = "fixtures/task-summary-delete.json"; // String ENTITIES_PATH = "fixtures/entities.json"; // String SENSORS_SUMMARIES_PATH = "fixtures/sensors.json"; // // // // SLA fixtures // String AGREEMENT_PATH_JSON = "fixtures/agreement.json"; // String AGREEMENT_STATUS_PATH_JSON = "fixtures/agreement-status.json"; // String VIOLATIONS_JSON_PATH = "fixtures/violations.json"; // String PENALTIES_JSON_PATH = "fixtures/penalties.json"; // // // Monitor fixtures // String MONITORING_RULES_PATH = "fixtures/monitoring-rules.xml"; // // // Planner fixtures // String ADPS_PATH = "fixtures/adps.json"; // String ADP_PATH = "fixtures/adp.yml"; // String AAM_PATH = "fixtures/aam.yml"; // String DESIGNER_TOPOLOGY = "fixtures/designer-topology.json"; // String APPLICATION_TREE = "fixtures/application-tree.json"; // } // Path: dashboard/src/test/java/eu/seaclouds/platform/dashboard/proxy/SlaProxyTest.java import java.util.List; import java.util.UUID; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import com.squareup.okhttp.mockwebserver.MockResponse; import eu.atos.sla.parser.data.GuaranteeTermsStatus; import eu.atos.sla.parser.data.Penalty; import eu.atos.sla.parser.data.wsag.Agreement; import eu.atos.sla.parser.data.wsag.GuaranteeTerm; import eu.seaclouds.platform.dashboard.util.ObjectMapperHelpers; import eu.seaclouds.platform.dashboard.utils.TestFixtures; import eu.seaclouds.platform.dashboard.utils.TestUtils; import org.testng.annotations.Test; import javax.ws.rs.core.MediaType; /* * Copyright 2014 SeaClouds * Contact: SeaClouds * * 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 eu.seaclouds.platform.dashboard.proxy; public class SlaProxyTest extends AbstractProxyTest<SlaProxy> { private final String RANDOM_STRING = UUID.randomUUID().toString(); @Override public SlaProxy getProxy() { return getSupport().getConfiguration().getSlaProxy(); } @Test public void testAddAgreement() throws Exception {
String json = TestUtils.getStringFromPath(TestFixtures.AGREEMENT_PATH_JSON);
SeaCloudsEU/SeaCloudsPlatform
dashboard/src/test/java/eu/seaclouds/platform/dashboard/rest/AbstractResourceTest.java
// Path: dashboard/src/test/java/eu/seaclouds/platform/dashboard/utils/TestFixtures.java // public interface TestFixtures { // String APPLICATION_ID = "DUkgr9Vb"; // // Deployer fixtures // String TOSCA_DAM_PATH = "fixtures/tosca-dam.yml"; // String APPLICATION_PATH = "fixtures/application.json"; // String TASK_SUMMARY_DEPLOY_PATH = "fixtures/task-summary-deploy.json"; // String TASK_SUMMARY_DELETE_PATH = "fixtures/task-summary-delete.json"; // String ENTITIES_PATH = "fixtures/entities.json"; // String SENSORS_SUMMARIES_PATH = "fixtures/sensors.json"; // // // // SLA fixtures // String AGREEMENT_PATH_JSON = "fixtures/agreement.json"; // String AGREEMENT_STATUS_PATH_JSON = "fixtures/agreement-status.json"; // String VIOLATIONS_JSON_PATH = "fixtures/violations.json"; // String PENALTIES_JSON_PATH = "fixtures/penalties.json"; // // // Monitor fixtures // String MONITORING_RULES_PATH = "fixtures/monitoring-rules.xml"; // // // Planner fixtures // String ADPS_PATH = "fixtures/adps.json"; // String ADP_PATH = "fixtures/adp.yml"; // String AAM_PATH = "fixtures/aam.yml"; // String DESIGNER_TOPOLOGY = "fixtures/designer-topology.json"; // String APPLICATION_TREE = "fixtures/application-tree.json"; // }
import com.fasterxml.jackson.databind.JsonNode; import eu.atos.sla.parser.data.GuaranteeTermsStatus; import eu.atos.sla.parser.data.Penalty; import eu.atos.sla.parser.data.Violation; import eu.atos.sla.parser.data.wsag.Agreement; import eu.atos.sla.parser.data.wsag.GuaranteeTerm; import eu.seaclouds.platform.dashboard.model.SeaCloudsApplicationDataStorage; import eu.seaclouds.platform.dashboard.proxy.*; import eu.seaclouds.platform.dashboard.util.ObjectMapperHelpers; import eu.seaclouds.platform.dashboard.utils.TestFixtures; import eu.seaclouds.platform.dashboard.utils.TestUtils; import it.polimi.tower4clouds.rules.MonitoringRules; import org.apache.brooklyn.rest.domain.ApplicationSummary; import org.apache.brooklyn.rest.domain.EntitySummary; import org.apache.brooklyn.rest.domain.SensorSummary; import org.apache.brooklyn.rest.domain.TaskSummary; import org.mockito.Matchers; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.List; import java.util.UUID; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Copyright 2014 SeaClouds * Contact: SeaClouds * * 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 eu.seaclouds.platform.dashboard.rest; public abstract class AbstractResourceTest<T extends Resource> { protected static final String RANDOM_STRING = UUID.randomUUID().toString(); private static final String DEPLOYER_ENDPOINT = "http://localhost:8081"; private static final String MONITOR_ENDPOINT = "http://localhost:8170"; private static final String GRAFANA_ENDPOINT = "http://localhost:3000"; private static final String PLANNER_ENDPOINT = "http://localhost:1234"; private static final String SLA_ENDPOINT = "http://localhost:8080"; private ApplicationSummary applicationSummary; private JsonNode applicationTree; private TaskSummary taskSummaryDeploy; private TaskSummary taskSummaryDelete; private List<SensorSummary> sensorSummaries; private List<EntitySummary> entitySummaries; private Agreement agreement; private GuaranteeTermsStatus agreementStatus; private List<Violation> agreementTermViolations; private List<Penalty> agreementTermPenalties; private MonitoringRules monitoringRules; private String topology; private String adp; private String adps; private String aam; private String dam; private final DeployerProxy deployerProxy = mock(DeployerProxy.class); private final PlannerProxy plannerProxy = mock(PlannerProxy.class); private final SlaProxy slaProxy = mock(SlaProxy.class); private final GrafanaProxy grafanaProxy = mock(GrafanaProxy.class); private void initObjects() throws IOException, JAXBException { applicationSummary = ObjectMapperHelpers.JsonToObject(
// Path: dashboard/src/test/java/eu/seaclouds/platform/dashboard/utils/TestFixtures.java // public interface TestFixtures { // String APPLICATION_ID = "DUkgr9Vb"; // // Deployer fixtures // String TOSCA_DAM_PATH = "fixtures/tosca-dam.yml"; // String APPLICATION_PATH = "fixtures/application.json"; // String TASK_SUMMARY_DEPLOY_PATH = "fixtures/task-summary-deploy.json"; // String TASK_SUMMARY_DELETE_PATH = "fixtures/task-summary-delete.json"; // String ENTITIES_PATH = "fixtures/entities.json"; // String SENSORS_SUMMARIES_PATH = "fixtures/sensors.json"; // // // // SLA fixtures // String AGREEMENT_PATH_JSON = "fixtures/agreement.json"; // String AGREEMENT_STATUS_PATH_JSON = "fixtures/agreement-status.json"; // String VIOLATIONS_JSON_PATH = "fixtures/violations.json"; // String PENALTIES_JSON_PATH = "fixtures/penalties.json"; // // // Monitor fixtures // String MONITORING_RULES_PATH = "fixtures/monitoring-rules.xml"; // // // Planner fixtures // String ADPS_PATH = "fixtures/adps.json"; // String ADP_PATH = "fixtures/adp.yml"; // String AAM_PATH = "fixtures/aam.yml"; // String DESIGNER_TOPOLOGY = "fixtures/designer-topology.json"; // String APPLICATION_TREE = "fixtures/application-tree.json"; // } // Path: dashboard/src/test/java/eu/seaclouds/platform/dashboard/rest/AbstractResourceTest.java import com.fasterxml.jackson.databind.JsonNode; import eu.atos.sla.parser.data.GuaranteeTermsStatus; import eu.atos.sla.parser.data.Penalty; import eu.atos.sla.parser.data.Violation; import eu.atos.sla.parser.data.wsag.Agreement; import eu.atos.sla.parser.data.wsag.GuaranteeTerm; import eu.seaclouds.platform.dashboard.model.SeaCloudsApplicationDataStorage; import eu.seaclouds.platform.dashboard.proxy.*; import eu.seaclouds.platform.dashboard.util.ObjectMapperHelpers; import eu.seaclouds.platform.dashboard.utils.TestFixtures; import eu.seaclouds.platform.dashboard.utils.TestUtils; import it.polimi.tower4clouds.rules.MonitoringRules; import org.apache.brooklyn.rest.domain.ApplicationSummary; import org.apache.brooklyn.rest.domain.EntitySummary; import org.apache.brooklyn.rest.domain.SensorSummary; import org.apache.brooklyn.rest.domain.TaskSummary; import org.mockito.Matchers; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.List; import java.util.UUID; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Copyright 2014 SeaClouds * Contact: SeaClouds * * 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 eu.seaclouds.platform.dashboard.rest; public abstract class AbstractResourceTest<T extends Resource> { protected static final String RANDOM_STRING = UUID.randomUUID().toString(); private static final String DEPLOYER_ENDPOINT = "http://localhost:8081"; private static final String MONITOR_ENDPOINT = "http://localhost:8170"; private static final String GRAFANA_ENDPOINT = "http://localhost:3000"; private static final String PLANNER_ENDPOINT = "http://localhost:1234"; private static final String SLA_ENDPOINT = "http://localhost:8080"; private ApplicationSummary applicationSummary; private JsonNode applicationTree; private TaskSummary taskSummaryDeploy; private TaskSummary taskSummaryDelete; private List<SensorSummary> sensorSummaries; private List<EntitySummary> entitySummaries; private Agreement agreement; private GuaranteeTermsStatus agreementStatus; private List<Violation> agreementTermViolations; private List<Penalty> agreementTermPenalties; private MonitoringRules monitoringRules; private String topology; private String adp; private String adps; private String aam; private String dam; private final DeployerProxy deployerProxy = mock(DeployerProxy.class); private final PlannerProxy plannerProxy = mock(PlannerProxy.class); private final SlaProxy slaProxy = mock(SlaProxy.class); private final GrafanaProxy grafanaProxy = mock(GrafanaProxy.class); private void initObjects() throws IOException, JAXBException { applicationSummary = ObjectMapperHelpers.JsonToObject(
TestUtils.getStringFromPath(TestFixtures.APPLICATION_PATH), ApplicationSummary.class);
SeaCloudsEU/SeaCloudsPlatform
deployer/src/main/java/eu/seaclouds/policy/SeaCloudsMonitoringInitializationPolicies.java
// Path: deployer/src/main/java/eu/seaclouds/policy/utils/SeaCloudsDcRequestDto.java // public class SeaCloudsDcRequestDto { // // public static final String ID_SUFIX = "_ID"; // private String id; // private String type; // private String url; // // private SeaCloudsDcRequestDto(Builder builder) { // id = builder.id; // type = builder.type; // url = builder.url; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public static class Builder { // private String id; // private String type; // private String url; // // public Builder type(String type) { // this.type = type; // this.id = type + ID_SUFIX; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public SeaCloudsDcRequestDto build() { // return new SeaCloudsDcRequestDto(this); // } // // } // // }
import java.net.URI; import java.util.List; import java.util.Map; import org.apache.brooklyn.api.entity.Application; import org.apache.brooklyn.api.entity.Entity; import org.apache.brooklyn.api.entity.EntityLocal; import org.apache.brooklyn.api.sensor.AttributeSensor; import org.apache.brooklyn.api.sensor.SensorEvent; import org.apache.brooklyn.api.sensor.SensorEventListener; import org.apache.brooklyn.camp.brooklyn.BrooklynCampConstants; import org.apache.brooklyn.config.ConfigKey; import org.apache.brooklyn.core.config.BasicConfigKey; import org.apache.brooklyn.core.config.ConfigKeys; import org.apache.brooklyn.core.entity.Attributes; import org.apache.brooklyn.core.entity.lifecycle.Lifecycle; import org.apache.brooklyn.core.policy.AbstractPolicy; import org.apache.brooklyn.core.sensor.Sensors; import org.apache.brooklyn.util.collections.MutableList; import org.apache.brooklyn.util.collections.MutableMap; import org.apache.brooklyn.util.core.flags.SetFromFlag; import org.apache.brooklyn.util.http.HttpTool; import org.apache.brooklyn.util.http.HttpToolResponse; import org.apache.brooklyn.util.text.Strings; import org.apache.http.HttpHeaders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Optional; import com.google.common.net.MediaType; import eu.seaclouds.policy.utils.SeaCloudsDcRequestDto;
private boolean configured; public LifecycleListener() { configured = false; } @Override public void onEvent(SensorEvent<Lifecycle> event) { if (event.getValue().equals(Lifecycle.RUNNING) && !configured) { configured = true; configureMontiroringForTargetEntities(); } } private void configureMontiroringForTargetEntities() { for (String targetEntityId : getConfig(TARGET_ENTITIES)) { Optional<Entity> optionalChild = findChildEntityByPlanId((Application) entity, targetEntityId); if (optionalChild.isPresent()) { Entity child = optionalChild.get(); configureSeaCloudDcForAEntity(child, targetEntityId); } } entity.sensors().set(MONITORING_CONFIGURED, true); } private void configureSeaCloudDcForAEntity(Entity child, String entityId) { String mainUri = getMainUri(child); if (!Strings.isBlank(mainUri)) {
// Path: deployer/src/main/java/eu/seaclouds/policy/utils/SeaCloudsDcRequestDto.java // public class SeaCloudsDcRequestDto { // // public static final String ID_SUFIX = "_ID"; // private String id; // private String type; // private String url; // // private SeaCloudsDcRequestDto(Builder builder) { // id = builder.id; // type = builder.type; // url = builder.url; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public static class Builder { // private String id; // private String type; // private String url; // // public Builder type(String type) { // this.type = type; // this.id = type + ID_SUFIX; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public SeaCloudsDcRequestDto build() { // return new SeaCloudsDcRequestDto(this); // } // // } // // } // Path: deployer/src/main/java/eu/seaclouds/policy/SeaCloudsMonitoringInitializationPolicies.java import java.net.URI; import java.util.List; import java.util.Map; import org.apache.brooklyn.api.entity.Application; import org.apache.brooklyn.api.entity.Entity; import org.apache.brooklyn.api.entity.EntityLocal; import org.apache.brooklyn.api.sensor.AttributeSensor; import org.apache.brooklyn.api.sensor.SensorEvent; import org.apache.brooklyn.api.sensor.SensorEventListener; import org.apache.brooklyn.camp.brooklyn.BrooklynCampConstants; import org.apache.brooklyn.config.ConfigKey; import org.apache.brooklyn.core.config.BasicConfigKey; import org.apache.brooklyn.core.config.ConfigKeys; import org.apache.brooklyn.core.entity.Attributes; import org.apache.brooklyn.core.entity.lifecycle.Lifecycle; import org.apache.brooklyn.core.policy.AbstractPolicy; import org.apache.brooklyn.core.sensor.Sensors; import org.apache.brooklyn.util.collections.MutableList; import org.apache.brooklyn.util.collections.MutableMap; import org.apache.brooklyn.util.core.flags.SetFromFlag; import org.apache.brooklyn.util.http.HttpTool; import org.apache.brooklyn.util.http.HttpToolResponse; import org.apache.brooklyn.util.text.Strings; import org.apache.http.HttpHeaders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Optional; import com.google.common.net.MediaType; import eu.seaclouds.policy.utils.SeaCloudsDcRequestDto; private boolean configured; public LifecycleListener() { configured = false; } @Override public void onEvent(SensorEvent<Lifecycle> event) { if (event.getValue().equals(Lifecycle.RUNNING) && !configured) { configured = true; configureMontiroringForTargetEntities(); } } private void configureMontiroringForTargetEntities() { for (String targetEntityId : getConfig(TARGET_ENTITIES)) { Optional<Entity> optionalChild = findChildEntityByPlanId((Application) entity, targetEntityId); if (optionalChild.isPresent()) { Entity child = optionalChild.get(); configureSeaCloudDcForAEntity(child, targetEntityId); } } entity.sensors().set(MONITORING_CONFIGURED, true); } private void configureSeaCloudDcForAEntity(Entity child, String entityId) { String mainUri = getMainUri(child); if (!Strings.isBlank(mainUri)) {
SeaCloudsDcRequestDto requestBody = new SeaCloudsDcRequestDto.Builder()
asanchezyu/RetrofitSoapSample
app/src/main/java/com/asanchezyu/retrofitsoap/injection/application/ApplicationComponent.java
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/UsStatesApi.java // public interface UsStatesApi { // // @Headers({ // "Content-Type: text/xml", // "Accept-Charset: utf-8" // }) // @POST("/uszip.asmx") // Call<UsStatesResponseEnvelope> requestStateInfo(@Body UsStatesRequestEnvelope body); // // }
import com.asanchezyu.retrofitsoap.api.UsStatesApi; import javax.inject.Singleton; import dagger.Component;
/* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.injection.application; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ @Singleton @Component(modules = ApplicationModule.class) public interface ApplicationComponent {
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/UsStatesApi.java // public interface UsStatesApi { // // @Headers({ // "Content-Type: text/xml", // "Accept-Charset: utf-8" // }) // @POST("/uszip.asmx") // Call<UsStatesResponseEnvelope> requestStateInfo(@Body UsStatesRequestEnvelope body); // // } // Path: app/src/main/java/com/asanchezyu/retrofitsoap/injection/application/ApplicationComponent.java import com.asanchezyu.retrofitsoap.api.UsStatesApi; import javax.inject.Singleton; import dagger.Component; /* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.injection.application; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ @Singleton @Component(modules = ApplicationModule.class) public interface ApplicationComponent {
UsStatesApi providesApi();
asanchezyu/RetrofitSoapSample
app/src/main/java/com/asanchezyu/retrofitsoap/domain/threads/InteractorExecutorImpl.java
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/Interactor.java // public interface Interactor { // // void run(); // // }
import com.asanchezyu.retrofitsoap.domain.interactors.Interactor; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.inject.Inject;
/* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.domain.threads; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public class InteractorExecutorImpl implements InteractorExecutor{ private static final int CORE_POOL_SIZE = 2; private static final int MAXIMUM_POOL_SIZE = 2; private static final long LIFE_TIME = 60; private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; private static final BlockingQueue QUEUE = new LinkedBlockingQueue(); private ThreadPoolExecutor threadPoolExecutor; @Inject public InteractorExecutorImpl() { threadPoolExecutor = new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, LIFE_TIME, TIME_UNIT, QUEUE ); } @Override
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/Interactor.java // public interface Interactor { // // void run(); // // } // Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/threads/InteractorExecutorImpl.java import com.asanchezyu.retrofitsoap.domain.interactors.Interactor; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.inject.Inject; /* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.domain.threads; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public class InteractorExecutorImpl implements InteractorExecutor{ private static final int CORE_POOL_SIZE = 2; private static final int MAXIMUM_POOL_SIZE = 2; private static final long LIFE_TIME = 60; private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; private static final BlockingQueue QUEUE = new LinkedBlockingQueue(); private ThreadPoolExecutor threadPoolExecutor; @Inject public InteractorExecutorImpl() { threadPoolExecutor = new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, LIFE_TIME, TIME_UNIT, QUEUE ); } @Override
public void run(final Interactor interactor) {
asanchezyu/RetrofitSoapSample
app/src/main/java/com/asanchezyu/retrofitsoap/presenters/ZipCodesPresenterImpl.java
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/search/SearchCodesByCityInteractor.java // public interface SearchCodesByCityInteractor extends Interactor{ // // interface Callback{ // // void onSuccess(List<ZipCodeDomain> zipCodes); // // void onError(); // // } // // void execute(String cityName, Callback callback ); // // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/model/ZipCodeDomain.java // public class ZipCodeDomain { // // private String city; // // private String state; // // private String zipCode; // // private String areaCode; // // private String timeZone; // // public String getAreaCode() { // return areaCode; // } // // public void setAreaCode(String areaCode) { // this.areaCode = areaCode; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getTimeZone() { // return timeZone; // } // // public void setTimeZone(String timeZone) { // this.timeZone = timeZone; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/ui/views/CityZipsView.java // public interface CityZipsView { // // void setCityZips(List<ZipCodeData> cityZips); // // void showWaitingDialog(); // // void hideWaitingDialog(); // // void showCityNeededErrorMessage(); // // void showErrorInRequest(); // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/util/ZipCodeMapperUi.java // public class ZipCodeMapperUi extends EntityMapper<ZipCodeData,ZipCodeDomain> { // // @Inject // public ZipCodeMapperUi() { // } // // @Override // public ZipCodeDomain map(ZipCodeData element) { // ZipCodeDomain element1 = new ZipCodeDomain(); // element1.setCity(element.getCity()); // element1.setTimeZone(element.getTimeZone()); // element1.setAreaCode(element.getAreaCode()); // element1.setState(element.getState()); // element1.setZipCode(element.getZipCode()); // return element1; // } // // @Override // public ZipCodeData reverseMap(ZipCodeDomain element) { // ZipCodeData codeData = new ZipCodeData(); // codeData.setCity(element.getCity()); // codeData.setState(element.getState()); // codeData.setAreaCode(element.getAreaCode()); // codeData.setTimeZone(element.getTimeZone()); // codeData.setZipCode(element.getZipCode()); // return codeData; // } // // }
import com.asanchezyu.retrofitsoap.domain.interactors.search.SearchCodesByCityInteractor; import com.asanchezyu.retrofitsoap.domain.model.ZipCodeDomain; import com.asanchezyu.retrofitsoap.ui.views.CityZipsView; import com.asanchezyu.retrofitsoap.util.ZipCodeMapperUi; import java.util.List; import javax.inject.Inject;
/* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.presenters; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public class ZipCodesPresenterImpl implements ZipCodesPresenter, SearchCodesByCityInteractor.Callback { @Inject
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/search/SearchCodesByCityInteractor.java // public interface SearchCodesByCityInteractor extends Interactor{ // // interface Callback{ // // void onSuccess(List<ZipCodeDomain> zipCodes); // // void onError(); // // } // // void execute(String cityName, Callback callback ); // // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/model/ZipCodeDomain.java // public class ZipCodeDomain { // // private String city; // // private String state; // // private String zipCode; // // private String areaCode; // // private String timeZone; // // public String getAreaCode() { // return areaCode; // } // // public void setAreaCode(String areaCode) { // this.areaCode = areaCode; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getTimeZone() { // return timeZone; // } // // public void setTimeZone(String timeZone) { // this.timeZone = timeZone; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/ui/views/CityZipsView.java // public interface CityZipsView { // // void setCityZips(List<ZipCodeData> cityZips); // // void showWaitingDialog(); // // void hideWaitingDialog(); // // void showCityNeededErrorMessage(); // // void showErrorInRequest(); // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/util/ZipCodeMapperUi.java // public class ZipCodeMapperUi extends EntityMapper<ZipCodeData,ZipCodeDomain> { // // @Inject // public ZipCodeMapperUi() { // } // // @Override // public ZipCodeDomain map(ZipCodeData element) { // ZipCodeDomain element1 = new ZipCodeDomain(); // element1.setCity(element.getCity()); // element1.setTimeZone(element.getTimeZone()); // element1.setAreaCode(element.getAreaCode()); // element1.setState(element.getState()); // element1.setZipCode(element.getZipCode()); // return element1; // } // // @Override // public ZipCodeData reverseMap(ZipCodeDomain element) { // ZipCodeData codeData = new ZipCodeData(); // codeData.setCity(element.getCity()); // codeData.setState(element.getState()); // codeData.setAreaCode(element.getAreaCode()); // codeData.setTimeZone(element.getTimeZone()); // codeData.setZipCode(element.getZipCode()); // return codeData; // } // // } // Path: app/src/main/java/com/asanchezyu/retrofitsoap/presenters/ZipCodesPresenterImpl.java import com.asanchezyu.retrofitsoap.domain.interactors.search.SearchCodesByCityInteractor; import com.asanchezyu.retrofitsoap.domain.model.ZipCodeDomain; import com.asanchezyu.retrofitsoap.ui.views.CityZipsView; import com.asanchezyu.retrofitsoap.util.ZipCodeMapperUi; import java.util.List; import javax.inject.Inject; /* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.presenters; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public class ZipCodesPresenterImpl implements ZipCodesPresenter, SearchCodesByCityInteractor.Callback { @Inject
CityZipsView view;
asanchezyu/RetrofitSoapSample
app/src/main/java/com/asanchezyu/retrofitsoap/presenters/ZipCodesPresenterImpl.java
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/search/SearchCodesByCityInteractor.java // public interface SearchCodesByCityInteractor extends Interactor{ // // interface Callback{ // // void onSuccess(List<ZipCodeDomain> zipCodes); // // void onError(); // // } // // void execute(String cityName, Callback callback ); // // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/model/ZipCodeDomain.java // public class ZipCodeDomain { // // private String city; // // private String state; // // private String zipCode; // // private String areaCode; // // private String timeZone; // // public String getAreaCode() { // return areaCode; // } // // public void setAreaCode(String areaCode) { // this.areaCode = areaCode; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getTimeZone() { // return timeZone; // } // // public void setTimeZone(String timeZone) { // this.timeZone = timeZone; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/ui/views/CityZipsView.java // public interface CityZipsView { // // void setCityZips(List<ZipCodeData> cityZips); // // void showWaitingDialog(); // // void hideWaitingDialog(); // // void showCityNeededErrorMessage(); // // void showErrorInRequest(); // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/util/ZipCodeMapperUi.java // public class ZipCodeMapperUi extends EntityMapper<ZipCodeData,ZipCodeDomain> { // // @Inject // public ZipCodeMapperUi() { // } // // @Override // public ZipCodeDomain map(ZipCodeData element) { // ZipCodeDomain element1 = new ZipCodeDomain(); // element1.setCity(element.getCity()); // element1.setTimeZone(element.getTimeZone()); // element1.setAreaCode(element.getAreaCode()); // element1.setState(element.getState()); // element1.setZipCode(element.getZipCode()); // return element1; // } // // @Override // public ZipCodeData reverseMap(ZipCodeDomain element) { // ZipCodeData codeData = new ZipCodeData(); // codeData.setCity(element.getCity()); // codeData.setState(element.getState()); // codeData.setAreaCode(element.getAreaCode()); // codeData.setTimeZone(element.getTimeZone()); // codeData.setZipCode(element.getZipCode()); // return codeData; // } // // }
import com.asanchezyu.retrofitsoap.domain.interactors.search.SearchCodesByCityInteractor; import com.asanchezyu.retrofitsoap.domain.model.ZipCodeDomain; import com.asanchezyu.retrofitsoap.ui.views.CityZipsView; import com.asanchezyu.retrofitsoap.util.ZipCodeMapperUi; import java.util.List; import javax.inject.Inject;
/* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.presenters; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public class ZipCodesPresenterImpl implements ZipCodesPresenter, SearchCodesByCityInteractor.Callback { @Inject CityZipsView view; @Inject
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/search/SearchCodesByCityInteractor.java // public interface SearchCodesByCityInteractor extends Interactor{ // // interface Callback{ // // void onSuccess(List<ZipCodeDomain> zipCodes); // // void onError(); // // } // // void execute(String cityName, Callback callback ); // // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/model/ZipCodeDomain.java // public class ZipCodeDomain { // // private String city; // // private String state; // // private String zipCode; // // private String areaCode; // // private String timeZone; // // public String getAreaCode() { // return areaCode; // } // // public void setAreaCode(String areaCode) { // this.areaCode = areaCode; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getTimeZone() { // return timeZone; // } // // public void setTimeZone(String timeZone) { // this.timeZone = timeZone; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/ui/views/CityZipsView.java // public interface CityZipsView { // // void setCityZips(List<ZipCodeData> cityZips); // // void showWaitingDialog(); // // void hideWaitingDialog(); // // void showCityNeededErrorMessage(); // // void showErrorInRequest(); // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/util/ZipCodeMapperUi.java // public class ZipCodeMapperUi extends EntityMapper<ZipCodeData,ZipCodeDomain> { // // @Inject // public ZipCodeMapperUi() { // } // // @Override // public ZipCodeDomain map(ZipCodeData element) { // ZipCodeDomain element1 = new ZipCodeDomain(); // element1.setCity(element.getCity()); // element1.setTimeZone(element.getTimeZone()); // element1.setAreaCode(element.getAreaCode()); // element1.setState(element.getState()); // element1.setZipCode(element.getZipCode()); // return element1; // } // // @Override // public ZipCodeData reverseMap(ZipCodeDomain element) { // ZipCodeData codeData = new ZipCodeData(); // codeData.setCity(element.getCity()); // codeData.setState(element.getState()); // codeData.setAreaCode(element.getAreaCode()); // codeData.setTimeZone(element.getTimeZone()); // codeData.setZipCode(element.getZipCode()); // return codeData; // } // // } // Path: app/src/main/java/com/asanchezyu/retrofitsoap/presenters/ZipCodesPresenterImpl.java import com.asanchezyu.retrofitsoap.domain.interactors.search.SearchCodesByCityInteractor; import com.asanchezyu.retrofitsoap.domain.model.ZipCodeDomain; import com.asanchezyu.retrofitsoap.ui.views.CityZipsView; import com.asanchezyu.retrofitsoap.util.ZipCodeMapperUi; import java.util.List; import javax.inject.Inject; /* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.presenters; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public class ZipCodesPresenterImpl implements ZipCodesPresenter, SearchCodesByCityInteractor.Callback { @Inject CityZipsView view; @Inject
ZipCodeMapperUi zipCodeMapper;
asanchezyu/RetrofitSoapSample
app/src/main/java/com/asanchezyu/retrofitsoap/presenters/ZipCodesPresenterImpl.java
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/search/SearchCodesByCityInteractor.java // public interface SearchCodesByCityInteractor extends Interactor{ // // interface Callback{ // // void onSuccess(List<ZipCodeDomain> zipCodes); // // void onError(); // // } // // void execute(String cityName, Callback callback ); // // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/model/ZipCodeDomain.java // public class ZipCodeDomain { // // private String city; // // private String state; // // private String zipCode; // // private String areaCode; // // private String timeZone; // // public String getAreaCode() { // return areaCode; // } // // public void setAreaCode(String areaCode) { // this.areaCode = areaCode; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getTimeZone() { // return timeZone; // } // // public void setTimeZone(String timeZone) { // this.timeZone = timeZone; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/ui/views/CityZipsView.java // public interface CityZipsView { // // void setCityZips(List<ZipCodeData> cityZips); // // void showWaitingDialog(); // // void hideWaitingDialog(); // // void showCityNeededErrorMessage(); // // void showErrorInRequest(); // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/util/ZipCodeMapperUi.java // public class ZipCodeMapperUi extends EntityMapper<ZipCodeData,ZipCodeDomain> { // // @Inject // public ZipCodeMapperUi() { // } // // @Override // public ZipCodeDomain map(ZipCodeData element) { // ZipCodeDomain element1 = new ZipCodeDomain(); // element1.setCity(element.getCity()); // element1.setTimeZone(element.getTimeZone()); // element1.setAreaCode(element.getAreaCode()); // element1.setState(element.getState()); // element1.setZipCode(element.getZipCode()); // return element1; // } // // @Override // public ZipCodeData reverseMap(ZipCodeDomain element) { // ZipCodeData codeData = new ZipCodeData(); // codeData.setCity(element.getCity()); // codeData.setState(element.getState()); // codeData.setAreaCode(element.getAreaCode()); // codeData.setTimeZone(element.getTimeZone()); // codeData.setZipCode(element.getZipCode()); // return codeData; // } // // }
import com.asanchezyu.retrofitsoap.domain.interactors.search.SearchCodesByCityInteractor; import com.asanchezyu.retrofitsoap.domain.model.ZipCodeDomain; import com.asanchezyu.retrofitsoap.ui.views.CityZipsView; import com.asanchezyu.retrofitsoap.util.ZipCodeMapperUi; import java.util.List; import javax.inject.Inject;
/* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.presenters; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public class ZipCodesPresenterImpl implements ZipCodesPresenter, SearchCodesByCityInteractor.Callback { @Inject CityZipsView view; @Inject ZipCodeMapperUi zipCodeMapper; @Inject SearchCodesByCityInteractor searchCodesByCityInteractor; @Inject public ZipCodesPresenterImpl() { } @Override public void makeSearch(String city) { if( city == null || city.isEmpty() ){ view.showCityNeededErrorMessage(); }else{ view.showWaitingDialog(); searchCodesByCityInteractor.execute( city, this ); } } @Override
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/search/SearchCodesByCityInteractor.java // public interface SearchCodesByCityInteractor extends Interactor{ // // interface Callback{ // // void onSuccess(List<ZipCodeDomain> zipCodes); // // void onError(); // // } // // void execute(String cityName, Callback callback ); // // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/model/ZipCodeDomain.java // public class ZipCodeDomain { // // private String city; // // private String state; // // private String zipCode; // // private String areaCode; // // private String timeZone; // // public String getAreaCode() { // return areaCode; // } // // public void setAreaCode(String areaCode) { // this.areaCode = areaCode; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getTimeZone() { // return timeZone; // } // // public void setTimeZone(String timeZone) { // this.timeZone = timeZone; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/ui/views/CityZipsView.java // public interface CityZipsView { // // void setCityZips(List<ZipCodeData> cityZips); // // void showWaitingDialog(); // // void hideWaitingDialog(); // // void showCityNeededErrorMessage(); // // void showErrorInRequest(); // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/util/ZipCodeMapperUi.java // public class ZipCodeMapperUi extends EntityMapper<ZipCodeData,ZipCodeDomain> { // // @Inject // public ZipCodeMapperUi() { // } // // @Override // public ZipCodeDomain map(ZipCodeData element) { // ZipCodeDomain element1 = new ZipCodeDomain(); // element1.setCity(element.getCity()); // element1.setTimeZone(element.getTimeZone()); // element1.setAreaCode(element.getAreaCode()); // element1.setState(element.getState()); // element1.setZipCode(element.getZipCode()); // return element1; // } // // @Override // public ZipCodeData reverseMap(ZipCodeDomain element) { // ZipCodeData codeData = new ZipCodeData(); // codeData.setCity(element.getCity()); // codeData.setState(element.getState()); // codeData.setAreaCode(element.getAreaCode()); // codeData.setTimeZone(element.getTimeZone()); // codeData.setZipCode(element.getZipCode()); // return codeData; // } // // } // Path: app/src/main/java/com/asanchezyu/retrofitsoap/presenters/ZipCodesPresenterImpl.java import com.asanchezyu.retrofitsoap.domain.interactors.search.SearchCodesByCityInteractor; import com.asanchezyu.retrofitsoap.domain.model.ZipCodeDomain; import com.asanchezyu.retrofitsoap.ui.views.CityZipsView; import com.asanchezyu.retrofitsoap.util.ZipCodeMapperUi; import java.util.List; import javax.inject.Inject; /* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.presenters; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public class ZipCodesPresenterImpl implements ZipCodesPresenter, SearchCodesByCityInteractor.Callback { @Inject CityZipsView view; @Inject ZipCodeMapperUi zipCodeMapper; @Inject SearchCodesByCityInteractor searchCodesByCityInteractor; @Inject public ZipCodesPresenterImpl() { } @Override public void makeSearch(String city) { if( city == null || city.isEmpty() ){ view.showCityNeededErrorMessage(); }else{ view.showWaitingDialog(); searchCodesByCityInteractor.execute( city, this ); } } @Override
public void onSuccess(List<ZipCodeDomain> list) {
asanchezyu/RetrofitSoapSample
app/src/main/java/com/asanchezyu/retrofitsoap/RetrofitSoapApplication.java
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/injection/application/ApplicationComponent.java // @Singleton // @Component(modules = ApplicationModule.class) // public interface ApplicationComponent { // // UsStatesApi providesApi(); // // // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/injection/application/ApplicationModule.java // @Module // @Singleton // public class ApplicationModule { // // private RetrofitSoapApplication application; // // public ApplicationModule(RetrofitSoapApplication application) { // this.application = application; // } // // @Provides // @Singleton // public UsStatesApi providesApi(){ // // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // Strategy strategy = new AnnotationStrategy(); // // Serializer serializer = new Persister(strategy); // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // .addInterceptor(interceptor) // .connectTimeout(2, TimeUnit.MINUTES) // .writeTimeout(2, TimeUnit.MINUTES) // .readTimeout(2, TimeUnit.MINUTES) // .build(); // // Retrofit retrofit = new Retrofit.Builder() // .addConverterFactory(SimpleXmlConverterFactory.create(serializer)) // .baseUrl("http://www.webservicex.net/") // .client(okHttpClient) // .build(); // // return retrofit.create( UsStatesApi.class); // // } // // }
import android.app.Application; import com.asanchezyu.retrofitsoap.injection.application.ApplicationComponent; import com.asanchezyu.retrofitsoap.injection.application.ApplicationModule; import com.asanchezyu.retrofitsoap.injection.application.DaggerApplicationComponent;
/* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public class RetrofitSoapApplication extends Application { private ApplicationComponent component; @Override public void onCreate() { super.onCreate(); component = DaggerApplicationComponent.builder()
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/injection/application/ApplicationComponent.java // @Singleton // @Component(modules = ApplicationModule.class) // public interface ApplicationComponent { // // UsStatesApi providesApi(); // // // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/injection/application/ApplicationModule.java // @Module // @Singleton // public class ApplicationModule { // // private RetrofitSoapApplication application; // // public ApplicationModule(RetrofitSoapApplication application) { // this.application = application; // } // // @Provides // @Singleton // public UsStatesApi providesApi(){ // // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // Strategy strategy = new AnnotationStrategy(); // // Serializer serializer = new Persister(strategy); // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // .addInterceptor(interceptor) // .connectTimeout(2, TimeUnit.MINUTES) // .writeTimeout(2, TimeUnit.MINUTES) // .readTimeout(2, TimeUnit.MINUTES) // .build(); // // Retrofit retrofit = new Retrofit.Builder() // .addConverterFactory(SimpleXmlConverterFactory.create(serializer)) // .baseUrl("http://www.webservicex.net/") // .client(okHttpClient) // .build(); // // return retrofit.create( UsStatesApi.class); // // } // // } // Path: app/src/main/java/com/asanchezyu/retrofitsoap/RetrofitSoapApplication.java import android.app.Application; import com.asanchezyu.retrofitsoap.injection.application.ApplicationComponent; import com.asanchezyu.retrofitsoap.injection.application.ApplicationModule; import com.asanchezyu.retrofitsoap.injection.application.DaggerApplicationComponent; /* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public class RetrofitSoapApplication extends Application { private ApplicationComponent component; @Override public void onCreate() { super.onCreate(); component = DaggerApplicationComponent.builder()
.applicationModule( new ApplicationModule(this))
asanchezyu/RetrofitSoapSample
app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/search/SearchCodesByCityInteractor.java
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/Interactor.java // public interface Interactor { // // void run(); // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/model/ZipCodeDomain.java // public class ZipCodeDomain { // // private String city; // // private String state; // // private String zipCode; // // private String areaCode; // // private String timeZone; // // public String getAreaCode() { // return areaCode; // } // // public void setAreaCode(String areaCode) { // this.areaCode = areaCode; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getTimeZone() { // return timeZone; // } // // public void setTimeZone(String timeZone) { // this.timeZone = timeZone; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // }
import com.asanchezyu.retrofitsoap.domain.interactors.Interactor; import com.asanchezyu.retrofitsoap.domain.model.ZipCodeDomain; import java.util.List;
/* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.domain.interactors.search; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public interface SearchCodesByCityInteractor extends Interactor{ interface Callback{
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/Interactor.java // public interface Interactor { // // void run(); // // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/model/ZipCodeDomain.java // public class ZipCodeDomain { // // private String city; // // private String state; // // private String zipCode; // // private String areaCode; // // private String timeZone; // // public String getAreaCode() { // return areaCode; // } // // public void setAreaCode(String areaCode) { // this.areaCode = areaCode; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getTimeZone() { // return timeZone; // } // // public void setTimeZone(String timeZone) { // this.timeZone = timeZone; // } // // public String getZipCode() { // return zipCode; // } // // public void setZipCode(String zipCode) { // this.zipCode = zipCode; // } // } // Path: app/src/main/java/com/asanchezyu/retrofitsoap/domain/interactors/search/SearchCodesByCityInteractor.java import com.asanchezyu.retrofitsoap.domain.interactors.Interactor; import com.asanchezyu.retrofitsoap.domain.model.ZipCodeDomain; import java.util.List; /* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.domain.interactors.search; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public interface SearchCodesByCityInteractor extends Interactor{ interface Callback{
void onSuccess(List<ZipCodeDomain> zipCodes);
asanchezyu/RetrofitSoapSample
app/src/main/java/com/asanchezyu/retrofitsoap/api/UsStatesApi.java
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/model/request/UsStatesRequestEnvelope.java // @Root(name = "soap12:Envelope") // @NamespaceList({ // @Namespace( prefix = "xsi", reference = "http://www.w3.org/2001/XMLSchema-instance"), // @Namespace( prefix = "xsd", reference = "http://www.w3.org/2001/XMLSchema"), // @Namespace( prefix = "soap12", reference = "http://www.w3.org/2003/05/soap-envelope") // }) // public class UsStatesRequestEnvelope { // // @Element(name = "soap12:Body", required = false) // private UsStatesRequestBody body; // // public UsStatesRequestBody getBody() { // return body; // } // // public void setBody(UsStatesRequestBody body) { // this.body = body; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/model/response/UsStatesResponseEnvelope.java // @Root(name = "soap12:Envelope") // @NamespaceList({ // @Namespace( prefix = "xsi", reference = "http://www.w3.org/2001/XMLSchema-instance"), // @Namespace( prefix = "xsd", reference = "http://www.w3.org/2001/XMLSchema"), // @Namespace( prefix = "soap12", reference = "http://www.w3.org/2003/05/soap-envelope") // }) // public class UsStatesResponseEnvelope { // // @Element(required = false, name = "Body") // private UsStatesResponseBody body; // // public UsStatesResponseBody getBody() { // return body; // } // // public void setBody(UsStatesResponseBody body) { // this.body = body; // } // }
import com.asanchezyu.retrofitsoap.api.model.request.UsStatesRequestEnvelope; import com.asanchezyu.retrofitsoap.api.model.response.UsStatesResponseEnvelope; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.Headers; import retrofit2.http.POST;
/* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.api; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public interface UsStatesApi { @Headers({ "Content-Type: text/xml", "Accept-Charset: utf-8" }) @POST("/uszip.asmx")
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/model/request/UsStatesRequestEnvelope.java // @Root(name = "soap12:Envelope") // @NamespaceList({ // @Namespace( prefix = "xsi", reference = "http://www.w3.org/2001/XMLSchema-instance"), // @Namespace( prefix = "xsd", reference = "http://www.w3.org/2001/XMLSchema"), // @Namespace( prefix = "soap12", reference = "http://www.w3.org/2003/05/soap-envelope") // }) // public class UsStatesRequestEnvelope { // // @Element(name = "soap12:Body", required = false) // private UsStatesRequestBody body; // // public UsStatesRequestBody getBody() { // return body; // } // // public void setBody(UsStatesRequestBody body) { // this.body = body; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/model/response/UsStatesResponseEnvelope.java // @Root(name = "soap12:Envelope") // @NamespaceList({ // @Namespace( prefix = "xsi", reference = "http://www.w3.org/2001/XMLSchema-instance"), // @Namespace( prefix = "xsd", reference = "http://www.w3.org/2001/XMLSchema"), // @Namespace( prefix = "soap12", reference = "http://www.w3.org/2003/05/soap-envelope") // }) // public class UsStatesResponseEnvelope { // // @Element(required = false, name = "Body") // private UsStatesResponseBody body; // // public UsStatesResponseBody getBody() { // return body; // } // // public void setBody(UsStatesResponseBody body) { // this.body = body; // } // } // Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/UsStatesApi.java import com.asanchezyu.retrofitsoap.api.model.request.UsStatesRequestEnvelope; import com.asanchezyu.retrofitsoap.api.model.response.UsStatesResponseEnvelope; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.Headers; import retrofit2.http.POST; /* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.api; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public interface UsStatesApi { @Headers({ "Content-Type: text/xml", "Accept-Charset: utf-8" }) @POST("/uszip.asmx")
Call<UsStatesResponseEnvelope> requestStateInfo(@Body UsStatesRequestEnvelope body);
asanchezyu/RetrofitSoapSample
app/src/main/java/com/asanchezyu/retrofitsoap/api/UsStatesApi.java
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/model/request/UsStatesRequestEnvelope.java // @Root(name = "soap12:Envelope") // @NamespaceList({ // @Namespace( prefix = "xsi", reference = "http://www.w3.org/2001/XMLSchema-instance"), // @Namespace( prefix = "xsd", reference = "http://www.w3.org/2001/XMLSchema"), // @Namespace( prefix = "soap12", reference = "http://www.w3.org/2003/05/soap-envelope") // }) // public class UsStatesRequestEnvelope { // // @Element(name = "soap12:Body", required = false) // private UsStatesRequestBody body; // // public UsStatesRequestBody getBody() { // return body; // } // // public void setBody(UsStatesRequestBody body) { // this.body = body; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/model/response/UsStatesResponseEnvelope.java // @Root(name = "soap12:Envelope") // @NamespaceList({ // @Namespace( prefix = "xsi", reference = "http://www.w3.org/2001/XMLSchema-instance"), // @Namespace( prefix = "xsd", reference = "http://www.w3.org/2001/XMLSchema"), // @Namespace( prefix = "soap12", reference = "http://www.w3.org/2003/05/soap-envelope") // }) // public class UsStatesResponseEnvelope { // // @Element(required = false, name = "Body") // private UsStatesResponseBody body; // // public UsStatesResponseBody getBody() { // return body; // } // // public void setBody(UsStatesResponseBody body) { // this.body = body; // } // }
import com.asanchezyu.retrofitsoap.api.model.request.UsStatesRequestEnvelope; import com.asanchezyu.retrofitsoap.api.model.response.UsStatesResponseEnvelope; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.Headers; import retrofit2.http.POST;
/* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.api; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public interface UsStatesApi { @Headers({ "Content-Type: text/xml", "Accept-Charset: utf-8" }) @POST("/uszip.asmx")
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/model/request/UsStatesRequestEnvelope.java // @Root(name = "soap12:Envelope") // @NamespaceList({ // @Namespace( prefix = "xsi", reference = "http://www.w3.org/2001/XMLSchema-instance"), // @Namespace( prefix = "xsd", reference = "http://www.w3.org/2001/XMLSchema"), // @Namespace( prefix = "soap12", reference = "http://www.w3.org/2003/05/soap-envelope") // }) // public class UsStatesRequestEnvelope { // // @Element(name = "soap12:Body", required = false) // private UsStatesRequestBody body; // // public UsStatesRequestBody getBody() { // return body; // } // // public void setBody(UsStatesRequestBody body) { // this.body = body; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/model/response/UsStatesResponseEnvelope.java // @Root(name = "soap12:Envelope") // @NamespaceList({ // @Namespace( prefix = "xsi", reference = "http://www.w3.org/2001/XMLSchema-instance"), // @Namespace( prefix = "xsd", reference = "http://www.w3.org/2001/XMLSchema"), // @Namespace( prefix = "soap12", reference = "http://www.w3.org/2003/05/soap-envelope") // }) // public class UsStatesResponseEnvelope { // // @Element(required = false, name = "Body") // private UsStatesResponseBody body; // // public UsStatesResponseBody getBody() { // return body; // } // // public void setBody(UsStatesResponseBody body) { // this.body = body; // } // } // Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/UsStatesApi.java import com.asanchezyu.retrofitsoap.api.model.request.UsStatesRequestEnvelope; import com.asanchezyu.retrofitsoap.api.model.response.UsStatesResponseEnvelope; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.Headers; import retrofit2.http.POST; /* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.api; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ public interface UsStatesApi { @Headers({ "Content-Type: text/xml", "Accept-Charset: utf-8" }) @POST("/uszip.asmx")
Call<UsStatesResponseEnvelope> requestStateInfo(@Body UsStatesRequestEnvelope body);
asanchezyu/RetrofitSoapSample
app/src/main/java/com/asanchezyu/retrofitsoap/injection/application/ApplicationModule.java
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/RetrofitSoapApplication.java // public class RetrofitSoapApplication extends Application { // // private ApplicationComponent component; // // @Override // public void onCreate() { // super.onCreate(); // // component = DaggerApplicationComponent.builder() // .applicationModule( new ApplicationModule(this)) // .build(); // } // // public ApplicationComponent getComponent() { // return component; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/UsStatesApi.java // public interface UsStatesApi { // // @Headers({ // "Content-Type: text/xml", // "Accept-Charset: utf-8" // }) // @POST("/uszip.asmx") // Call<UsStatesResponseEnvelope> requestStateInfo(@Body UsStatesRequestEnvelope body); // // }
import dagger.Provides; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.simplexml.SimpleXmlConverterFactory; import com.asanchezyu.retrofitsoap.RetrofitSoapApplication; import com.asanchezyu.retrofitsoap.api.UsStatesApi; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.Strategy; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module;
/* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.injection.application; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ @Module @Singleton public class ApplicationModule {
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/RetrofitSoapApplication.java // public class RetrofitSoapApplication extends Application { // // private ApplicationComponent component; // // @Override // public void onCreate() { // super.onCreate(); // // component = DaggerApplicationComponent.builder() // .applicationModule( new ApplicationModule(this)) // .build(); // } // // public ApplicationComponent getComponent() { // return component; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/UsStatesApi.java // public interface UsStatesApi { // // @Headers({ // "Content-Type: text/xml", // "Accept-Charset: utf-8" // }) // @POST("/uszip.asmx") // Call<UsStatesResponseEnvelope> requestStateInfo(@Body UsStatesRequestEnvelope body); // // } // Path: app/src/main/java/com/asanchezyu/retrofitsoap/injection/application/ApplicationModule.java import dagger.Provides; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.simplexml.SimpleXmlConverterFactory; import com.asanchezyu.retrofitsoap.RetrofitSoapApplication; import com.asanchezyu.retrofitsoap.api.UsStatesApi; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.Strategy; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; /* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.injection.application; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ @Module @Singleton public class ApplicationModule {
private RetrofitSoapApplication application;
asanchezyu/RetrofitSoapSample
app/src/main/java/com/asanchezyu/retrofitsoap/injection/application/ApplicationModule.java
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/RetrofitSoapApplication.java // public class RetrofitSoapApplication extends Application { // // private ApplicationComponent component; // // @Override // public void onCreate() { // super.onCreate(); // // component = DaggerApplicationComponent.builder() // .applicationModule( new ApplicationModule(this)) // .build(); // } // // public ApplicationComponent getComponent() { // return component; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/UsStatesApi.java // public interface UsStatesApi { // // @Headers({ // "Content-Type: text/xml", // "Accept-Charset: utf-8" // }) // @POST("/uszip.asmx") // Call<UsStatesResponseEnvelope> requestStateInfo(@Body UsStatesRequestEnvelope body); // // }
import dagger.Provides; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.simplexml.SimpleXmlConverterFactory; import com.asanchezyu.retrofitsoap.RetrofitSoapApplication; import com.asanchezyu.retrofitsoap.api.UsStatesApi; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.Strategy; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module;
/* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.injection.application; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ @Module @Singleton public class ApplicationModule { private RetrofitSoapApplication application; public ApplicationModule(RetrofitSoapApplication application) { this.application = application; } @Provides @Singleton
// Path: app/src/main/java/com/asanchezyu/retrofitsoap/RetrofitSoapApplication.java // public class RetrofitSoapApplication extends Application { // // private ApplicationComponent component; // // @Override // public void onCreate() { // super.onCreate(); // // component = DaggerApplicationComponent.builder() // .applicationModule( new ApplicationModule(this)) // .build(); // } // // public ApplicationComponent getComponent() { // return component; // } // } // // Path: app/src/main/java/com/asanchezyu/retrofitsoap/api/UsStatesApi.java // public interface UsStatesApi { // // @Headers({ // "Content-Type: text/xml", // "Accept-Charset: utf-8" // }) // @POST("/uszip.asmx") // Call<UsStatesResponseEnvelope> requestStateInfo(@Body UsStatesRequestEnvelope body); // // } // Path: app/src/main/java/com/asanchezyu/retrofitsoap/injection/application/ApplicationModule.java import dagger.Provides; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.simplexml.SimpleXmlConverterFactory; import com.asanchezyu.retrofitsoap.RetrofitSoapApplication; import com.asanchezyu.retrofitsoap.api.UsStatesApi; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.Strategy; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; /* * Copyright 2016. Alejandro Sánchez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.asanchezyu.retrofitsoap.injection.application; /** * Class Description. * * @author [email protected]. * @version 1.0. * @since 15/6/16. */ @Module @Singleton public class ApplicationModule { private RetrofitSoapApplication application; public ApplicationModule(RetrofitSoapApplication application) { this.application = application; } @Provides @Singleton
public UsStatesApi providesApi(){
PlayFab/JavaSDK
PlayFabServerSDK/src/main/java/com/playfab/PlayFabSettings.java
// Path: PlayFabServerSDK/src/main/java/com/playfab/PlayFabErrors.java // public static interface ErrorCallback { // public void callback(PlayFabError error); // }
import java.lang.StringBuilder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.playfab.PlayFabErrors.ErrorCallback;
package com.playfab; public class PlayFabSettings { public static String SdkVersion = "0.148.220305"; public static String BuildIdentifier = "adobuild_javasdk_117"; public static String SdkVersionString = "JavaSDK-0.148.220305"; public static Map<String, String> RequestGetParams; static { Map<String, String> getParams = new HashMap<String, String>(); getParams.put("sdk", SdkVersionString); RequestGetParams = Collections.unmodifiableMap(getParams); } public static String ProductionEnvironmentUrl = ".playfabapi.com"; // This is only for customers running a private cluster. Generally you shouldn't touch this public static String VerticalName = null; // The name of a customer vertical. This is only for customers running a private cluster. Generally you shouldn't touch this public static String TitleId = null; // You must set this value for PlayFabSdk to work properly (Found in the Game Manager for your title, at the PlayFab Website)
// Path: PlayFabServerSDK/src/main/java/com/playfab/PlayFabErrors.java // public static interface ErrorCallback { // public void callback(PlayFabError error); // } // Path: PlayFabServerSDK/src/main/java/com/playfab/PlayFabSettings.java import java.lang.StringBuilder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.playfab.PlayFabErrors.ErrorCallback; package com.playfab; public class PlayFabSettings { public static String SdkVersion = "0.148.220305"; public static String BuildIdentifier = "adobuild_javasdk_117"; public static String SdkVersionString = "JavaSDK-0.148.220305"; public static Map<String, String> RequestGetParams; static { Map<String, String> getParams = new HashMap<String, String>(); getParams.put("sdk", SdkVersionString); RequestGetParams = Collections.unmodifiableMap(getParams); } public static String ProductionEnvironmentUrl = ".playfabapi.com"; // This is only for customers running a private cluster. Generally you shouldn't touch this public static String VerticalName = null; // The name of a customer vertical. This is only for customers running a private cluster. Generally you shouldn't touch this public static String TitleId = null; // You must set this value for PlayFabSdk to work properly (Found in the Game Manager for your title, at the PlayFab Website)
public static ErrorCallback GlobalErrorHandler;
PlayFab/JavaSDK
AndroidStudioExample/app/src/main/java/com/playfab/PlayFabSettings.java
// Path: PlayFabServerSDK/src/main/java/com/playfab/PlayFabErrors.java // public static interface ErrorCallback { // public void callback(PlayFabError error); // }
import java.lang.StringBuilder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import android.content.Context; import com.playfab.PlayFabErrors.ErrorCallback;
package com.playfab; public class PlayFabSettings { public static String SdkVersion = "0.148.220305"; public static String BuildIdentifier = "adobuild_javasdk_117"; public static String SdkVersionString = "JavaSDK-0.148.220305"; public static Map<String, String> RequestGetParams; static { Map<String, String> getParams = new HashMap<String, String>(); getParams.put("sdk", SdkVersionString); RequestGetParams = Collections.unmodifiableMap(getParams); } public static String ProductionEnvironmentUrl = ".playfabapi.com"; // This is only for customers running a private cluster. Generally you shouldn't touch this public static String VerticalName = null; // The name of a customer vertical. This is only for customers running a private cluster. Generally you shouldn't touch this public static String TitleId = null; // You must set this value for PlayFabSdk to work properly (Found in the Game Manager for your title, at the PlayFab Website)
// Path: PlayFabServerSDK/src/main/java/com/playfab/PlayFabErrors.java // public static interface ErrorCallback { // public void callback(PlayFabError error); // } // Path: AndroidStudioExample/app/src/main/java/com/playfab/PlayFabSettings.java import java.lang.StringBuilder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import android.content.Context; import com.playfab.PlayFabErrors.ErrorCallback; package com.playfab; public class PlayFabSettings { public static String SdkVersion = "0.148.220305"; public static String BuildIdentifier = "adobuild_javasdk_117"; public static String SdkVersionString = "JavaSDK-0.148.220305"; public static Map<String, String> RequestGetParams; static { Map<String, String> getParams = new HashMap<String, String>(); getParams.put("sdk", SdkVersionString); RequestGetParams = Collections.unmodifiableMap(getParams); } public static String ProductionEnvironmentUrl = ".playfabapi.com"; // This is only for customers running a private cluster. Generally you shouldn't touch this public static String VerticalName = null; // The name of a customer vertical. This is only for customers running a private cluster. Generally you shouldn't touch this public static String TitleId = null; // You must set this value for PlayFabSdk to work properly (Found in the Game Manager for your title, at the PlayFab Website)
public static ErrorCallback GlobalErrorHandler;
KalebKE/FSensor
fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAccelerationFusion.java
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/filter/gyroscope/fusion/OrientationFused.java // public abstract class OrientationFused extends BaseFilter { // // protected static final float EPSILON = 0.000000001f; // // Nano-second to second conversion // protected static final float NS2S = 1.0f / 1000000000.0f; // private static final String tag = OrientationFused.class.getSimpleName(); // public static float DEFAULT_TIME_CONSTANT = 0.18f; // // The coefficient for the fusedOrientation... 0.5 = means it is averaging the two // // transfer functions (rotations from the gyroscope and // // acceleration/magnetic, respectively). // public float timeConstant; // protected Quaternion rotationVector; // protected long timestamp = 0; // protected float[] output = new float[3]; // // /** // * Initialize a singleton instance. // */ // public OrientationFused() { // this(DEFAULT_TIME_CONSTANT); // } // // public OrientationFused(float timeConstant) { // this.timeConstant = timeConstant; // // } // // @Override // public float[] getOutput() { // return output; // } // // public void reset() { // timestamp = 0; // rotationVector = null; // } // // public boolean isBaseOrientationSet() { // return rotationVector != null; // } // // /** // * The complementary fusedOrientation coefficient, a floating point value between 0-1, // * exclusive of 0, inclusive of 1. // * // * @param timeConstant // */ // public void setTimeConstant(float timeConstant) { // this.timeConstant = timeConstant; // } // // /** // * Calculate the fused orientation of the device. // * @param gyroscope the gyroscope measurements. // * @param timestamp the gyroscope timestamp // * @param acceleration the acceleration measurements // * @param magnetic the magnetic measurements // * @return the fused orientation estimation. // */ // public abstract float[] calculateFusedOrientation(float[] gyroscope, long timestamp, float[] acceleration, float[] magnetic); // // public void setBaseOrientation(Quaternion baseOrientation) { // rotationVector = baseOrientation; // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/util/gravity/GravityUtil.java // public class GravityUtil { // // private static final String tag = GravityUtil.class.getSimpleName(); // // private static float[] gravity = new float[]{SensorManager.GRAVITY_EARTH, SensorManager.GRAVITY_EARTH, SensorManager.GRAVITY_EARTH}; // // /** // * Assumes a positive, counter-clockwise, right-handed rotation // * orientation[0] = pitch, rotation around the X axis. // * orientation[1] = roll, rotation around the Y axis // * orientation[2] = azimuth, rotation around the Z axis // * @param orientation The orientation. // * @return The gravity components of the orientation. // */ // public static float[] getGravityFromOrientation(float[] orientation) { // // float[] components = new float[3]; // // float pitch = orientation[1]; // float roll = orientation[2]; // // // Find the gravity component of the X-axis // // = g*-cos(pitch)*sin(roll); // components[0] = (float) -(gravity[0] // * -Math.cos(pitch) * Math // .sin(roll)); // // // Find the gravity component of the Y-axis // // = g*-sin(pitch); // components[1] = (float) (gravity[1] * -Math // .sin(pitch)); // // // Find the gravity component of the Z-axis // // = g*cos(pitch)*cos(roll); // components[2] = (float) (gravity[2] // * Math.cos(pitch) * Math.cos(roll)); // // return components; // } // // /** // * Set the gravity as measured by the sensor. Defaults to SensorManager.GRAVITY_EARTH // * @param g the gravity of earth in units of m/s^2 // */ // public static void setGravity(float[] g) { // gravity = g; // } // }
import com.kircherelectronics.fsensor.filter.gyroscope.fusion.OrientationFused; import com.kircherelectronics.fsensor.util.gravity.GravityUtil;
package com.kircherelectronics.fsensor.linearacceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * A wrapper for Linear Acceleration filters that are backed by sensor fusions. * * Created by kaleb on 7/6/17. */ public class LinearAccelerationFusion extends LinearAcceleration { public LinearAccelerationFusion(OrientationFused orientationFused) { super(orientationFused); } @Override public float[] getGravity() {
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/filter/gyroscope/fusion/OrientationFused.java // public abstract class OrientationFused extends BaseFilter { // // protected static final float EPSILON = 0.000000001f; // // Nano-second to second conversion // protected static final float NS2S = 1.0f / 1000000000.0f; // private static final String tag = OrientationFused.class.getSimpleName(); // public static float DEFAULT_TIME_CONSTANT = 0.18f; // // The coefficient for the fusedOrientation... 0.5 = means it is averaging the two // // transfer functions (rotations from the gyroscope and // // acceleration/magnetic, respectively). // public float timeConstant; // protected Quaternion rotationVector; // protected long timestamp = 0; // protected float[] output = new float[3]; // // /** // * Initialize a singleton instance. // */ // public OrientationFused() { // this(DEFAULT_TIME_CONSTANT); // } // // public OrientationFused(float timeConstant) { // this.timeConstant = timeConstant; // // } // // @Override // public float[] getOutput() { // return output; // } // // public void reset() { // timestamp = 0; // rotationVector = null; // } // // public boolean isBaseOrientationSet() { // return rotationVector != null; // } // // /** // * The complementary fusedOrientation coefficient, a floating point value between 0-1, // * exclusive of 0, inclusive of 1. // * // * @param timeConstant // */ // public void setTimeConstant(float timeConstant) { // this.timeConstant = timeConstant; // } // // /** // * Calculate the fused orientation of the device. // * @param gyroscope the gyroscope measurements. // * @param timestamp the gyroscope timestamp // * @param acceleration the acceleration measurements // * @param magnetic the magnetic measurements // * @return the fused orientation estimation. // */ // public abstract float[] calculateFusedOrientation(float[] gyroscope, long timestamp, float[] acceleration, float[] magnetic); // // public void setBaseOrientation(Quaternion baseOrientation) { // rotationVector = baseOrientation; // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/util/gravity/GravityUtil.java // public class GravityUtil { // // private static final String tag = GravityUtil.class.getSimpleName(); // // private static float[] gravity = new float[]{SensorManager.GRAVITY_EARTH, SensorManager.GRAVITY_EARTH, SensorManager.GRAVITY_EARTH}; // // /** // * Assumes a positive, counter-clockwise, right-handed rotation // * orientation[0] = pitch, rotation around the X axis. // * orientation[1] = roll, rotation around the Y axis // * orientation[2] = azimuth, rotation around the Z axis // * @param orientation The orientation. // * @return The gravity components of the orientation. // */ // public static float[] getGravityFromOrientation(float[] orientation) { // // float[] components = new float[3]; // // float pitch = orientation[1]; // float roll = orientation[2]; // // // Find the gravity component of the X-axis // // = g*-cos(pitch)*sin(roll); // components[0] = (float) -(gravity[0] // * -Math.cos(pitch) * Math // .sin(roll)); // // // Find the gravity component of the Y-axis // // = g*-sin(pitch); // components[1] = (float) (gravity[1] * -Math // .sin(pitch)); // // // Find the gravity component of the Z-axis // // = g*cos(pitch)*cos(roll); // components[2] = (float) (gravity[2] // * Math.cos(pitch) * Math.cos(roll)); // // return components; // } // // /** // * Set the gravity as measured by the sensor. Defaults to SensorManager.GRAVITY_EARTH // * @param g the gravity of earth in units of m/s^2 // */ // public static void setGravity(float[] g) { // gravity = g; // } // } // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAccelerationFusion.java import com.kircherelectronics.fsensor.filter.gyroscope.fusion.OrientationFused; import com.kircherelectronics.fsensor.util.gravity.GravityUtil; package com.kircherelectronics.fsensor.linearacceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * A wrapper for Linear Acceleration filters that are backed by sensor fusions. * * Created by kaleb on 7/6/17. */ public class LinearAccelerationFusion extends LinearAcceleration { public LinearAccelerationFusion(OrientationFused orientationFused) { super(orientationFused); } @Override public float[] getGravity() {
return GravityUtil.getGravityFromOrientation(filter.getOutput());
KalebKE/FSensor
fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAcceleration.java
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/BaseFilter.java // public abstract class BaseFilter { // public abstract float[] getOutput(); // }
import com.kircherelectronics.fsensor.BaseFilter;
package com.kircherelectronics.fsensor.linearacceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * A base implementation of a linear acceleration fusedOrientation. Linear acceleration is defined as * linearAcceleration = (acceleration - gravity). An acceleration sensor by itself is not capable of determining the * difference between gravity/tilt and true linear acceleration. There are standalone-sensor weighted averaging methods * as well as multi-sensor fusion methods available to estimate linear acceleration. * * @author Kaleb */ public abstract class LinearAcceleration { private static final String tag = LinearAcceleration.class.getSimpleName(); private final float[] output = new float[]{0, 0, 0};
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/BaseFilter.java // public abstract class BaseFilter { // public abstract float[] getOutput(); // } // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAcceleration.java import com.kircherelectronics.fsensor.BaseFilter; package com.kircherelectronics.fsensor.linearacceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /** * A base implementation of a linear acceleration fusedOrientation. Linear acceleration is defined as * linearAcceleration = (acceleration - gravity). An acceleration sensor by itself is not capable of determining the * difference between gravity/tilt and true linear acceleration. There are standalone-sensor weighted averaging methods * as well as multi-sensor fusion methods available to estimate linear acceleration. * * @author Kaleb */ public abstract class LinearAcceleration { private static final String tag = LinearAcceleration.class.getSimpleName(); private final float[] output = new float[]{0, 0, 0};
protected final BaseFilter filter;
KalebKE/FSensor
fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/acceleration/AccelerationSensor.java
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/observer/SensorSubject.java // public class SensorSubject { // private final List<SensorObserver> observers = new ArrayList<>(); // // public interface SensorObserver { // void onSensorChanged(float[] values); // } // // public void register(SensorObserver observer) { // if(!observers.contains(observer)) { // observers.add(observer); // } // } // // public void unregister(SensorObserver observer) { // observers.remove(observer); // } // // public void onNext(float[] values) { // for(int i = 0; i < observers.size(); i++) { // observers.get(i).onSensorChanged(values); // } // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/FSensor.java // public interface FSensor { // void register(SensorSubject.SensorObserver sensorObserver); // void unregister(SensorSubject.SensorObserver sensorObserver); // // void start(); // void stop(); // void reset(); // }
import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.kircherelectronics.fsensor.observer.SensorSubject; import com.kircherelectronics.fsensor.sensor.FSensor;
package com.kircherelectronics.fsensor.sensor.acceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ public class AccelerationSensor implements FSensor { private static final String TAG = AccelerationSensor.class.getSimpleName(); private final SensorManager sensorManager; private final SimpleSensorListener listener; private float startTime = 0; private int count = 0; private float[] acceleration = new float[3]; private float[] output = new float[4]; private int sensorDelay = SensorManager.SENSOR_DELAY_FASTEST;
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/observer/SensorSubject.java // public class SensorSubject { // private final List<SensorObserver> observers = new ArrayList<>(); // // public interface SensorObserver { // void onSensorChanged(float[] values); // } // // public void register(SensorObserver observer) { // if(!observers.contains(observer)) { // observers.add(observer); // } // } // // public void unregister(SensorObserver observer) { // observers.remove(observer); // } // // public void onNext(float[] values) { // for(int i = 0; i < observers.size(); i++) { // observers.get(i).onSensorChanged(values); // } // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/FSensor.java // public interface FSensor { // void register(SensorSubject.SensorObserver sensorObserver); // void unregister(SensorSubject.SensorObserver sensorObserver); // // void start(); // void stop(); // void reset(); // } // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/acceleration/AccelerationSensor.java import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.kircherelectronics.fsensor.observer.SensorSubject; import com.kircherelectronics.fsensor.sensor.FSensor; package com.kircherelectronics.fsensor.sensor.acceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ public class AccelerationSensor implements FSensor { private static final String TAG = AccelerationSensor.class.getSimpleName(); private final SensorManager sensorManager; private final SimpleSensorListener listener; private float startTime = 0; private int count = 0; private float[] acceleration = new float[3]; private float[] output = new float[4]; private int sensorDelay = SensorManager.SENSOR_DELAY_FASTEST;
private final SensorSubject sensorSubject;
KalebKE/FSensor
fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/acceleration/LowPassLinearAccelerationSensor.java
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/filter/averaging/LowPassFilter.java // public class LowPassFilter extends AveragingFilter // { // private static final String tag = LowPassFilter.class.getSimpleName(); // // // Gravity and linear accelerations components for the // // Wikipedia low-pass fusedOrientation // private float[] output; // // public LowPassFilter() { // this(DEFAULT_TIME_CONSTANT); // } // // public LowPassFilter(float timeConstant) { // this.timeConstant = timeConstant; // reset(); // } // // /** // * Add a sample. // * // * @param values // * The acceleration data. A 1x3 matrix containing the data from the X, Y and Z axis of the sensor // * noting that order is arbitrary. // * @return Returns the output of the fusedOrientation. // */ // public float[] filter(float[] values) // { // // Initialize the start time. // if (startTime == 0) // { // startTime = System.nanoTime(); // } // // timestamp = System.nanoTime(); // // // Find the sample period (between updates) and convert from // // nanoseconds to seconds. Note that the sensor delivery rates can // // individually vary by a relatively large time frame, so we use an // // averaging technique with the number of sensor updates to // // determine the delivery rate. // float dt = 1 / (count++ / ((timestamp - startTime) / 1000000000.0f)); // // float alpha = timeConstant / (timeConstant + dt); // // output[0] = alpha * output[0] + (1 - alpha) * values[0]; // output[1] = alpha * output[1] + (1 - alpha) * values[1]; // output[2] = alpha * output[2] + (1 - alpha) * values[2]; // // return output; // } // // @Override // public float[] getOutput() { // return output; // } // // public void setTimeConstant(float timeConstant) // { // this.timeConstant = timeConstant; // } // // public void reset() // { // super.reset(); // this.output = new float[] // { 0, 0, 0 }; // // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAcceleration.java // public abstract class LinearAcceleration { // // private static final String tag = LinearAcceleration.class.getSimpleName(); // // private final float[] output = new float[]{0, 0, 0}; // // protected final BaseFilter filter; // // public LinearAcceleration(BaseFilter filter) { // this.filter = filter; // } // // public float[] filter(float[] values) { // // float[] gravity = getGravity(); // // // Determine the linear acceleration // output[0] = values[0] - gravity[0]; // output[1] = values[1] - gravity[1]; // output[2] = values[2] - gravity[2]; // // return output; // } // // public abstract float[] getGravity(); // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAccelerationAveraging.java // public class LinearAccelerationAveraging extends LinearAcceleration { // // public LinearAccelerationAveraging(AveragingFilter averagingFilter) { // super(averagingFilter); // } // // @Override // public float[] getGravity() { // return filter.getOutput(); // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/observer/SensorSubject.java // public class SensorSubject { // private final List<SensorObserver> observers = new ArrayList<>(); // // public interface SensorObserver { // void onSensorChanged(float[] values); // } // // public void register(SensorObserver observer) { // if(!observers.contains(observer)) { // observers.add(observer); // } // } // // public void unregister(SensorObserver observer) { // observers.remove(observer); // } // // public void onNext(float[] values) { // for(int i = 0; i < observers.size(); i++) { // observers.get(i).onSensorChanged(values); // } // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/FSensor.java // public interface FSensor { // void register(SensorSubject.SensorObserver sensorObserver); // void unregister(SensorSubject.SensorObserver sensorObserver); // // void start(); // void stop(); // void reset(); // }
import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.kircherelectronics.fsensor.filter.averaging.LowPassFilter; import com.kircherelectronics.fsensor.linearacceleration.LinearAcceleration; import com.kircherelectronics.fsensor.linearacceleration.LinearAccelerationAveraging; import com.kircherelectronics.fsensor.observer.SensorSubject; import com.kircherelectronics.fsensor.sensor.FSensor;
package com.kircherelectronics.fsensor.sensor.acceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ public class LowPassLinearAccelerationSensor implements FSensor { private static final String TAG = LowPassLinearAccelerationSensor.class.getSimpleName(); private final SensorManager sensorManager; private final SimpleSensorListener listener; private float startTime = 0; private int count = 0; private float[] rawAcceleration = new float[3]; private float[] acceleration = new float[3]; private float[] output = new float[4];
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/filter/averaging/LowPassFilter.java // public class LowPassFilter extends AveragingFilter // { // private static final String tag = LowPassFilter.class.getSimpleName(); // // // Gravity and linear accelerations components for the // // Wikipedia low-pass fusedOrientation // private float[] output; // // public LowPassFilter() { // this(DEFAULT_TIME_CONSTANT); // } // // public LowPassFilter(float timeConstant) { // this.timeConstant = timeConstant; // reset(); // } // // /** // * Add a sample. // * // * @param values // * The acceleration data. A 1x3 matrix containing the data from the X, Y and Z axis of the sensor // * noting that order is arbitrary. // * @return Returns the output of the fusedOrientation. // */ // public float[] filter(float[] values) // { // // Initialize the start time. // if (startTime == 0) // { // startTime = System.nanoTime(); // } // // timestamp = System.nanoTime(); // // // Find the sample period (between updates) and convert from // // nanoseconds to seconds. Note that the sensor delivery rates can // // individually vary by a relatively large time frame, so we use an // // averaging technique with the number of sensor updates to // // determine the delivery rate. // float dt = 1 / (count++ / ((timestamp - startTime) / 1000000000.0f)); // // float alpha = timeConstant / (timeConstant + dt); // // output[0] = alpha * output[0] + (1 - alpha) * values[0]; // output[1] = alpha * output[1] + (1 - alpha) * values[1]; // output[2] = alpha * output[2] + (1 - alpha) * values[2]; // // return output; // } // // @Override // public float[] getOutput() { // return output; // } // // public void setTimeConstant(float timeConstant) // { // this.timeConstant = timeConstant; // } // // public void reset() // { // super.reset(); // this.output = new float[] // { 0, 0, 0 }; // // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAcceleration.java // public abstract class LinearAcceleration { // // private static final String tag = LinearAcceleration.class.getSimpleName(); // // private final float[] output = new float[]{0, 0, 0}; // // protected final BaseFilter filter; // // public LinearAcceleration(BaseFilter filter) { // this.filter = filter; // } // // public float[] filter(float[] values) { // // float[] gravity = getGravity(); // // // Determine the linear acceleration // output[0] = values[0] - gravity[0]; // output[1] = values[1] - gravity[1]; // output[2] = values[2] - gravity[2]; // // return output; // } // // public abstract float[] getGravity(); // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAccelerationAveraging.java // public class LinearAccelerationAveraging extends LinearAcceleration { // // public LinearAccelerationAveraging(AveragingFilter averagingFilter) { // super(averagingFilter); // } // // @Override // public float[] getGravity() { // return filter.getOutput(); // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/observer/SensorSubject.java // public class SensorSubject { // private final List<SensorObserver> observers = new ArrayList<>(); // // public interface SensorObserver { // void onSensorChanged(float[] values); // } // // public void register(SensorObserver observer) { // if(!observers.contains(observer)) { // observers.add(observer); // } // } // // public void unregister(SensorObserver observer) { // observers.remove(observer); // } // // public void onNext(float[] values) { // for(int i = 0; i < observers.size(); i++) { // observers.get(i).onSensorChanged(values); // } // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/FSensor.java // public interface FSensor { // void register(SensorSubject.SensorObserver sensorObserver); // void unregister(SensorSubject.SensorObserver sensorObserver); // // void start(); // void stop(); // void reset(); // } // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/acceleration/LowPassLinearAccelerationSensor.java import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.kircherelectronics.fsensor.filter.averaging.LowPassFilter; import com.kircherelectronics.fsensor.linearacceleration.LinearAcceleration; import com.kircherelectronics.fsensor.linearacceleration.LinearAccelerationAveraging; import com.kircherelectronics.fsensor.observer.SensorSubject; import com.kircherelectronics.fsensor.sensor.FSensor; package com.kircherelectronics.fsensor.sensor.acceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ public class LowPassLinearAccelerationSensor implements FSensor { private static final String TAG = LowPassLinearAccelerationSensor.class.getSimpleName(); private final SensorManager sensorManager; private final SimpleSensorListener listener; private float startTime = 0; private int count = 0; private float[] rawAcceleration = new float[3]; private float[] acceleration = new float[3]; private float[] output = new float[4];
private LinearAcceleration linearAccelerationFilterLpf;
KalebKE/FSensor
fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/acceleration/LowPassLinearAccelerationSensor.java
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/filter/averaging/LowPassFilter.java // public class LowPassFilter extends AveragingFilter // { // private static final String tag = LowPassFilter.class.getSimpleName(); // // // Gravity and linear accelerations components for the // // Wikipedia low-pass fusedOrientation // private float[] output; // // public LowPassFilter() { // this(DEFAULT_TIME_CONSTANT); // } // // public LowPassFilter(float timeConstant) { // this.timeConstant = timeConstant; // reset(); // } // // /** // * Add a sample. // * // * @param values // * The acceleration data. A 1x3 matrix containing the data from the X, Y and Z axis of the sensor // * noting that order is arbitrary. // * @return Returns the output of the fusedOrientation. // */ // public float[] filter(float[] values) // { // // Initialize the start time. // if (startTime == 0) // { // startTime = System.nanoTime(); // } // // timestamp = System.nanoTime(); // // // Find the sample period (between updates) and convert from // // nanoseconds to seconds. Note that the sensor delivery rates can // // individually vary by a relatively large time frame, so we use an // // averaging technique with the number of sensor updates to // // determine the delivery rate. // float dt = 1 / (count++ / ((timestamp - startTime) / 1000000000.0f)); // // float alpha = timeConstant / (timeConstant + dt); // // output[0] = alpha * output[0] + (1 - alpha) * values[0]; // output[1] = alpha * output[1] + (1 - alpha) * values[1]; // output[2] = alpha * output[2] + (1 - alpha) * values[2]; // // return output; // } // // @Override // public float[] getOutput() { // return output; // } // // public void setTimeConstant(float timeConstant) // { // this.timeConstant = timeConstant; // } // // public void reset() // { // super.reset(); // this.output = new float[] // { 0, 0, 0 }; // // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAcceleration.java // public abstract class LinearAcceleration { // // private static final String tag = LinearAcceleration.class.getSimpleName(); // // private final float[] output = new float[]{0, 0, 0}; // // protected final BaseFilter filter; // // public LinearAcceleration(BaseFilter filter) { // this.filter = filter; // } // // public float[] filter(float[] values) { // // float[] gravity = getGravity(); // // // Determine the linear acceleration // output[0] = values[0] - gravity[0]; // output[1] = values[1] - gravity[1]; // output[2] = values[2] - gravity[2]; // // return output; // } // // public abstract float[] getGravity(); // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAccelerationAveraging.java // public class LinearAccelerationAveraging extends LinearAcceleration { // // public LinearAccelerationAveraging(AveragingFilter averagingFilter) { // super(averagingFilter); // } // // @Override // public float[] getGravity() { // return filter.getOutput(); // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/observer/SensorSubject.java // public class SensorSubject { // private final List<SensorObserver> observers = new ArrayList<>(); // // public interface SensorObserver { // void onSensorChanged(float[] values); // } // // public void register(SensorObserver observer) { // if(!observers.contains(observer)) { // observers.add(observer); // } // } // // public void unregister(SensorObserver observer) { // observers.remove(observer); // } // // public void onNext(float[] values) { // for(int i = 0; i < observers.size(); i++) { // observers.get(i).onSensorChanged(values); // } // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/FSensor.java // public interface FSensor { // void register(SensorSubject.SensorObserver sensorObserver); // void unregister(SensorSubject.SensorObserver sensorObserver); // // void start(); // void stop(); // void reset(); // }
import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.kircherelectronics.fsensor.filter.averaging.LowPassFilter; import com.kircherelectronics.fsensor.linearacceleration.LinearAcceleration; import com.kircherelectronics.fsensor.linearacceleration.LinearAccelerationAveraging; import com.kircherelectronics.fsensor.observer.SensorSubject; import com.kircherelectronics.fsensor.sensor.FSensor;
package com.kircherelectronics.fsensor.sensor.acceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ public class LowPassLinearAccelerationSensor implements FSensor { private static final String TAG = LowPassLinearAccelerationSensor.class.getSimpleName(); private final SensorManager sensorManager; private final SimpleSensorListener listener; private float startTime = 0; private int count = 0; private float[] rawAcceleration = new float[3]; private float[] acceleration = new float[3]; private float[] output = new float[4]; private LinearAcceleration linearAccelerationFilterLpf;
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/filter/averaging/LowPassFilter.java // public class LowPassFilter extends AveragingFilter // { // private static final String tag = LowPassFilter.class.getSimpleName(); // // // Gravity and linear accelerations components for the // // Wikipedia low-pass fusedOrientation // private float[] output; // // public LowPassFilter() { // this(DEFAULT_TIME_CONSTANT); // } // // public LowPassFilter(float timeConstant) { // this.timeConstant = timeConstant; // reset(); // } // // /** // * Add a sample. // * // * @param values // * The acceleration data. A 1x3 matrix containing the data from the X, Y and Z axis of the sensor // * noting that order is arbitrary. // * @return Returns the output of the fusedOrientation. // */ // public float[] filter(float[] values) // { // // Initialize the start time. // if (startTime == 0) // { // startTime = System.nanoTime(); // } // // timestamp = System.nanoTime(); // // // Find the sample period (between updates) and convert from // // nanoseconds to seconds. Note that the sensor delivery rates can // // individually vary by a relatively large time frame, so we use an // // averaging technique with the number of sensor updates to // // determine the delivery rate. // float dt = 1 / (count++ / ((timestamp - startTime) / 1000000000.0f)); // // float alpha = timeConstant / (timeConstant + dt); // // output[0] = alpha * output[0] + (1 - alpha) * values[0]; // output[1] = alpha * output[1] + (1 - alpha) * values[1]; // output[2] = alpha * output[2] + (1 - alpha) * values[2]; // // return output; // } // // @Override // public float[] getOutput() { // return output; // } // // public void setTimeConstant(float timeConstant) // { // this.timeConstant = timeConstant; // } // // public void reset() // { // super.reset(); // this.output = new float[] // { 0, 0, 0 }; // // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAcceleration.java // public abstract class LinearAcceleration { // // private static final String tag = LinearAcceleration.class.getSimpleName(); // // private final float[] output = new float[]{0, 0, 0}; // // protected final BaseFilter filter; // // public LinearAcceleration(BaseFilter filter) { // this.filter = filter; // } // // public float[] filter(float[] values) { // // float[] gravity = getGravity(); // // // Determine the linear acceleration // output[0] = values[0] - gravity[0]; // output[1] = values[1] - gravity[1]; // output[2] = values[2] - gravity[2]; // // return output; // } // // public abstract float[] getGravity(); // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAccelerationAveraging.java // public class LinearAccelerationAveraging extends LinearAcceleration { // // public LinearAccelerationAveraging(AveragingFilter averagingFilter) { // super(averagingFilter); // } // // @Override // public float[] getGravity() { // return filter.getOutput(); // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/observer/SensorSubject.java // public class SensorSubject { // private final List<SensorObserver> observers = new ArrayList<>(); // // public interface SensorObserver { // void onSensorChanged(float[] values); // } // // public void register(SensorObserver observer) { // if(!observers.contains(observer)) { // observers.add(observer); // } // } // // public void unregister(SensorObserver observer) { // observers.remove(observer); // } // // public void onNext(float[] values) { // for(int i = 0; i < observers.size(); i++) { // observers.get(i).onSensorChanged(values); // } // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/FSensor.java // public interface FSensor { // void register(SensorSubject.SensorObserver sensorObserver); // void unregister(SensorSubject.SensorObserver sensorObserver); // // void start(); // void stop(); // void reset(); // } // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/acceleration/LowPassLinearAccelerationSensor.java import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.kircherelectronics.fsensor.filter.averaging.LowPassFilter; import com.kircherelectronics.fsensor.linearacceleration.LinearAcceleration; import com.kircherelectronics.fsensor.linearacceleration.LinearAccelerationAveraging; import com.kircherelectronics.fsensor.observer.SensorSubject; import com.kircherelectronics.fsensor.sensor.FSensor; package com.kircherelectronics.fsensor.sensor.acceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ public class LowPassLinearAccelerationSensor implements FSensor { private static final String TAG = LowPassLinearAccelerationSensor.class.getSimpleName(); private final SensorManager sensorManager; private final SimpleSensorListener listener; private float startTime = 0; private int count = 0; private float[] rawAcceleration = new float[3]; private float[] acceleration = new float[3]; private float[] output = new float[4]; private LinearAcceleration linearAccelerationFilterLpf;
private LowPassFilter lpfGravity;
KalebKE/FSensor
fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/acceleration/LowPassLinearAccelerationSensor.java
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/filter/averaging/LowPassFilter.java // public class LowPassFilter extends AveragingFilter // { // private static final String tag = LowPassFilter.class.getSimpleName(); // // // Gravity and linear accelerations components for the // // Wikipedia low-pass fusedOrientation // private float[] output; // // public LowPassFilter() { // this(DEFAULT_TIME_CONSTANT); // } // // public LowPassFilter(float timeConstant) { // this.timeConstant = timeConstant; // reset(); // } // // /** // * Add a sample. // * // * @param values // * The acceleration data. A 1x3 matrix containing the data from the X, Y and Z axis of the sensor // * noting that order is arbitrary. // * @return Returns the output of the fusedOrientation. // */ // public float[] filter(float[] values) // { // // Initialize the start time. // if (startTime == 0) // { // startTime = System.nanoTime(); // } // // timestamp = System.nanoTime(); // // // Find the sample period (between updates) and convert from // // nanoseconds to seconds. Note that the sensor delivery rates can // // individually vary by a relatively large time frame, so we use an // // averaging technique with the number of sensor updates to // // determine the delivery rate. // float dt = 1 / (count++ / ((timestamp - startTime) / 1000000000.0f)); // // float alpha = timeConstant / (timeConstant + dt); // // output[0] = alpha * output[0] + (1 - alpha) * values[0]; // output[1] = alpha * output[1] + (1 - alpha) * values[1]; // output[2] = alpha * output[2] + (1 - alpha) * values[2]; // // return output; // } // // @Override // public float[] getOutput() { // return output; // } // // public void setTimeConstant(float timeConstant) // { // this.timeConstant = timeConstant; // } // // public void reset() // { // super.reset(); // this.output = new float[] // { 0, 0, 0 }; // // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAcceleration.java // public abstract class LinearAcceleration { // // private static final String tag = LinearAcceleration.class.getSimpleName(); // // private final float[] output = new float[]{0, 0, 0}; // // protected final BaseFilter filter; // // public LinearAcceleration(BaseFilter filter) { // this.filter = filter; // } // // public float[] filter(float[] values) { // // float[] gravity = getGravity(); // // // Determine the linear acceleration // output[0] = values[0] - gravity[0]; // output[1] = values[1] - gravity[1]; // output[2] = values[2] - gravity[2]; // // return output; // } // // public abstract float[] getGravity(); // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAccelerationAveraging.java // public class LinearAccelerationAveraging extends LinearAcceleration { // // public LinearAccelerationAveraging(AveragingFilter averagingFilter) { // super(averagingFilter); // } // // @Override // public float[] getGravity() { // return filter.getOutput(); // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/observer/SensorSubject.java // public class SensorSubject { // private final List<SensorObserver> observers = new ArrayList<>(); // // public interface SensorObserver { // void onSensorChanged(float[] values); // } // // public void register(SensorObserver observer) { // if(!observers.contains(observer)) { // observers.add(observer); // } // } // // public void unregister(SensorObserver observer) { // observers.remove(observer); // } // // public void onNext(float[] values) { // for(int i = 0; i < observers.size(); i++) { // observers.get(i).onSensorChanged(values); // } // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/FSensor.java // public interface FSensor { // void register(SensorSubject.SensorObserver sensorObserver); // void unregister(SensorSubject.SensorObserver sensorObserver); // // void start(); // void stop(); // void reset(); // }
import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.kircherelectronics.fsensor.filter.averaging.LowPassFilter; import com.kircherelectronics.fsensor.linearacceleration.LinearAcceleration; import com.kircherelectronics.fsensor.linearacceleration.LinearAccelerationAveraging; import com.kircherelectronics.fsensor.observer.SensorSubject; import com.kircherelectronics.fsensor.sensor.FSensor;
start(); } private float calculateSensorFrequency() { // Initialize the start time. if (startTime == 0) { startTime = System.nanoTime(); } long timestamp = System.nanoTime(); // Find the sample period (between updates) and convert from // nanoseconds to seconds. Note that the sensor delivery rates can // individually vary by a relatively large time frame, so we use an // averaging technique with the number of sensor updates to // determine the delivery rate. return (count++ / ((timestamp - startTime) / 1000000000.0f)); } private float[] invert(float[] values) { for (int i = 0; i < values.length; i++) { values[i] = -values[i]; } return values; } private void initializeFSensorFusions() { lpfGravity = new LowPassFilter();
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/filter/averaging/LowPassFilter.java // public class LowPassFilter extends AveragingFilter // { // private static final String tag = LowPassFilter.class.getSimpleName(); // // // Gravity and linear accelerations components for the // // Wikipedia low-pass fusedOrientation // private float[] output; // // public LowPassFilter() { // this(DEFAULT_TIME_CONSTANT); // } // // public LowPassFilter(float timeConstant) { // this.timeConstant = timeConstant; // reset(); // } // // /** // * Add a sample. // * // * @param values // * The acceleration data. A 1x3 matrix containing the data from the X, Y and Z axis of the sensor // * noting that order is arbitrary. // * @return Returns the output of the fusedOrientation. // */ // public float[] filter(float[] values) // { // // Initialize the start time. // if (startTime == 0) // { // startTime = System.nanoTime(); // } // // timestamp = System.nanoTime(); // // // Find the sample period (between updates) and convert from // // nanoseconds to seconds. Note that the sensor delivery rates can // // individually vary by a relatively large time frame, so we use an // // averaging technique with the number of sensor updates to // // determine the delivery rate. // float dt = 1 / (count++ / ((timestamp - startTime) / 1000000000.0f)); // // float alpha = timeConstant / (timeConstant + dt); // // output[0] = alpha * output[0] + (1 - alpha) * values[0]; // output[1] = alpha * output[1] + (1 - alpha) * values[1]; // output[2] = alpha * output[2] + (1 - alpha) * values[2]; // // return output; // } // // @Override // public float[] getOutput() { // return output; // } // // public void setTimeConstant(float timeConstant) // { // this.timeConstant = timeConstant; // } // // public void reset() // { // super.reset(); // this.output = new float[] // { 0, 0, 0 }; // // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAcceleration.java // public abstract class LinearAcceleration { // // private static final String tag = LinearAcceleration.class.getSimpleName(); // // private final float[] output = new float[]{0, 0, 0}; // // protected final BaseFilter filter; // // public LinearAcceleration(BaseFilter filter) { // this.filter = filter; // } // // public float[] filter(float[] values) { // // float[] gravity = getGravity(); // // // Determine the linear acceleration // output[0] = values[0] - gravity[0]; // output[1] = values[1] - gravity[1]; // output[2] = values[2] - gravity[2]; // // return output; // } // // public abstract float[] getGravity(); // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/linearacceleration/LinearAccelerationAveraging.java // public class LinearAccelerationAveraging extends LinearAcceleration { // // public LinearAccelerationAveraging(AveragingFilter averagingFilter) { // super(averagingFilter); // } // // @Override // public float[] getGravity() { // return filter.getOutput(); // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/observer/SensorSubject.java // public class SensorSubject { // private final List<SensorObserver> observers = new ArrayList<>(); // // public interface SensorObserver { // void onSensorChanged(float[] values); // } // // public void register(SensorObserver observer) { // if(!observers.contains(observer)) { // observers.add(observer); // } // } // // public void unregister(SensorObserver observer) { // observers.remove(observer); // } // // public void onNext(float[] values) { // for(int i = 0; i < observers.size(); i++) { // observers.get(i).onSensorChanged(values); // } // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/FSensor.java // public interface FSensor { // void register(SensorSubject.SensorObserver sensorObserver); // void unregister(SensorSubject.SensorObserver sensorObserver); // // void start(); // void stop(); // void reset(); // } // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/acceleration/LowPassLinearAccelerationSensor.java import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.kircherelectronics.fsensor.filter.averaging.LowPassFilter; import com.kircherelectronics.fsensor.linearacceleration.LinearAcceleration; import com.kircherelectronics.fsensor.linearacceleration.LinearAccelerationAveraging; import com.kircherelectronics.fsensor.observer.SensorSubject; import com.kircherelectronics.fsensor.sensor.FSensor; start(); } private float calculateSensorFrequency() { // Initialize the start time. if (startTime == 0) { startTime = System.nanoTime(); } long timestamp = System.nanoTime(); // Find the sample period (between updates) and convert from // nanoseconds to seconds. Note that the sensor delivery rates can // individually vary by a relatively large time frame, so we use an // averaging technique with the number of sensor updates to // determine the delivery rate. return (count++ / ((timestamp - startTime) / 1000000000.0f)); } private float[] invert(float[] values) { for (int i = 0; i < values.length; i++) { values[i] = -values[i]; } return values; } private void initializeFSensorFusions() { lpfGravity = new LowPassFilter();
linearAccelerationFilterLpf = new LinearAccelerationAveraging(lpfGravity);
KalebKE/FSensor
fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/acceleration/LinearAccelerationSensor.java
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/observer/SensorSubject.java // public class SensorSubject { // private final List<SensorObserver> observers = new ArrayList<>(); // // public interface SensorObserver { // void onSensorChanged(float[] values); // } // // public void register(SensorObserver observer) { // if(!observers.contains(observer)) { // observers.add(observer); // } // } // // public void unregister(SensorObserver observer) { // observers.remove(observer); // } // // public void onNext(float[] values) { // for(int i = 0; i < observers.size(); i++) { // observers.get(i).onSensorChanged(values); // } // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/FSensor.java // public interface FSensor { // void register(SensorSubject.SensorObserver sensorObserver); // void unregister(SensorSubject.SensorObserver sensorObserver); // // void start(); // void stop(); // void reset(); // }
import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.kircherelectronics.fsensor.observer.SensorSubject; import com.kircherelectronics.fsensor.sensor.FSensor;
package com.kircherelectronics.fsensor.sensor.acceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ public class LinearAccelerationSensor implements FSensor { private static final String TAG = LinearAccelerationSensor.class.getSimpleName(); private final SensorManager sensorManager; private final SimpleSensorListener listener; private float startTime = 0; private int count = 0; private float[] acceleration = new float[3]; private float[] output = new float[4]; private int sensorDelay = SensorManager.SENSOR_DELAY_FASTEST;
// Path: fsensor/src/main/java/com/kircherelectronics/fsensor/observer/SensorSubject.java // public class SensorSubject { // private final List<SensorObserver> observers = new ArrayList<>(); // // public interface SensorObserver { // void onSensorChanged(float[] values); // } // // public void register(SensorObserver observer) { // if(!observers.contains(observer)) { // observers.add(observer); // } // } // // public void unregister(SensorObserver observer) { // observers.remove(observer); // } // // public void onNext(float[] values) { // for(int i = 0; i < observers.size(); i++) { // observers.get(i).onSensorChanged(values); // } // } // } // // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/FSensor.java // public interface FSensor { // void register(SensorSubject.SensorObserver sensorObserver); // void unregister(SensorSubject.SensorObserver sensorObserver); // // void start(); // void stop(); // void reset(); // } // Path: fsensor/src/main/java/com/kircherelectronics/fsensor/sensor/acceleration/LinearAccelerationSensor.java import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import com.kircherelectronics.fsensor.observer.SensorSubject; import com.kircherelectronics.fsensor.sensor.FSensor; package com.kircherelectronics.fsensor.sensor.acceleration; /* * Copyright 2018, Kircher Electronics, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ public class LinearAccelerationSensor implements FSensor { private static final String TAG = LinearAccelerationSensor.class.getSimpleName(); private final SensorManager sensorManager; private final SimpleSensorListener listener; private float startTime = 0; private int count = 0; private float[] acceleration = new float[3]; private float[] output = new float[4]; private int sensorDelay = SensorManager.SENSOR_DELAY_FASTEST;
private final SensorSubject sensorSubject;
iansrobinson/neode
src/test/java/org/neo4j/neode/CreateNodesBatchCommandTest.java
// Path: src/main/java/org/neo4j/neode/logging/SysOutLog.java // public final class SysOutLog implements Log // { // public static final Log INSTANCE = new SysOutLog(); // // private SysOutLog() // { // } // // @Override // public void write( String value ) // { // System.out.println( value ); // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // }
import org.junit.Test; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.logging.SysOutLog; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.neo4j.neode.properties.Property.indexableProperty;
package org.neo4j.neode; public class CreateNodesBatchCommandTest { @Test public void shouldCreateNodeWithNamePropertyValuePrefixedWithNodeLabel() throws Exception { // given
// Path: src/main/java/org/neo4j/neode/logging/SysOutLog.java // public final class SysOutLog implements Log // { // public static final Log INSTANCE = new SysOutLog(); // // private SysOutLog() // { // } // // @Override // public void write( String value ) // { // System.out.println( value ); // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // Path: src/test/java/org/neo4j/neode/CreateNodesBatchCommandTest.java import org.junit.Test; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.logging.SysOutLog; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.neo4j.neode.properties.Property.indexableProperty; package org.neo4j.neode; public class CreateNodesBatchCommandTest { @Test public void shouldCreateNodeWithNamePropertyValuePrefixedWithNodeLabel() throws Exception { // given
GraphDatabaseService db = Db.impermanentDb();
iansrobinson/neode
src/test/java/org/neo4j/neode/CreateNodesBatchCommandTest.java
// Path: src/main/java/org/neo4j/neode/logging/SysOutLog.java // public final class SysOutLog implements Log // { // public static final Log INSTANCE = new SysOutLog(); // // private SysOutLog() // { // } // // @Override // public void write( String value ) // { // System.out.println( value ); // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // }
import org.junit.Test; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.logging.SysOutLog; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.neo4j.neode.properties.Property.indexableProperty;
package org.neo4j.neode; public class CreateNodesBatchCommandTest { @Test public void shouldCreateNodeWithNamePropertyValuePrefixedWithNodeLabel() throws Exception { // given GraphDatabaseService db = Db.impermanentDb();
// Path: src/main/java/org/neo4j/neode/logging/SysOutLog.java // public final class SysOutLog implements Log // { // public static final Log INSTANCE = new SysOutLog(); // // private SysOutLog() // { // } // // @Override // public void write( String value ) // { // System.out.println( value ); // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // Path: src/test/java/org/neo4j/neode/CreateNodesBatchCommandTest.java import org.junit.Test; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.logging.SysOutLog; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.neo4j.neode.properties.Property.indexableProperty; package org.neo4j.neode; public class CreateNodesBatchCommandTest { @Test public void shouldCreateNodeWithNamePropertyValuePrefixedWithNodeLabel() throws Exception { // given GraphDatabaseService db = Db.impermanentDb();
DatasetManager dsm = new DatasetManager( db, SysOutLog.INSTANCE );
iansrobinson/neode
src/test/java/org/neo4j/neode/CreateNodesBatchCommandTest.java
// Path: src/main/java/org/neo4j/neode/logging/SysOutLog.java // public final class SysOutLog implements Log // { // public static final Log INSTANCE = new SysOutLog(); // // private SysOutLog() // { // } // // @Override // public void write( String value ) // { // System.out.println( value ); // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // }
import org.junit.Test; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.logging.SysOutLog; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.neo4j.neode.properties.Property.indexableProperty;
package org.neo4j.neode; public class CreateNodesBatchCommandTest { @Test public void shouldCreateNodeWithNamePropertyValuePrefixedWithNodeLabel() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); DatasetManager dsm = new DatasetManager( db, SysOutLog.INSTANCE ); Dataset dataset = dsm.newDataset( "Test" );
// Path: src/main/java/org/neo4j/neode/logging/SysOutLog.java // public final class SysOutLog implements Log // { // public static final Log INSTANCE = new SysOutLog(); // // private SysOutLog() // { // } // // @Override // public void write( String value ) // { // System.out.println( value ); // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // Path: src/test/java/org/neo4j/neode/CreateNodesBatchCommandTest.java import org.junit.Test; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.logging.SysOutLog; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.neo4j.neode.properties.Property.indexableProperty; package org.neo4j.neode; public class CreateNodesBatchCommandTest { @Test public void shouldCreateNodeWithNamePropertyValuePrefixedWithNodeLabel() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); DatasetManager dsm = new DatasetManager( db, SysOutLog.INSTANCE ); Dataset dataset = dsm.newDataset( "Test" );
NodeSpecification user = new NodeSpecification( "user", asList( indexableProperty( db, "user", "name" ) ), db );
iansrobinson/neode
src/test/java/org/neo4j/neode/probabilities/FlatProbabilityDistributionUniqueTest.java
// Path: src/main/java/org/neo4j/neode/Range.java // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // }
import java.util.List; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.neo4j.neode.Range.exactly; import static org.neo4j.neode.Range.minMax; import static org.neo4j.neode.probabilities.FlatProbabilityDistributionUnique.flatDistribution;
package org.neo4j.neode.probabilities; public class FlatProbabilityDistributionUniqueTest { @Test public void shouldReturnListOfNumbers() throws Exception { // given ProbabilityDistribution generator = flatDistribution(); // when
// Path: src/main/java/org/neo4j/neode/Range.java // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // Path: src/test/java/org/neo4j/neode/probabilities/FlatProbabilityDistributionUniqueTest.java import java.util.List; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.neo4j.neode.Range.exactly; import static org.neo4j.neode.Range.minMax; import static org.neo4j.neode.probabilities.FlatProbabilityDistributionUnique.flatDistribution; package org.neo4j.neode.probabilities; public class FlatProbabilityDistributionUniqueTest { @Test public void shouldReturnListOfNumbers() throws Exception { // given ProbabilityDistribution generator = flatDistribution(); // when
List<Integer> results = generator.generateList( 5, minMax( 1, 5 ) );
iansrobinson/neode
src/test/java/org/neo4j/neode/probabilities/FlatProbabilityDistributionUniqueTest.java
// Path: src/main/java/org/neo4j/neode/Range.java // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // }
import java.util.List; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.neo4j.neode.Range.exactly; import static org.neo4j.neode.Range.minMax; import static org.neo4j.neode.probabilities.FlatProbabilityDistributionUnique.flatDistribution;
package org.neo4j.neode.probabilities; public class FlatProbabilityDistributionUniqueTest { @Test public void shouldReturnListOfNumbers() throws Exception { // given ProbabilityDistribution generator = flatDistribution(); // when List<Integer> results = generator.generateList( 5, minMax( 1, 5 ) ); // then assertTrue( results.contains( 1 ) ); assertTrue( results.contains( 2 ) ); assertTrue( results.contains( 3 ) ); assertTrue( results.contains( 4 ) ); assertTrue( results.contains( 5 ) ); } @Test public void shouldReturnSingleNumber() throws Exception { // given ProbabilityDistribution generator = flatDistribution(); // when
// Path: src/main/java/org/neo4j/neode/Range.java // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // Path: src/test/java/org/neo4j/neode/probabilities/FlatProbabilityDistributionUniqueTest.java import java.util.List; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.neo4j.neode.Range.exactly; import static org.neo4j.neode.Range.minMax; import static org.neo4j.neode.probabilities.FlatProbabilityDistributionUnique.flatDistribution; package org.neo4j.neode.probabilities; public class FlatProbabilityDistributionUniqueTest { @Test public void shouldReturnListOfNumbers() throws Exception { // given ProbabilityDistribution generator = flatDistribution(); // when List<Integer> results = generator.generateList( 5, minMax( 1, 5 ) ); // then assertTrue( results.contains( 1 ) ); assertTrue( results.contains( 2 ) ); assertTrue( results.contains( 3 ) ); assertTrue( results.contains( 4 ) ); assertTrue( results.contains( 5 ) ); } @Test public void shouldReturnSingleNumber() throws Exception { // given ProbabilityDistribution generator = flatDistribution(); // when
int result = generator.generateSingle( exactly( 1 ) );
iansrobinson/neode
src/main/java/org/neo4j/neode/CreateNodesBatchCommand.java
// Path: src/main/java/org/neo4j/neode/logging/Log.java // public interface Log // { // void write( String value ); // }
import org.neo4j.neode.logging.Log;
public int numberOfIterations() { return numberOfIterations; } @Override public int batchSize() { return batchSize; } @Override public void execute( int iteration ) { nodeCollection.add( nodeSpecification.build( iteration ) ); } @Override public String description() { return "Creating '" + shortDescription() + "' nodes."; } @Override public String shortDescription() { return nodeSpecification.labelName(); } @Override
// Path: src/main/java/org/neo4j/neode/logging/Log.java // public interface Log // { // void write( String value ); // } // Path: src/main/java/org/neo4j/neode/CreateNodesBatchCommand.java import org.neo4j.neode.logging.Log; public int numberOfIterations() { return numberOfIterations; } @Override public int batchSize() { return batchSize; } @Override public void execute( int iteration ) { nodeCollection.add( nodeSpecification.build( iteration ) ); } @Override public String description() { return "Creating '" + shortDescription() + "' nodes."; } @Override public String shortDescription() { return nodeSpecification.labelName(); } @Override
public void onBegin( Log log )
iansrobinson/neode
src/main/java/org/neo4j/neode/probabilities/NormalProbabilityDistributionUnique.java
// Path: src/main/java/org/neo4j/neode/Range.java // public class Range // { // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // private final int min; // private final int max; // // private Range( int min, int max ) // { // if ( min < 0 ) // { // throw new IllegalArgumentException( "Min must be greater or equal to 0" ); // } // // if ( max < min ) // { // throw new IllegalArgumentException( "Max must be greater or equal to min" ); // } // // this.min = min; // this.max = max; // } // // public int min() // { // return min; // } // // public int max() // { // return max; // } // // public int difference() // { // return max - min; // } // // public boolean isInRange( int value ) // { // return value >= min() && value <= max; // } // // public int getRandom( ProbabilityDistribution probabilityDistribution ) // { // if ( difference() == 0 ) // { // return min(); // } // return probabilityDistribution.generateSingle( this ); // } // // @Override // public String toString() // { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // // @Override // public boolean equals( Object o ) // { // if ( this == o ) // { // return true; // } // if ( o == null || getClass() != o.getClass() ) // { // return false; // } // // Range range = (Range) o; // // return max == range.max && min == range.min; // } // // @Override // public int hashCode() // { // int result = min; // result = 31 * result + max; // return result; // } // }
import org.neo4j.neode.Range;
package org.neo4j.neode.probabilities; class NormalProbabilityDistributionUnique extends BaseUniqueProbabilityDistribution {
// Path: src/main/java/org/neo4j/neode/Range.java // public class Range // { // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // private final int min; // private final int max; // // private Range( int min, int max ) // { // if ( min < 0 ) // { // throw new IllegalArgumentException( "Min must be greater or equal to 0" ); // } // // if ( max < min ) // { // throw new IllegalArgumentException( "Max must be greater or equal to min" ); // } // // this.min = min; // this.max = max; // } // // public int min() // { // return min; // } // // public int max() // { // return max; // } // // public int difference() // { // return max - min; // } // // public boolean isInRange( int value ) // { // return value >= min() && value <= max; // } // // public int getRandom( ProbabilityDistribution probabilityDistribution ) // { // if ( difference() == 0 ) // { // return min(); // } // return probabilityDistribution.generateSingle( this ); // } // // @Override // public String toString() // { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // // @Override // public boolean equals( Object o ) // { // if ( this == o ) // { // return true; // } // if ( o == null || getClass() != o.getClass() ) // { // return false; // } // // Range range = (Range) o; // // return max == range.max && min == range.min; // } // // @Override // public int hashCode() // { // int result = min; // result = 31 * result + max; // return result; // } // } // Path: src/main/java/org/neo4j/neode/probabilities/NormalProbabilityDistributionUnique.java import org.neo4j.neode.Range; package org.neo4j.neode.probabilities; class NormalProbabilityDistributionUnique extends BaseUniqueProbabilityDistribution {
protected int getNextNumber( Range minMax )
iansrobinson/neode
src/test/java/org/neo4j/neode/properties/IndexablePropertyTest.java
// Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // }
import org.junit.Test; import org.neo4j.graphdb.*; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.test.Db; import static org.junit.Assert.assertEquals;
package org.neo4j.neode.properties; public class IndexablePropertyTest { @Test public void shouldIndexProperty() throws Exception { // given PropertyValueGenerator generator = new PropertyValueGenerator() { @Override public Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ) { return "value"; } };
// Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // Path: src/test/java/org/neo4j/neode/properties/IndexablePropertyTest.java import org.junit.Test; import org.neo4j.graphdb.*; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.test.Db; import static org.junit.Assert.assertEquals; package org.neo4j.neode.properties; public class IndexablePropertyTest { @Test public void shouldIndexProperty() throws Exception { // given PropertyValueGenerator generator = new PropertyValueGenerator() { @Override public Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ) { return "value"; } };
GraphDatabaseService db = Db.impermanentDb();
iansrobinson/neode
src/main/java/org/neo4j/neode/RelationshipSpecification.java
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // }
import java.util.List; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Expander; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.neode.properties.Property; import static org.neo4j.kernel.Traversal.expanderForTypes;
package org.neo4j.neode; public class RelationshipSpecification { private final RelationshipType relationshipType;
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // Path: src/main/java/org/neo4j/neode/RelationshipSpecification.java import java.util.List; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Expander; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.neode.properties.Property; import static org.neo4j.kernel.Traversal.expanderForTypes; package org.neo4j.neode; public class RelationshipSpecification { private final RelationshipType relationshipType;
private final List<Property> properties;
iansrobinson/neode
src/main/java/org/neo4j/neode/GetOrCreateUniqueNodes.java
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.neo4j.graphdb.Node; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static org.neo4j.neode.Range.minMax;
package org.neo4j.neode; class GetOrCreateUniqueNodes implements TargetNodesSource { private final NodeSpecification nodeSpecification; private final int totalNumberOfNodes;
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // Path: src/main/java/org/neo4j/neode/GetOrCreateUniqueNodes.java import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.neo4j.graphdb.Node; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static org.neo4j.neode.Range.minMax; package org.neo4j.neode; class GetOrCreateUniqueNodes implements TargetNodesSource { private final NodeSpecification nodeSpecification; private final int totalNumberOfNodes;
private final ProbabilityDistribution probabilityDistribution;
iansrobinson/neode
src/main/java/org/neo4j/neode/GetOrCreateUniqueNodes.java
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.neo4j.graphdb.Node; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static org.neo4j.neode.Range.minMax;
package org.neo4j.neode; class GetOrCreateUniqueNodes implements TargetNodesSource { private final NodeSpecification nodeSpecification; private final int totalNumberOfNodes; private final ProbabilityDistribution probabilityDistribution; private final ArrayList<Long> nodeIds; GetOrCreateUniqueNodes( NodeSpecification nodeSpecification, int totalNumberOfNodes, ProbabilityDistribution probabilityDistribution ) { this.nodeSpecification = nodeSpecification; this.totalNumberOfNodes = totalNumberOfNodes; this.probabilityDistribution = probabilityDistribution; nodeIds = new ArrayList<Long>( totalNumberOfNodes ); for ( int i = 0; i < totalNumberOfNodes; i++ ) { nodeIds.add( null ); } } @Override public Iterable<Node> getTargetNodes( int quantity, Node currentNode ) { final List<Integer> nodeIdPositions; try {
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // Path: src/main/java/org/neo4j/neode/GetOrCreateUniqueNodes.java import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.neo4j.graphdb.Node; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static org.neo4j.neode.Range.minMax; package org.neo4j.neode; class GetOrCreateUniqueNodes implements TargetNodesSource { private final NodeSpecification nodeSpecification; private final int totalNumberOfNodes; private final ProbabilityDistribution probabilityDistribution; private final ArrayList<Long> nodeIds; GetOrCreateUniqueNodes( NodeSpecification nodeSpecification, int totalNumberOfNodes, ProbabilityDistribution probabilityDistribution ) { this.nodeSpecification = nodeSpecification; this.totalNumberOfNodes = totalNumberOfNodes; this.probabilityDistribution = probabilityDistribution; nodeIds = new ArrayList<Long>( totalNumberOfNodes ); for ( int i = 0; i < totalNumberOfNodes; i++ ) { nodeIds.add( null ); } } @Override public Iterable<Node> getTargetNodes( int quantity, Node currentNode ) { final List<Integer> nodeIdPositions; try {
nodeIdPositions = probabilityDistribution.generateList( quantity, minMax( 0, totalNumberOfNodes - 1 ) );
iansrobinson/neode
src/main/java/org/neo4j/neode/BatchCommand.java
// Path: src/main/java/org/neo4j/neode/logging/Log.java // public interface Log // { // void write( String value ); // }
import org.neo4j.neode.logging.Log;
/* * Copyright (C) 2012 Neo Technology * All rights reserved */ package org.neo4j.neode; interface BatchCommand<T> { int numberOfIterations(); int batchSize(); void execute( int iteration ); String description(); String shortDescription();
// Path: src/main/java/org/neo4j/neode/logging/Log.java // public interface Log // { // void write( String value ); // } // Path: src/main/java/org/neo4j/neode/BatchCommand.java import org.neo4j.neode.logging.Log; /* * Copyright (C) 2012 Neo Technology * All rights reserved */ package org.neo4j.neode; interface BatchCommand<T> { int numberOfIterations(); int batchSize(); void execute( int iteration ); String description(); String shortDescription();
void onBegin( Log log );
iansrobinson/neode
src/main/java/org/neo4j/neode/SparseNodeListGenerator.java
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // }
import java.util.ArrayList; import java.util.List; import org.neo4j.graphdb.Node; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static java.lang.Math.round; import static org.neo4j.neode.Range.minMax;
package org.neo4j.neode; class SparseNodeListGenerator { private final GraphQuery query;
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // Path: src/main/java/org/neo4j/neode/SparseNodeListGenerator.java import java.util.ArrayList; import java.util.List; import org.neo4j.graphdb.Node; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static java.lang.Math.round; import static org.neo4j.neode.Range.minMax; package org.neo4j.neode; class SparseNodeListGenerator { private final GraphQuery query;
private final ProbabilityDistribution probabilityDistribution;
iansrobinson/neode
src/main/java/org/neo4j/neode/SparseNodeListGenerator.java
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // }
import java.util.ArrayList; import java.util.List; import org.neo4j.graphdb.Node; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static java.lang.Math.round; import static org.neo4j.neode.Range.minMax;
package org.neo4j.neode; class SparseNodeListGenerator { private final GraphQuery query; private final ProbabilityDistribution probabilityDistribution; private final double proportionOfNodesToListSize; SparseNodeListGenerator( GraphQuery query, double proportionOfNodesToListSize, ProbabilityDistribution probabilityDistribution ) { if ( proportionOfNodesToListSize < 1.0 ) { throw new IllegalArgumentException( "proportionOfNodesToListSize must be greater than or equal to 1.0" ); } this.query = query; this.probabilityDistribution = probabilityDistribution; this.proportionOfNodesToListSize = proportionOfNodesToListSize; } public List<Node> getSparseListOfExistingNodes( int size, Node currentNode ) { List<Node> existingNodes = new ArrayList<Node>( IteratorUtil.asCollection( query.execute( currentNode ) ) ); List<Node> sparseList = new ArrayList<Node>( size ); int candidatePoolSize = (int) round( size * proportionOfNodesToListSize ); List<Integer> candidateIndexes = probabilityDistribution.generateList( candidatePoolSize,
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // Path: src/main/java/org/neo4j/neode/SparseNodeListGenerator.java import java.util.ArrayList; import java.util.List; import org.neo4j.graphdb.Node; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static java.lang.Math.round; import static org.neo4j.neode.Range.minMax; package org.neo4j.neode; class SparseNodeListGenerator { private final GraphQuery query; private final ProbabilityDistribution probabilityDistribution; private final double proportionOfNodesToListSize; SparseNodeListGenerator( GraphQuery query, double proportionOfNodesToListSize, ProbabilityDistribution probabilityDistribution ) { if ( proportionOfNodesToListSize < 1.0 ) { throw new IllegalArgumentException( "proportionOfNodesToListSize must be greater than or equal to 1.0" ); } this.query = query; this.probabilityDistribution = probabilityDistribution; this.proportionOfNodesToListSize = proportionOfNodesToListSize; } public List<Node> getSparseListOfExistingNodes( int size, Node currentNode ) { List<Node> existingNodes = new ArrayList<Node>( IteratorUtil.asCollection( query.execute( currentNode ) ) ); List<Node> sparseList = new ArrayList<Node>( size ); int candidatePoolSize = (int) round( size * proportionOfNodesToListSize ); List<Integer> candidateIndexes = probabilityDistribution.generateList( candidatePoolSize,
minMax( 0, candidatePoolSize - 1 ) );
iansrobinson/neode
src/main/java/org/neo4j/neode/NodeSpecification.java
// Path: src/main/java/org/neo4j/neode/interfaces/UpdateDataset.java // public interface UpdateDataset<T> // { // T update( Dataset dataset, int batchSize ); // // T update( Dataset dataset ); // // void updateNoReturn( Dataset dataset, int batchSize ); // // void updateNoReturn( Dataset dataset ); // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // }
import java.util.HashSet; import java.util.List; import java.util.Set; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Label; import org.neo4j.graphdb.Node; import org.neo4j.neode.interfaces.UpdateDataset; import org.neo4j.neode.properties.Property; import org.neo4j.tooling.GlobalGraphOperations;
package org.neo4j.neode; public class NodeSpecification { private final Label label;
// Path: src/main/java/org/neo4j/neode/interfaces/UpdateDataset.java // public interface UpdateDataset<T> // { // T update( Dataset dataset, int batchSize ); // // T update( Dataset dataset ); // // void updateNoReturn( Dataset dataset, int batchSize ); // // void updateNoReturn( Dataset dataset ); // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // Path: src/main/java/org/neo4j/neode/NodeSpecification.java import java.util.HashSet; import java.util.List; import java.util.Set; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Label; import org.neo4j.graphdb.Node; import org.neo4j.neode.interfaces.UpdateDataset; import org.neo4j.neode.properties.Property; import org.neo4j.tooling.GlobalGraphOperations; package org.neo4j.neode; public class NodeSpecification { private final Label label;
private final List<Property> properties;
iansrobinson/neode
src/main/java/org/neo4j/neode/NodeSpecification.java
// Path: src/main/java/org/neo4j/neode/interfaces/UpdateDataset.java // public interface UpdateDataset<T> // { // T update( Dataset dataset, int batchSize ); // // T update( Dataset dataset ); // // void updateNoReturn( Dataset dataset, int batchSize ); // // void updateNoReturn( Dataset dataset ); // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // }
import java.util.HashSet; import java.util.List; import java.util.Set; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Label; import org.neo4j.graphdb.Node; import org.neo4j.neode.interfaces.UpdateDataset; import org.neo4j.neode.properties.Property; import org.neo4j.tooling.GlobalGraphOperations;
package org.neo4j.neode; public class NodeSpecification { private final Label label; private final List<Property> properties; private final GraphDatabaseService db; NodeSpecification( String label, List<Property> properties, GraphDatabaseService db ) { this( DynamicLabel.label(label), properties, db ); } NodeSpecification( Label label, List<Property> properties, GraphDatabaseService db ) { this.label = label; this.properties = properties; this.db = db; }
// Path: src/main/java/org/neo4j/neode/interfaces/UpdateDataset.java // public interface UpdateDataset<T> // { // T update( Dataset dataset, int batchSize ); // // T update( Dataset dataset ); // // void updateNoReturn( Dataset dataset, int batchSize ); // // void updateNoReturn( Dataset dataset ); // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // Path: src/main/java/org/neo4j/neode/NodeSpecification.java import java.util.HashSet; import java.util.List; import java.util.Set; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Label; import org.neo4j.graphdb.Node; import org.neo4j.neode.interfaces.UpdateDataset; import org.neo4j.neode.properties.Property; import org.neo4j.tooling.GlobalGraphOperations; package org.neo4j.neode; public class NodeSpecification { private final Label label; private final List<Property> properties; private final GraphDatabaseService db; NodeSpecification( String label, List<Property> properties, GraphDatabaseService db ) { this( DynamicLabel.label(label), properties, db ); } NodeSpecification( Label label, List<Property> properties, GraphDatabaseService db ) { this.label = label; this.properties = properties; this.db = db; }
public UpdateDataset<NodeCollection> create( int quantity )
iansrobinson/neode
src/test/java/org/neo4j/neode/RelationshipSpecificationTest.java
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public abstract class PropertyValueGenerator // { // public static PropertyValueGenerator counterBased() // { // return new CounterBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator idBased() // { // return new IdBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator integerRange( int min, int max, // ProbabilityDistribution probabilityDistribution ) // { // return new RangeBasedIntegerPropertyValueGenerator( Range.minMax( min, max ), probabilityDistribution ); // } // // public static PropertyValueGenerator integerRange( int min, int max ) // { // return integerRange( min, max, ProbabilityDistribution.flatDistribution() ); // } // // public abstract Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // }
import java.util.Collections; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.properties.Property; import org.neo4j.neode.properties.PropertyValueGenerator; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.neo4j.graphdb.DynamicRelationshipType.withName; import static org.neo4j.neode.properties.Property.property;
package org.neo4j.neode; public class RelationshipSpecificationTest { @Test public void shouldCreateRelationshipBetweenTwoNodes() throws Exception { // given
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public abstract class PropertyValueGenerator // { // public static PropertyValueGenerator counterBased() // { // return new CounterBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator idBased() // { // return new IdBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator integerRange( int min, int max, // ProbabilityDistribution probabilityDistribution ) // { // return new RangeBasedIntegerPropertyValueGenerator( Range.minMax( min, max ), probabilityDistribution ); // } // // public static PropertyValueGenerator integerRange( int min, int max ) // { // return integerRange( min, max, ProbabilityDistribution.flatDistribution() ); // } // // public abstract Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // Path: src/test/java/org/neo4j/neode/RelationshipSpecificationTest.java import java.util.Collections; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.properties.Property; import org.neo4j.neode.properties.PropertyValueGenerator; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.neo4j.graphdb.DynamicRelationshipType.withName; import static org.neo4j.neode.properties.Property.property; package org.neo4j.neode; public class RelationshipSpecificationTest { @Test public void shouldCreateRelationshipBetweenTwoNodes() throws Exception { // given
GraphDatabaseService db = Db.impermanentDb();
iansrobinson/neode
src/test/java/org/neo4j/neode/RelationshipSpecificationTest.java
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public abstract class PropertyValueGenerator // { // public static PropertyValueGenerator counterBased() // { // return new CounterBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator idBased() // { // return new IdBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator integerRange( int min, int max, // ProbabilityDistribution probabilityDistribution ) // { // return new RangeBasedIntegerPropertyValueGenerator( Range.minMax( min, max ), probabilityDistribution ); // } // // public static PropertyValueGenerator integerRange( int min, int max ) // { // return integerRange( min, max, ProbabilityDistribution.flatDistribution() ); // } // // public abstract Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // }
import java.util.Collections; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.properties.Property; import org.neo4j.neode.properties.PropertyValueGenerator; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.neo4j.graphdb.DynamicRelationshipType.withName; import static org.neo4j.neode.properties.Property.property;
package org.neo4j.neode; public class RelationshipSpecificationTest { @Test public void shouldCreateRelationshipBetweenTwoNodes() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); Node startNode, endNode; try ( Transaction tx = db.beginTx() ) { startNode = db.createNode(); endNode = db.createNode(); RelationshipSpecification specification = new RelationshipSpecification( withName( "FRIEND" ),
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public abstract class PropertyValueGenerator // { // public static PropertyValueGenerator counterBased() // { // return new CounterBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator idBased() // { // return new IdBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator integerRange( int min, int max, // ProbabilityDistribution probabilityDistribution ) // { // return new RangeBasedIntegerPropertyValueGenerator( Range.minMax( min, max ), probabilityDistribution ); // } // // public static PropertyValueGenerator integerRange( int min, int max ) // { // return integerRange( min, max, ProbabilityDistribution.flatDistribution() ); // } // // public abstract Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // Path: src/test/java/org/neo4j/neode/RelationshipSpecificationTest.java import java.util.Collections; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.properties.Property; import org.neo4j.neode.properties.PropertyValueGenerator; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.neo4j.graphdb.DynamicRelationshipType.withName; import static org.neo4j.neode.properties.Property.property; package org.neo4j.neode; public class RelationshipSpecificationTest { @Test public void shouldCreateRelationshipBetweenTwoNodes() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); Node startNode, endNode; try ( Transaction tx = db.beginTx() ) { startNode = db.createNode(); endNode = db.createNode(); RelationshipSpecification specification = new RelationshipSpecification( withName( "FRIEND" ),
Collections.<Property>emptyList(), db );
iansrobinson/neode
src/test/java/org/neo4j/neode/RelationshipSpecificationTest.java
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public abstract class PropertyValueGenerator // { // public static PropertyValueGenerator counterBased() // { // return new CounterBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator idBased() // { // return new IdBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator integerRange( int min, int max, // ProbabilityDistribution probabilityDistribution ) // { // return new RangeBasedIntegerPropertyValueGenerator( Range.minMax( min, max ), probabilityDistribution ); // } // // public static PropertyValueGenerator integerRange( int min, int max ) // { // return integerRange( min, max, ProbabilityDistribution.flatDistribution() ); // } // // public abstract Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // }
import java.util.Collections; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.properties.Property; import org.neo4j.neode.properties.PropertyValueGenerator; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.neo4j.graphdb.DynamicRelationshipType.withName; import static org.neo4j.neode.properties.Property.property;
endNode = db.createNode(); RelationshipSpecification specification = new RelationshipSpecification( withName( "FRIEND" ), Collections.<Property>emptyList(), db ); // when specification.createRelationship( startNode, endNode, 0 ); tx.success(); } // then try ( Transaction tx = db.beginTx() ) { assertEquals( endNode, startNode.getSingleRelationship( withName( "FRIEND" ), Direction.OUTGOING ).getEndNode() ); tx.success(); } } @Test public void shouldCreatePropertiesForRelationship() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); Node startNode; try ( Transaction tx = db.beginTx() ) { startNode = db.createNode(); Node endNode = db.createNode();
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public abstract class PropertyValueGenerator // { // public static PropertyValueGenerator counterBased() // { // return new CounterBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator idBased() // { // return new IdBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator integerRange( int min, int max, // ProbabilityDistribution probabilityDistribution ) // { // return new RangeBasedIntegerPropertyValueGenerator( Range.minMax( min, max ), probabilityDistribution ); // } // // public static PropertyValueGenerator integerRange( int min, int max ) // { // return integerRange( min, max, ProbabilityDistribution.flatDistribution() ); // } // // public abstract Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // Path: src/test/java/org/neo4j/neode/RelationshipSpecificationTest.java import java.util.Collections; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.properties.Property; import org.neo4j.neode.properties.PropertyValueGenerator; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.neo4j.graphdb.DynamicRelationshipType.withName; import static org.neo4j.neode.properties.Property.property; endNode = db.createNode(); RelationshipSpecification specification = new RelationshipSpecification( withName( "FRIEND" ), Collections.<Property>emptyList(), db ); // when specification.createRelationship( startNode, endNode, 0 ); tx.success(); } // then try ( Transaction tx = db.beginTx() ) { assertEquals( endNode, startNode.getSingleRelationship( withName( "FRIEND" ), Direction.OUTGOING ).getEndNode() ); tx.success(); } } @Test public void shouldCreatePropertiesForRelationship() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); Node startNode; try ( Transaction tx = db.beginTx() ) { startNode = db.createNode(); Node endNode = db.createNode();
PropertyValueGenerator propertyValueGenerator = new PropertyValueGenerator()
iansrobinson/neode
src/test/java/org/neo4j/neode/RelationshipSpecificationTest.java
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public abstract class PropertyValueGenerator // { // public static PropertyValueGenerator counterBased() // { // return new CounterBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator idBased() // { // return new IdBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator integerRange( int min, int max, // ProbabilityDistribution probabilityDistribution ) // { // return new RangeBasedIntegerPropertyValueGenerator( Range.minMax( min, max ), probabilityDistribution ); // } // // public static PropertyValueGenerator integerRange( int min, int max ) // { // return integerRange( min, max, ProbabilityDistribution.flatDistribution() ); // } // // public abstract Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // }
import java.util.Collections; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.properties.Property; import org.neo4j.neode.properties.PropertyValueGenerator; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.neo4j.graphdb.DynamicRelationshipType.withName; import static org.neo4j.neode.properties.Property.property;
// then try ( Transaction tx = db.beginTx() ) { assertEquals( endNode, startNode.getSingleRelationship( withName( "FRIEND" ), Direction.OUTGOING ).getEndNode() ); tx.success(); } } @Test public void shouldCreatePropertiesForRelationship() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); Node startNode; try ( Transaction tx = db.beginTx() ) { startNode = db.createNode(); Node endNode = db.createNode(); PropertyValueGenerator propertyValueGenerator = new PropertyValueGenerator() { @Override public Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ) { return "value"; } }; RelationshipSpecification specification = new RelationshipSpecification( withName( "FRIEND" ),
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public abstract class PropertyValueGenerator // { // public static PropertyValueGenerator counterBased() // { // return new CounterBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator idBased() // { // return new IdBasedStringPropertyValueGenerator(); // } // // public static PropertyValueGenerator integerRange( int min, int max, // ProbabilityDistribution probabilityDistribution ) // { // return new RangeBasedIntegerPropertyValueGenerator( Range.minMax( min, max ), probabilityDistribution ); // } // // public static PropertyValueGenerator integerRange( int min, int max ) // { // return integerRange( min, max, ProbabilityDistribution.flatDistribution() ); // } // // public abstract Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // Path: src/test/java/org/neo4j/neode/RelationshipSpecificationTest.java import java.util.Collections; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.properties.Property; import org.neo4j.neode.properties.PropertyValueGenerator; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.neo4j.graphdb.DynamicRelationshipType.withName; import static org.neo4j.neode.properties.Property.property; // then try ( Transaction tx = db.beginTx() ) { assertEquals( endNode, startNode.getSingleRelationship( withName( "FRIEND" ), Direction.OUTGOING ).getEndNode() ); tx.success(); } } @Test public void shouldCreatePropertiesForRelationship() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); Node startNode; try ( Transaction tx = db.beginTx() ) { startNode = db.createNode(); Node endNode = db.createNode(); PropertyValueGenerator propertyValueGenerator = new PropertyValueGenerator() { @Override public Object generateValue( PropertyContainer propertyContainer, String nodeLabel, int iteration ) { return "value"; } }; RelationshipSpecification specification = new RelationshipSpecification( withName( "FRIEND" ),
asList( property( "name", propertyValueGenerator ) ), db );
iansrobinson/neode
src/main/java/org/neo4j/neode/GetExistingUniqueNodes.java
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // }
import java.util.List; import org.neo4j.graphdb.Node; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static org.neo4j.neode.Range.minMax;
package org.neo4j.neode; class GetExistingUniqueNodes implements TargetNodesSource { private final NodeCollection nodeCollection;
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // Path: src/main/java/org/neo4j/neode/GetExistingUniqueNodes.java import java.util.List; import org.neo4j.graphdb.Node; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static org.neo4j.neode.Range.minMax; package org.neo4j.neode; class GetExistingUniqueNodes implements TargetNodesSource { private final NodeCollection nodeCollection;
private final ProbabilityDistribution probabilityDistribution;
iansrobinson/neode
src/main/java/org/neo4j/neode/GetExistingUniqueNodes.java
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // }
import java.util.List; import org.neo4j.graphdb.Node; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static org.neo4j.neode.Range.minMax;
package org.neo4j.neode; class GetExistingUniqueNodes implements TargetNodesSource { private final NodeCollection nodeCollection; private final ProbabilityDistribution probabilityDistribution; GetExistingUniqueNodes( NodeCollection nodeCollection, ProbabilityDistribution probabilityDistribution ) { this.nodeCollection = nodeCollection; this.probabilityDistribution = probabilityDistribution; } @Override public Iterable<Node> getTargetNodes( int quantity, Node currentNode ) { final List<Integer> nodeIdPositions; try { nodeIdPositions = probabilityDistribution.generateList( quantity,
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // Path: src/main/java/org/neo4j/neode/GetExistingUniqueNodes.java import java.util.List; import org.neo4j.graphdb.Node; import org.neo4j.neode.probabilities.ProbabilityDistribution; import static org.neo4j.neode.Range.minMax; package org.neo4j.neode; class GetExistingUniqueNodes implements TargetNodesSource { private final NodeCollection nodeCollection; private final ProbabilityDistribution probabilityDistribution; GetExistingUniqueNodes( NodeCollection nodeCollection, ProbabilityDistribution probabilityDistribution ) { this.nodeCollection = nodeCollection; this.probabilityDistribution = probabilityDistribution; } @Override public Iterable<Node> getTargetNodes( int quantity, Node currentNode ) { final List<Integer> nodeIdPositions; try { nodeIdPositions = probabilityDistribution.generateList( quantity,
minMax( 0, nodeCollection.size() - 1 )
iansrobinson/neode
src/main/java/org/neo4j/neode/properties/RangeBasedIntegerPropertyValueGenerator.java
// Path: src/main/java/org/neo4j/neode/Range.java // public class Range // { // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // private final int min; // private final int max; // // private Range( int min, int max ) // { // if ( min < 0 ) // { // throw new IllegalArgumentException( "Min must be greater or equal to 0" ); // } // // if ( max < min ) // { // throw new IllegalArgumentException( "Max must be greater or equal to min" ); // } // // this.min = min; // this.max = max; // } // // public int min() // { // return min; // } // // public int max() // { // return max; // } // // public int difference() // { // return max - min; // } // // public boolean isInRange( int value ) // { // return value >= min() && value <= max; // } // // public int getRandom( ProbabilityDistribution probabilityDistribution ) // { // if ( difference() == 0 ) // { // return min(); // } // return probabilityDistribution.generateSingle( this ); // } // // @Override // public String toString() // { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // // @Override // public boolean equals( Object o ) // { // if ( this == o ) // { // return true; // } // if ( o == null || getClass() != o.getClass() ) // { // return false; // } // // Range range = (Range) o; // // return max == range.max && min == range.min; // } // // @Override // public int hashCode() // { // int result = min; // result = 31 * result + max; // return result; // } // } // // Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // }
import org.neo4j.graphdb.PropertyContainer; import org.neo4j.neode.Range; import org.neo4j.neode.probabilities.ProbabilityDistribution;
package org.neo4j.neode.properties; class RangeBasedIntegerPropertyValueGenerator extends PropertyValueGenerator {
// Path: src/main/java/org/neo4j/neode/Range.java // public class Range // { // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // private final int min; // private final int max; // // private Range( int min, int max ) // { // if ( min < 0 ) // { // throw new IllegalArgumentException( "Min must be greater or equal to 0" ); // } // // if ( max < min ) // { // throw new IllegalArgumentException( "Max must be greater or equal to min" ); // } // // this.min = min; // this.max = max; // } // // public int min() // { // return min; // } // // public int max() // { // return max; // } // // public int difference() // { // return max - min; // } // // public boolean isInRange( int value ) // { // return value >= min() && value <= max; // } // // public int getRandom( ProbabilityDistribution probabilityDistribution ) // { // if ( difference() == 0 ) // { // return min(); // } // return probabilityDistribution.generateSingle( this ); // } // // @Override // public String toString() // { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // // @Override // public boolean equals( Object o ) // { // if ( this == o ) // { // return true; // } // if ( o == null || getClass() != o.getClass() ) // { // return false; // } // // Range range = (Range) o; // // return max == range.max && min == range.min; // } // // @Override // public int hashCode() // { // int result = min; // result = 31 * result + max; // return result; // } // } // // Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // Path: src/main/java/org/neo4j/neode/properties/RangeBasedIntegerPropertyValueGenerator.java import org.neo4j.graphdb.PropertyContainer; import org.neo4j.neode.Range; import org.neo4j.neode.probabilities.ProbabilityDistribution; package org.neo4j.neode.properties; class RangeBasedIntegerPropertyValueGenerator extends PropertyValueGenerator {
private final Range range;
iansrobinson/neode
src/main/java/org/neo4j/neode/properties/RangeBasedIntegerPropertyValueGenerator.java
// Path: src/main/java/org/neo4j/neode/Range.java // public class Range // { // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // private final int min; // private final int max; // // private Range( int min, int max ) // { // if ( min < 0 ) // { // throw new IllegalArgumentException( "Min must be greater or equal to 0" ); // } // // if ( max < min ) // { // throw new IllegalArgumentException( "Max must be greater or equal to min" ); // } // // this.min = min; // this.max = max; // } // // public int min() // { // return min; // } // // public int max() // { // return max; // } // // public int difference() // { // return max - min; // } // // public boolean isInRange( int value ) // { // return value >= min() && value <= max; // } // // public int getRandom( ProbabilityDistribution probabilityDistribution ) // { // if ( difference() == 0 ) // { // return min(); // } // return probabilityDistribution.generateSingle( this ); // } // // @Override // public String toString() // { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // // @Override // public boolean equals( Object o ) // { // if ( this == o ) // { // return true; // } // if ( o == null || getClass() != o.getClass() ) // { // return false; // } // // Range range = (Range) o; // // return max == range.max && min == range.min; // } // // @Override // public int hashCode() // { // int result = min; // result = 31 * result + max; // return result; // } // } // // Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // }
import org.neo4j.graphdb.PropertyContainer; import org.neo4j.neode.Range; import org.neo4j.neode.probabilities.ProbabilityDistribution;
package org.neo4j.neode.properties; class RangeBasedIntegerPropertyValueGenerator extends PropertyValueGenerator { private final Range range;
// Path: src/main/java/org/neo4j/neode/Range.java // public class Range // { // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // private final int min; // private final int max; // // private Range( int min, int max ) // { // if ( min < 0 ) // { // throw new IllegalArgumentException( "Min must be greater or equal to 0" ); // } // // if ( max < min ) // { // throw new IllegalArgumentException( "Max must be greater or equal to min" ); // } // // this.min = min; // this.max = max; // } // // public int min() // { // return min; // } // // public int max() // { // return max; // } // // public int difference() // { // return max - min; // } // // public boolean isInRange( int value ) // { // return value >= min() && value <= max; // } // // public int getRandom( ProbabilityDistribution probabilityDistribution ) // { // if ( difference() == 0 ) // { // return min(); // } // return probabilityDistribution.generateSingle( this ); // } // // @Override // public String toString() // { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // // @Override // public boolean equals( Object o ) // { // if ( this == o ) // { // return true; // } // if ( o == null || getClass() != o.getClass() ) // { // return false; // } // // Range range = (Range) o; // // return max == range.max && min == range.min; // } // // @Override // public int hashCode() // { // int result = min; // result = 31 * result + max; // return result; // } // } // // Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // Path: src/main/java/org/neo4j/neode/properties/RangeBasedIntegerPropertyValueGenerator.java import org.neo4j.graphdb.PropertyContainer; import org.neo4j.neode.Range; import org.neo4j.neode.probabilities.ProbabilityDistribution; package org.neo4j.neode.properties; class RangeBasedIntegerPropertyValueGenerator extends PropertyValueGenerator { private final Range range;
private final ProbabilityDistribution probabilityDistribution;
iansrobinson/neode
src/test/java/org/neo4j/neode/QueryBasedGetOrCreateNodesTest.java
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // }
import java.util.Collections; import java.util.Iterator; import java.util.List; import org.junit.Test; import org.neo4j.graphdb.*; import org.neo4j.neode.properties.Property; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.neo4j.neode; public class QueryBasedGetOrCreateNodesTest { @Test public void shouldReturnAMixtureOfExistingAndNewNodes() throws Exception { // given
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // Path: src/test/java/org/neo4j/neode/QueryBasedGetOrCreateNodesTest.java import java.util.Collections; import java.util.Iterator; import java.util.List; import org.junit.Test; import org.neo4j.graphdb.*; import org.neo4j.neode.properties.Property; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package org.neo4j.neode; public class QueryBasedGetOrCreateNodesTest { @Test public void shouldReturnAMixtureOfExistingAndNewNodes() throws Exception { // given
GraphDatabaseService db = Db.impermanentDb();
iansrobinson/neode
src/test/java/org/neo4j/neode/QueryBasedGetOrCreateNodesTest.java
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // }
import java.util.Collections; import java.util.Iterator; import java.util.List; import org.junit.Test; import org.neo4j.graphdb.*; import org.neo4j.neode.properties.Property; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.neo4j.neode; public class QueryBasedGetOrCreateNodesTest { @Test public void shouldReturnAMixtureOfExistingAndNewNodes() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); Label label = DynamicLabel.label("user"); Node node0, node4; Iterable<Node> results; try ( Transaction tx = db.beginTx() ) { Node currentNode = db.createNode(); node0 = db.createNode(); node4 = db.createNode();
// Path: src/main/java/org/neo4j/neode/properties/Property.java // public abstract class Property // { // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // public static Property property( String name, PropertyValueGenerator generator ) // { // return new NonIndexableProperty( name, generator ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, String... labelNames ) // { // return indexableProperty( db,label, name, new CounterBasedStringPropertyValueGenerator(), labelNames ); // } // // public static Property indexableProperty( GraphDatabaseService db, String label, String name, PropertyValueGenerator generator, String... labelNames ) // { // return new IndexableProperty( db,label,name, generator, labelNames ); // } // // public abstract void setProperty(PropertyContainer propertyContainer, String label, // int iteration); // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // Path: src/test/java/org/neo4j/neode/QueryBasedGetOrCreateNodesTest.java import java.util.Collections; import java.util.Iterator; import java.util.List; import org.junit.Test; import org.neo4j.graphdb.*; import org.neo4j.neode.properties.Property; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package org.neo4j.neode; public class QueryBasedGetOrCreateNodesTest { @Test public void shouldReturnAMixtureOfExistingAndNewNodes() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); Label label = DynamicLabel.label("user"); Node node0, node4; Iterable<Node> results; try ( Transaction tx = db.beginTx() ) { Node currentNode = db.createNode(); node0 = db.createNode(); node4 = db.createNode();
NodeSpecification user = new NodeSpecification( label, Collections.<Property>emptyList(), db );
iansrobinson/neode
src/main/java/org/neo4j/neode/NodeCollection.java
// Path: src/main/java/org/neo4j/neode/interfaces/UpdateDataset.java // public interface UpdateDataset<T> // { // T update( Dataset dataset, int batchSize ); // // T update( Dataset dataset ); // // void updateNoReturn( Dataset dataset, int batchSize ); // // void updateNoReturn( Dataset dataset ); // }
import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import org.neo4j.graphdb.*; import org.neo4j.neode.interfaces.UpdateDataset;
public NodeCollection approxPercentage( int percentage ) { if ( percentage < 1 || percentage > 100 ) { throw new IllegalArgumentException( "Percent must be between 1 and 100" ); } Random random = new Random(); int arraySize = nodeIds.size() * ((percentage + 10) / 100); Set<Long> newNodeIds = new HashSet<Long>( arraySize ); for ( Long nodeId : nodeIds ) { int score = random.nextInt( 100 ) + 1; if ( score <= percentage ) { newNodeIds.add( nodeId ); } } return new NodeCollection( db, label, newNodeIds ); } public NodeCollection combine( NodeCollection other ) { Set<Long> newNodeIds = new HashSet<Long>( nodeIds.size() + other.nodeIds.size() ); newNodeIds.addAll( nodeIds ); newNodeIds.addAll( other.nodeIds ); return new NodeCollection( db, label, newNodeIds ); }
// Path: src/main/java/org/neo4j/neode/interfaces/UpdateDataset.java // public interface UpdateDataset<T> // { // T update( Dataset dataset, int batchSize ); // // T update( Dataset dataset ); // // void updateNoReturn( Dataset dataset, int batchSize ); // // void updateNoReturn( Dataset dataset ); // } // Path: src/main/java/org/neo4j/neode/NodeCollection.java import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import org.neo4j.graphdb.*; import org.neo4j.neode.interfaces.UpdateDataset; public NodeCollection approxPercentage( int percentage ) { if ( percentage < 1 || percentage > 100 ) { throw new IllegalArgumentException( "Percent must be between 1 and 100" ); } Random random = new Random(); int arraySize = nodeIds.size() * ((percentage + 10) / 100); Set<Long> newNodeIds = new HashSet<Long>( arraySize ); for ( Long nodeId : nodeIds ) { int score = random.nextInt( 100 ) + 1; if ( score <= percentage ) { newNodeIds.add( nodeId ); } } return new NodeCollection( db, label, newNodeIds ); } public NodeCollection combine( NodeCollection other ) { Set<Long> newNodeIds = new HashSet<Long>( nodeIds.size() + other.nodeIds.size() ); newNodeIds.addAll( nodeIds ); newNodeIds.addAll( other.nodeIds ); return new NodeCollection( db, label, newNodeIds ); }
public UpdateDataset<NodeCollection> createRelationshipsTo( TargetNodesStrategy targetNodesStrategy )
iansrobinson/neode
src/main/java/org/neo4j/neode/RelateToChoiceOfNodesBatchCommand.java
// Path: src/main/java/org/neo4j/neode/logging/Log.java // public interface Log // { // void write( String value ); // }
import java.util.List; import org.neo4j.neode.logging.Log;
{ return startNodes.size(); } @Override public int batchSize() { return batchSize; } @Override public void execute( int iteration ) { BatchCommand<NodeCollection> nextCommand = commands.nextCommand(); nextCommand.execute( iteration ); } @Override public String description() { return "Creating choice of relationships."; } @Override public String shortDescription() { return "Create choice of relationships"; } @Override
// Path: src/main/java/org/neo4j/neode/logging/Log.java // public interface Log // { // void write( String value ); // } // Path: src/main/java/org/neo4j/neode/RelateToChoiceOfNodesBatchCommand.java import java.util.List; import org.neo4j.neode.logging.Log; { return startNodes.size(); } @Override public int batchSize() { return batchSize; } @Override public void execute( int iteration ) { BatchCommand<NodeCollection> nextCommand = commands.nextCommand(); nextCommand.execute( iteration ); } @Override public String description() { return "Creating choice of relationships."; } @Override public String shortDescription() { return "Create choice of relationships"; } @Override
public void onBegin( Log log )
iansrobinson/neode
src/test/java/org/neo4j/neode/GraphQueryTest.java
// Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // }
import java.util.Iterator; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.ReturnableEvaluator; import org.neo4j.graphdb.StopEvaluator; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.Traverser; import org.neo4j.neode.test.Db; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.neo4j.graphdb.DynamicRelationshipType.withName;
package org.neo4j.neode; public class GraphQueryTest { @Test public void shouldBeAbleToImplementAnonymousGraphQuery() throws Exception { // given
// Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // Path: src/test/java/org/neo4j/neode/GraphQueryTest.java import java.util.Iterator; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.ReturnableEvaluator; import org.neo4j.graphdb.StopEvaluator; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.Traverser; import org.neo4j.neode.test.Db; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.neo4j.graphdb.DynamicRelationshipType.withName; package org.neo4j.neode; public class GraphQueryTest { @Test public void shouldBeAbleToImplementAnonymousGraphQuery() throws Exception { // given
GraphDatabaseService db = Db.impermanentDb();
iansrobinson/neode
src/test/java/org/neo4j/neode/GetOrCreateUniqueNodesTest.java
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // }
import java.util.Iterator; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.neo4j.neode.properties.Property.property; import static org.neo4j.neode.properties.PropertyValueGenerator.iterationBased;
package org.neo4j.neode; public class GetOrCreateUniqueNodesTest { @Test public void shouldReturnSpecifiedNumberOfNodes() throws Exception { // given
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // Path: src/test/java/org/neo4j/neode/GetOrCreateUniqueNodesTest.java import java.util.Iterator; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.neo4j.neode.properties.Property.property; import static org.neo4j.neode.properties.PropertyValueGenerator.iterationBased; package org.neo4j.neode; public class GetOrCreateUniqueNodesTest { @Test public void shouldReturnSpecifiedNumberOfNodes() throws Exception { // given
GraphDatabaseService db = Db.impermanentDb();
iansrobinson/neode
src/test/java/org/neo4j/neode/GetOrCreateUniqueNodesTest.java
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // }
import java.util.Iterator; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.neo4j.neode.properties.Property.property; import static org.neo4j.neode.properties.PropertyValueGenerator.iterationBased;
package org.neo4j.neode; public class GetOrCreateUniqueNodesTest { @Test public void shouldReturnSpecifiedNumberOfNodes() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); try (Transaction tx = db.beginTx()) { NodeSpecification nodeSpecification = new NodeSpecification( "user",
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // Path: src/test/java/org/neo4j/neode/GetOrCreateUniqueNodesTest.java import java.util.Iterator; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.neo4j.neode.properties.Property.property; import static org.neo4j.neode.properties.PropertyValueGenerator.iterationBased; package org.neo4j.neode; public class GetOrCreateUniqueNodesTest { @Test public void shouldReturnSpecifiedNumberOfNodes() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); try (Transaction tx = db.beginTx()) { NodeSpecification nodeSpecification = new NodeSpecification( "user",
asList( property( "name", iterationBased() ) ), db );
iansrobinson/neode
src/test/java/org/neo4j/neode/GetOrCreateUniqueNodesTest.java
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // }
import java.util.Iterator; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.neo4j.neode.properties.Property.property; import static org.neo4j.neode.properties.PropertyValueGenerator.iterationBased;
package org.neo4j.neode; public class GetOrCreateUniqueNodesTest { @Test public void shouldReturnSpecifiedNumberOfNodes() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); try (Transaction tx = db.beginTx()) { NodeSpecification nodeSpecification = new NodeSpecification( "user",
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // Path: src/test/java/org/neo4j/neode/GetOrCreateUniqueNodesTest.java import java.util.Iterator; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.neo4j.neode.properties.Property.property; import static org.neo4j.neode.properties.PropertyValueGenerator.iterationBased; package org.neo4j.neode; public class GetOrCreateUniqueNodesTest { @Test public void shouldReturnSpecifiedNumberOfNodes() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); try (Transaction tx = db.beginTx()) { NodeSpecification nodeSpecification = new NodeSpecification( "user",
asList( property( "name", iterationBased() ) ), db );
iansrobinson/neode
src/test/java/org/neo4j/neode/GetOrCreateUniqueNodesTest.java
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // }
import java.util.Iterator; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.neo4j.neode.properties.Property.property; import static org.neo4j.neode.properties.PropertyValueGenerator.iterationBased;
package org.neo4j.neode; public class GetOrCreateUniqueNodesTest { @Test public void shouldReturnSpecifiedNumberOfNodes() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); try (Transaction tx = db.beginTx()) { NodeSpecification nodeSpecification = new NodeSpecification( "user", asList( property( "name", iterationBased() ) ), db );
// Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // // Path: src/test/java/org/neo4j/neode/test/Db.java // public final class Db // { // private Db() // { // } // // public static GraphDatabaseService impermanentDb() // { // Map<String, String> params = new HashMap<String, String>(); // params.put( "online_backup_enabled", "false" ); // // return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig( params ).newGraphDatabase(); // } // // public static GraphDatabaseService tempDb() // { // return new GraphDatabaseFactory().newEmbeddedDatabase( createTempDatabaseDir().getAbsolutePath() ); // } // // private static File createTempDatabaseDir() // { // // File d; // try // { // d = File.createTempFile( "datasetbuilder-", "dir" ); // System.out.println( String.format( "Created a new Neo4j database at [%s]", d.getAbsolutePath() ) ); // } // catch ( IOException e ) // { // throw new RuntimeException( e ); // } // if ( !d.delete() ) // { // throw new RuntimeException( "temp config directory pre-delete failed" ); // } // if ( !d.mkdirs() ) // { // throw new RuntimeException( "temp config directory not created" ); // } // d.deleteOnExit(); // return d; // } // // public static void usingSampleDataset( WithSampleDataset f ) // { // GraphDatabaseService db = Db.impermanentDb(); // Node firstNode, secondNode, thirdNode; // try ( Transaction tx = db.beginTx() ) // { // firstNode = db.createNode(); // secondNode = db.createNode(); // thirdNode = db.createNode(); // tx.success(); // } // // try ( Transaction tx = db.beginTx() ) // { // f.execute( db, firstNode, secondNode, thirdNode ); // tx.success(); // } // db.shutdown(); // } // // public interface WithSampleDataset // { // public void execute( GraphDatabaseService db, Node firstNode, Node secondNode, Node thirdNode ); // } // // // } // // Path: src/main/java/org/neo4j/neode/properties/Property.java // public static Property property( String name ) // { // return new NonIndexableProperty( name, new CounterBasedStringPropertyValueGenerator() ); // } // // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java // public static PropertyValueGenerator iterationBased() // { // return new IterationBasedStringPropertyValueGenerator(); // } // Path: src/test/java/org/neo4j/neode/GetOrCreateUniqueNodesTest.java import java.util.Iterator; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.neode.test.Db; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.neo4j.neode.properties.Property.property; import static org.neo4j.neode.properties.PropertyValueGenerator.iterationBased; package org.neo4j.neode; public class GetOrCreateUniqueNodesTest { @Test public void shouldReturnSpecifiedNumberOfNodes() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); try (Transaction tx = db.beginTx()) { NodeSpecification nodeSpecification = new NodeSpecification( "user", asList( property( "name", iterationBased() ) ), db );
ProbabilityDistribution probabilityDistribution = mock( ProbabilityDistribution.class );
iansrobinson/neode
src/test/java/org/neo4j/neode/probabilities/NormalProbabilityDistributionUniqueTest.java
// Path: src/main/java/org/neo4j/neode/Range.java // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // }
import java.util.List; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.neo4j.neode.Range.exactly; import static org.neo4j.neode.Range.minMax; import static org.neo4j.neode.probabilities.NormalProbabilityDistributionUnique.normalDistribution;
package org.neo4j.neode.probabilities; public class NormalProbabilityDistributionUniqueTest { @Test public void shouldReturnListOfNumbers() throws Exception { // given ProbabilityDistribution generator = normalDistribution(); // when
// Path: src/main/java/org/neo4j/neode/Range.java // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // Path: src/test/java/org/neo4j/neode/probabilities/NormalProbabilityDistributionUniqueTest.java import java.util.List; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.neo4j.neode.Range.exactly; import static org.neo4j.neode.Range.minMax; import static org.neo4j.neode.probabilities.NormalProbabilityDistributionUnique.normalDistribution; package org.neo4j.neode.probabilities; public class NormalProbabilityDistributionUniqueTest { @Test public void shouldReturnListOfNumbers() throws Exception { // given ProbabilityDistribution generator = normalDistribution(); // when
List<Integer> results = generator.generateList( 5, minMax( 1, 5 ) );
iansrobinson/neode
src/test/java/org/neo4j/neode/probabilities/NormalProbabilityDistributionUniqueTest.java
// Path: src/main/java/org/neo4j/neode/Range.java // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // }
import java.util.List; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.neo4j.neode.Range.exactly; import static org.neo4j.neode.Range.minMax; import static org.neo4j.neode.probabilities.NormalProbabilityDistributionUnique.normalDistribution;
package org.neo4j.neode.probabilities; public class NormalProbabilityDistributionUniqueTest { @Test public void shouldReturnListOfNumbers() throws Exception { // given ProbabilityDistribution generator = normalDistribution(); // when List<Integer> results = generator.generateList( 5, minMax( 1, 5 ) ); // then assertTrue( results.contains( 1 ) ); assertTrue( results.contains( 2 ) ); assertTrue( results.contains( 3 ) ); assertTrue( results.contains( 4 ) ); assertTrue( results.contains( 5 ) ); } @Test public void shouldReturnSingleNumber() throws Exception { // given ProbabilityDistribution generator = normalDistribution(); // when
// Path: src/main/java/org/neo4j/neode/Range.java // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // Path: src/main/java/org/neo4j/neode/Range.java // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // Path: src/test/java/org/neo4j/neode/probabilities/NormalProbabilityDistributionUniqueTest.java import java.util.List; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.neo4j.neode.Range.exactly; import static org.neo4j.neode.Range.minMax; import static org.neo4j.neode.probabilities.NormalProbabilityDistributionUnique.normalDistribution; package org.neo4j.neode.probabilities; public class NormalProbabilityDistributionUniqueTest { @Test public void shouldReturnListOfNumbers() throws Exception { // given ProbabilityDistribution generator = normalDistribution(); // when List<Integer> results = generator.generateList( 5, minMax( 1, 5 ) ); // then assertTrue( results.contains( 1 ) ); assertTrue( results.contains( 2 ) ); assertTrue( results.contains( 3 ) ); assertTrue( results.contains( 4 ) ); assertTrue( results.contains( 5 ) ); } @Test public void shouldReturnSingleNumber() throws Exception { // given ProbabilityDistribution generator = normalDistribution(); // when
int result = generator.generateSingle( exactly( 1 ) );
iansrobinson/neode
src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java
// Path: src/main/java/org/neo4j/neode/Range.java // public class Range // { // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // private final int min; // private final int max; // // private Range( int min, int max ) // { // if ( min < 0 ) // { // throw new IllegalArgumentException( "Min must be greater or equal to 0" ); // } // // if ( max < min ) // { // throw new IllegalArgumentException( "Max must be greater or equal to min" ); // } // // this.min = min; // this.max = max; // } // // public int min() // { // return min; // } // // public int max() // { // return max; // } // // public int difference() // { // return max - min; // } // // public boolean isInRange( int value ) // { // return value >= min() && value <= max; // } // // public int getRandom( ProbabilityDistribution probabilityDistribution ) // { // if ( difference() == 0 ) // { // return min(); // } // return probabilityDistribution.generateSingle( this ); // } // // @Override // public String toString() // { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // // @Override // public boolean equals( Object o ) // { // if ( this == o ) // { // return true; // } // if ( o == null || getClass() != o.getClass() ) // { // return false; // } // // Range range = (Range) o; // // return max == range.max && min == range.min; // } // // @Override // public int hashCode() // { // int result = min; // result = 31 * result + max; // return result; // } // } // // Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // }
import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.neode.Range;
/* * Copyright (C) 2012 Neo Technology * All rights reserved */ package org.neo4j.neode.properties; public abstract class PropertyValueGenerator { public static PropertyValueGenerator counterBased() { return new CounterBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator iterationBased() { return new IterationBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator idBased() { return new IdBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator integerRange( int min, int max,
// Path: src/main/java/org/neo4j/neode/Range.java // public class Range // { // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // private final int min; // private final int max; // // private Range( int min, int max ) // { // if ( min < 0 ) // { // throw new IllegalArgumentException( "Min must be greater or equal to 0" ); // } // // if ( max < min ) // { // throw new IllegalArgumentException( "Max must be greater or equal to min" ); // } // // this.min = min; // this.max = max; // } // // public int min() // { // return min; // } // // public int max() // { // return max; // } // // public int difference() // { // return max - min; // } // // public boolean isInRange( int value ) // { // return value >= min() && value <= max; // } // // public int getRandom( ProbabilityDistribution probabilityDistribution ) // { // if ( difference() == 0 ) // { // return min(); // } // return probabilityDistribution.generateSingle( this ); // } // // @Override // public String toString() // { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // // @Override // public boolean equals( Object o ) // { // if ( this == o ) // { // return true; // } // if ( o == null || getClass() != o.getClass() ) // { // return false; // } // // Range range = (Range) o; // // return max == range.max && min == range.min; // } // // @Override // public int hashCode() // { // int result = min; // result = 31 * result + max; // return result; // } // } // // Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.neode.Range; /* * Copyright (C) 2012 Neo Technology * All rights reserved */ package org.neo4j.neode.properties; public abstract class PropertyValueGenerator { public static PropertyValueGenerator counterBased() { return new CounterBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator iterationBased() { return new IterationBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator idBased() { return new IdBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator integerRange( int min, int max,
ProbabilityDistribution probabilityDistribution )
iansrobinson/neode
src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java
// Path: src/main/java/org/neo4j/neode/Range.java // public class Range // { // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // private final int min; // private final int max; // // private Range( int min, int max ) // { // if ( min < 0 ) // { // throw new IllegalArgumentException( "Min must be greater or equal to 0" ); // } // // if ( max < min ) // { // throw new IllegalArgumentException( "Max must be greater or equal to min" ); // } // // this.min = min; // this.max = max; // } // // public int min() // { // return min; // } // // public int max() // { // return max; // } // // public int difference() // { // return max - min; // } // // public boolean isInRange( int value ) // { // return value >= min() && value <= max; // } // // public int getRandom( ProbabilityDistribution probabilityDistribution ) // { // if ( difference() == 0 ) // { // return min(); // } // return probabilityDistribution.generateSingle( this ); // } // // @Override // public String toString() // { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // // @Override // public boolean equals( Object o ) // { // if ( this == o ) // { // return true; // } // if ( o == null || getClass() != o.getClass() ) // { // return false; // } // // Range range = (Range) o; // // return max == range.max && min == range.min; // } // // @Override // public int hashCode() // { // int result = min; // result = 31 * result + max; // return result; // } // } // // Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // }
import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.neode.Range;
/* * Copyright (C) 2012 Neo Technology * All rights reserved */ package org.neo4j.neode.properties; public abstract class PropertyValueGenerator { public static PropertyValueGenerator counterBased() { return new CounterBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator iterationBased() { return new IterationBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator idBased() { return new IdBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator integerRange( int min, int max, ProbabilityDistribution probabilityDistribution ) {
// Path: src/main/java/org/neo4j/neode/Range.java // public class Range // { // public static Range minMax( int min, int max ) // { // return new Range( min, max ); // } // // public static Range exactly( int count ) // { // return new Range( count, count ); // } // // private final int min; // private final int max; // // private Range( int min, int max ) // { // if ( min < 0 ) // { // throw new IllegalArgumentException( "Min must be greater or equal to 0" ); // } // // if ( max < min ) // { // throw new IllegalArgumentException( "Max must be greater or equal to min" ); // } // // this.min = min; // this.max = max; // } // // public int min() // { // return min; // } // // public int max() // { // return max; // } // // public int difference() // { // return max - min; // } // // public boolean isInRange( int value ) // { // return value >= min() && value <= max; // } // // public int getRandom( ProbabilityDistribution probabilityDistribution ) // { // if ( difference() == 0 ) // { // return min(); // } // return probabilityDistribution.generateSingle( this ); // } // // @Override // public String toString() // { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // // @Override // public boolean equals( Object o ) // { // if ( this == o ) // { // return true; // } // if ( o == null || getClass() != o.getClass() ) // { // return false; // } // // Range range = (Range) o; // // return max == range.max && min == range.min; // } // // @Override // public int hashCode() // { // int result = min; // result = 31 * result + max; // return result; // } // } // // Path: src/main/java/org/neo4j/neode/probabilities/ProbabilityDistribution.java // public abstract class ProbabilityDistribution // { // private static final Random RANDOM_INSTANCE = new Random(); // // public static ProbabilityDistribution flatDistribution() // { // return new FlatProbabilityDistributionUnique(); // } // // public static ProbabilityDistribution normalDistribution() // { // return new NormalProbabilityDistributionUnique(); // } // // private final Random random; // // protected ProbabilityDistribution() // { // this.random = RANDOM_INSTANCE; // } // // public abstract List<Integer> generateList( Range sizeRange, Range range ); // // public abstract List<Integer> generateList( int size, Range range ); // // public abstract int generateSingle( Range range ); // // public abstract String description(); // // protected final Random random() // { // return random; // } // } // Path: src/main/java/org/neo4j/neode/properties/PropertyValueGenerator.java import org.neo4j.neode.probabilities.ProbabilityDistribution; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.neode.Range; /* * Copyright (C) 2012 Neo Technology * All rights reserved */ package org.neo4j.neode.properties; public abstract class PropertyValueGenerator { public static PropertyValueGenerator counterBased() { return new CounterBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator iterationBased() { return new IterationBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator idBased() { return new IdBasedStringPropertyValueGenerator(); } public static PropertyValueGenerator integerRange( int min, int max, ProbabilityDistribution probabilityDistribution ) {
return new RangeBasedIntegerPropertyValueGenerator( Range.minMax( min, max ), probabilityDistribution );