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
|
---|---|---|---|---|---|---|
yangshuai0711/dingding-app-server | dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/web/RedisUtil.java | // Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/bean/TypeRef.java
// public class TypeRef<T> extends TypeReference<T> {
//
// @Override
// public int compareTo(TypeReference<T> o) {
// return this.getType().equals(o.getType())?0:1;
// }
// }
//
// Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/spring/SpringContextHolder.java
// public class SpringContextHolder implements ApplicationContextAware{
// private static ApplicationContext context;
// @Override
// public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// context = applicationContext;
// }
//
// public static <T> T getBean(Class<T> claz){
// return context.getBean(claz);
// }
//
// public static <T> T getBean(String name){
// return (T)context.getBean(name);
// }
// }
| import com.mocoder.dingding.utils.bean.TypeRef;
import com.mocoder.dingding.utils.spring.SpringContextHolder;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import java.util.Map; | public Object doInRedis(RedisConnection connection) throws DataAccessException {
try {
byte[] byteKey = key.getBytes("utf-8");
connection.set(byteKey, value.getBytes("utf-8"));
if (seconds != null) {
connection.expire(byteKey, seconds);
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("不支持的编码类型utf-8", e);
}
return null;
}
}, true, true);
}
public static void del(final String key) {
redisTemplate.execute(new RedisCallback() {
@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {
try {
byte[] byteKey = key.getBytes("utf-8");
connection.del(byteKey);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("不支持的编码类型utf-8", e);
}
return null;
}
}, true, true);
}
| // Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/bean/TypeRef.java
// public class TypeRef<T> extends TypeReference<T> {
//
// @Override
// public int compareTo(TypeReference<T> o) {
// return this.getType().equals(o.getType())?0:1;
// }
// }
//
// Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/spring/SpringContextHolder.java
// public class SpringContextHolder implements ApplicationContextAware{
// private static ApplicationContext context;
// @Override
// public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// context = applicationContext;
// }
//
// public static <T> T getBean(Class<T> claz){
// return context.getBean(claz);
// }
//
// public static <T> T getBean(String name){
// return (T)context.getBean(name);
// }
// }
// Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/web/RedisUtil.java
import com.mocoder.dingding.utils.bean.TypeRef;
import com.mocoder.dingding.utils.spring.SpringContextHolder;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import java.util.Map;
public Object doInRedis(RedisConnection connection) throws DataAccessException {
try {
byte[] byteKey = key.getBytes("utf-8");
connection.set(byteKey, value.getBytes("utf-8"));
if (seconds != null) {
connection.expire(byteKey, seconds);
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("不支持的编码类型utf-8", e);
}
return null;
}
}, true, true);
}
public static void del(final String key) {
redisTemplate.execute(new RedisCallback() {
@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {
try {
byte[] byteKey = key.getBytes("utf-8");
connection.del(byteKey);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("不支持的编码类型utf-8", e);
}
return null;
}
}, true, true);
}
| public static <T> T getObj(final String key, final TypeRef<T> type, final Long seconds) { |
yangshuai0711/dingding-app-server | dingding-app-server-web/src/test/java/com/mocoder/dingding/test/service/RpcServiceTest.java | // Path: dingding-app-server-rpc/src/main/java/com/mocoder/dingding/rpc/SmsServiceWrap.java
// public interface SmsServiceWrap {
//
// /**
// * 发送登录验证码短信
// * @param validCode
// * @param mobileNum
// * @return
// */
// public boolean sentLoginValidCodeSms(String mobileNum,String validCode);
//
// /**
// * 发送登录验证码短信
// * @param validCode
// * @param mobileNum
// * @return
// */
// public boolean sentRegValidCodeSms(String mobileNum,String validCode);
// /**
// * 发送重要操作验证码短信
// * @param validCode
// * @param mobileNum
// * @return
// */
// public boolean sentRegValidCodeSms(String mobileNum,String validCode,String operate);
// }
| import com.mocoder.dingding.rpc.SmsServiceWrap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource; | package com.mocoder.dingding.test.service;
/**
* Created with IntelliJ IDEA.
* User: likun7
* Date: 14-11-19
* Time: 上午11:52
* To change this template use File | Settings | File Templates.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-config.xml"})
public class RpcServiceTest {
@Resource | // Path: dingding-app-server-rpc/src/main/java/com/mocoder/dingding/rpc/SmsServiceWrap.java
// public interface SmsServiceWrap {
//
// /**
// * 发送登录验证码短信
// * @param validCode
// * @param mobileNum
// * @return
// */
// public boolean sentLoginValidCodeSms(String mobileNum,String validCode);
//
// /**
// * 发送登录验证码短信
// * @param validCode
// * @param mobileNum
// * @return
// */
// public boolean sentRegValidCodeSms(String mobileNum,String validCode);
// /**
// * 发送重要操作验证码短信
// * @param validCode
// * @param mobileNum
// * @return
// */
// public boolean sentRegValidCodeSms(String mobileNum,String validCode,String operate);
// }
// Path: dingding-app-server-web/src/test/java/com/mocoder/dingding/test/service/RpcServiceTest.java
import com.mocoder.dingding.rpc.SmsServiceWrap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
package com.mocoder.dingding.test.service;
/**
* Created with IntelliJ IDEA.
* User: likun7
* Date: 14-11-19
* Time: 上午11:52
* To change this template use File | Settings | File Templates.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-config.xml"})
public class RpcServiceTest {
@Resource | private SmsServiceWrap smsServiceWrap; |
yangshuai0711/dingding-app-server | dingding-app-server-web/src/main/java/com/mocoder/dingding/web/util/CacheKeyGenerator.java | // Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/web/JsonUtil.java
// public class JsonUtil {
//
// /**
// * 将对象按照json字符串格式输出
// *
// * @param obj javabean对象实例
// * @return json字符串
// * @throws IOException
// */
// public static String toString(Object obj) throws IOException {
// if(obj==null){
// return null;
// }
// ObjectMapper mapper = new ObjectMapper();
// mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
// return mapper.writeValueAsString(obj);
// }
//
// /**
// * 解析json字符串格式到javabean对象
// *
// * @param json json字符串
// * @param type 类型包装类,new新实力请带上泛型
// * @param <T> 目标对象类型
// * @return 目标对象实例
// * @throws IOException
// */
// public static <T> T toObject(String json, TypeRef<T> type) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, type);
// }
//
// /**
// * 解析json字符串格式到javabean对象
// *
// * @param json json字符串
// * @param claz 目标类型,不支持泛型
// * @param <T> 目标对象类型
// * @return 目标对象实例
// * @throws IOException
// */
// public static <T> T toObject(String json, Class<T> claz) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, claz);
// }
// }
| import com.mocoder.dingding.utils.web.JsonUtil;
import org.springframework.cache.interceptor.DefaultKeyGenerator;
import org.springframework.cache.interceptor.KeyGenerator;
import java.io.IOException;
import java.lang.reflect.Method; | package com.mocoder.dingding.web.util;
/**
* Created by yangshuai on 16/1/30.
*/
public class CacheKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object target, Method method, Object... params) {
try {
StringBuilder sb = new StringBuilder(target.getClass().getName()).append('.') | // Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/web/JsonUtil.java
// public class JsonUtil {
//
// /**
// * 将对象按照json字符串格式输出
// *
// * @param obj javabean对象实例
// * @return json字符串
// * @throws IOException
// */
// public static String toString(Object obj) throws IOException {
// if(obj==null){
// return null;
// }
// ObjectMapper mapper = new ObjectMapper();
// mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
// return mapper.writeValueAsString(obj);
// }
//
// /**
// * 解析json字符串格式到javabean对象
// *
// * @param json json字符串
// * @param type 类型包装类,new新实力请带上泛型
// * @param <T> 目标对象类型
// * @return 目标对象实例
// * @throws IOException
// */
// public static <T> T toObject(String json, TypeRef<T> type) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, type);
// }
//
// /**
// * 解析json字符串格式到javabean对象
// *
// * @param json json字符串
// * @param claz 目标类型,不支持泛型
// * @param <T> 目标对象类型
// * @return 目标对象实例
// * @throws IOException
// */
// public static <T> T toObject(String json, Class<T> claz) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, claz);
// }
// }
// Path: dingding-app-server-web/src/main/java/com/mocoder/dingding/web/util/CacheKeyGenerator.java
import com.mocoder.dingding.utils.web.JsonUtil;
import org.springframework.cache.interceptor.DefaultKeyGenerator;
import org.springframework.cache.interceptor.KeyGenerator;
import java.io.IOException;
import java.lang.reflect.Method;
package com.mocoder.dingding.web.util;
/**
* Created by yangshuai on 16/1/30.
*/
public class CacheKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object target, Method method, Object... params) {
try {
StringBuilder sb = new StringBuilder(target.getClass().getName()).append('.') | .append(method.getName()).append('(').append(JsonUtil.toString(params)) |
yangshuai0711/dingding-app-server | dingding-app-server-web/src/main/java/com/mocoder/dingding/web/annotation/ValidateBody.java | // Path: dingding-app-server-web/src/main/java/com/mocoder/dingding/web/util/BodyAlgorithmEnum.java
// public enum BodyAlgorithmEnum {
//
// BASE64("base64"),
// DES("des")
// ;
// private String name;
//
// BodyAlgorithmEnum(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
// }
| import com.mocoder.dingding.web.util.BodyAlgorithmEnum;
import java.lang.annotation.*; | package com.mocoder.dingding.web.annotation;
/**
* Created by yangshuai3 on 2016/2/1.
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValidateBody {
/**
* @return 参数字段名,从request.getParameter获取
*/
String value() default "body";
/**
* @return 对称加密算法
* @see com.mocoder.dingding.web.util.BodyAlgorithmEnum
*/ | // Path: dingding-app-server-web/src/main/java/com/mocoder/dingding/web/util/BodyAlgorithmEnum.java
// public enum BodyAlgorithmEnum {
//
// BASE64("base64"),
// DES("des")
// ;
// private String name;
//
// BodyAlgorithmEnum(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
// }
// Path: dingding-app-server-web/src/main/java/com/mocoder/dingding/web/annotation/ValidateBody.java
import com.mocoder.dingding.web.util.BodyAlgorithmEnum;
import java.lang.annotation.*;
package com.mocoder.dingding.web.annotation;
/**
* Created by yangshuai3 on 2016/2/1.
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValidateBody {
/**
* @return 参数字段名,从request.getParameter获取
*/
String value() default "body";
/**
* @return 对称加密算法
* @see com.mocoder.dingding.web.util.BodyAlgorithmEnum
*/ | BodyAlgorithmEnum[] algorithm() default {}; |
yangshuai0711/dingding-app-server | dingding-app-server-model/src/main/java/com/mocoder/dingding/vo/CommonResponse.java | // Path: dingding-app-server-model/src/main/java/com/mocoder/dingding/enums/ErrorTypeEnum.java
// public enum ErrorTypeEnum {
//
// SYSTEM_EXCEPTION(10,"后台程序异常","系统繁忙,请重试"),
// SYSTEM_ENV_EXCEPTION(11,"系统环境异常","系统繁忙,请重试"),
//
// INPUT_PARAMETER_VALIDATE_ERROR(20,"参数校验错误","系统繁忙,请重试"),
// INPUT_PARAMETER_SESSION_ERROR(-20,"参数sessionId为空","系统繁忙,请重试"),
// INPUT_PARAMETER_PARSE_ERROR(21,"入参解析错误","系统繁忙,请重试"),
//
// VALIDATE_CODE_ERROR(30,"验证码不正确","验证码输入有误,请重试"),
// VALIDATE_CODE_RETRY_ERROR(-30,"验证码不正确","验证码输入错误次数超过限制,请重新获取验证码"),
// NOT_LOGIN(-31,"未登录","您的登录信息已过期,请重新登录"),
// LOGIN_DUPLICATE_ERROR(31,"重复登录,session未过期,无需登录" ,"您已经在线,无需再次登录" ),
// REG_DUPLICATE_ERROR(32,"重复注册,手机号码已注册" ,"您的手机号码已注册" ),
// PASS_LOGIN_ERROR(33,"密码错误","账号或密码错误"),
// ACCOUNT_NOT_EXISTS(35,"手机号不存在","该手机号还没有注册"),
// NOT_LOG_OUT_ERROR(36,"需要退出登录状态","请先退出登录"),
//
// SMS_SEND_ERROR(40,"短信发送失败","短信发送失败,请稍后再试"),
//
// USER_OPERATE_NOT_PERMIT(50,"用户没有权限进行此操作","您没有权限进行此操作")
// ;
//
// private Integer code;
// private String msg;
// private String uiMsg;
//
// ErrorTypeEnum(Integer code, String msg, String uiMsg) {
// this.code = code;
// this.msg = msg;
// this.uiMsg = uiMsg;
// }
//
// public Integer getCode() {
// return code;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public String getUiMsg() {
// return uiMsg;
// }
// }
| import com.mocoder.dingding.enums.ErrorTypeEnum;
import java.io.Serializable; | package com.mocoder.dingding.vo;
/**
* Created by yangshuai3 on 2016/1/26.
*/
public class CommonResponse<T> implements Serializable {
private String code;
private String msg;
private T data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
| // Path: dingding-app-server-model/src/main/java/com/mocoder/dingding/enums/ErrorTypeEnum.java
// public enum ErrorTypeEnum {
//
// SYSTEM_EXCEPTION(10,"后台程序异常","系统繁忙,请重试"),
// SYSTEM_ENV_EXCEPTION(11,"系统环境异常","系统繁忙,请重试"),
//
// INPUT_PARAMETER_VALIDATE_ERROR(20,"参数校验错误","系统繁忙,请重试"),
// INPUT_PARAMETER_SESSION_ERROR(-20,"参数sessionId为空","系统繁忙,请重试"),
// INPUT_PARAMETER_PARSE_ERROR(21,"入参解析错误","系统繁忙,请重试"),
//
// VALIDATE_CODE_ERROR(30,"验证码不正确","验证码输入有误,请重试"),
// VALIDATE_CODE_RETRY_ERROR(-30,"验证码不正确","验证码输入错误次数超过限制,请重新获取验证码"),
// NOT_LOGIN(-31,"未登录","您的登录信息已过期,请重新登录"),
// LOGIN_DUPLICATE_ERROR(31,"重复登录,session未过期,无需登录" ,"您已经在线,无需再次登录" ),
// REG_DUPLICATE_ERROR(32,"重复注册,手机号码已注册" ,"您的手机号码已注册" ),
// PASS_LOGIN_ERROR(33,"密码错误","账号或密码错误"),
// ACCOUNT_NOT_EXISTS(35,"手机号不存在","该手机号还没有注册"),
// NOT_LOG_OUT_ERROR(36,"需要退出登录状态","请先退出登录"),
//
// SMS_SEND_ERROR(40,"短信发送失败","短信发送失败,请稍后再试"),
//
// USER_OPERATE_NOT_PERMIT(50,"用户没有权限进行此操作","您没有权限进行此操作")
// ;
//
// private Integer code;
// private String msg;
// private String uiMsg;
//
// ErrorTypeEnum(Integer code, String msg, String uiMsg) {
// this.code = code;
// this.msg = msg;
// this.uiMsg = uiMsg;
// }
//
// public Integer getCode() {
// return code;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public String getUiMsg() {
// return uiMsg;
// }
// }
// Path: dingding-app-server-model/src/main/java/com/mocoder/dingding/vo/CommonResponse.java
import com.mocoder.dingding.enums.ErrorTypeEnum;
import java.io.Serializable;
package com.mocoder.dingding.vo;
/**
* Created by yangshuai3 on 2016/1/26.
*/
public class CommonResponse<T> implements Serializable {
private String code;
private String msg;
private T data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
| public void resolveErrorInfo(ErrorTypeEnum errorType) { |
yangshuai0711/dingding-app-server | dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/web/WebUtil.java | // Path: dingding-app-server-model/src/main/java/com/mocoder/dingding/vo/CommonResponse.java
// public class CommonResponse<T> implements Serializable {
// private String code;
// private String msg;
// private T data;
//
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public void resolveErrorInfo(ErrorTypeEnum errorType) {
// this.code=String.valueOf(errorType.getCode());
// this.msg =errorType.getUiMsg();
// }
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
// }
| import com.mocoder.dingding.vo.CommonResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Map; |
/**
* 手否简单类型(字符串、基本类型以及其包装类型)
*
* @param obj 要判断的对象实例
* @return 是否简单类型
*/
public static boolean isSimpleType(Object obj) {
Class claz = obj.getClass();
if (claz.isPrimitive()) {//基本类型
return true;
}
try {
if (((Class) claz.getField("TYPE").get(null)).isPrimitive()) {//包装基本类型
return true;
}
} catch (Exception e) {
}
if (claz == String.class) {
return true;
}
return false;
}
/**
* 写出返回结果到response
* @param response
* @param result
* @throws IOException
*/ | // Path: dingding-app-server-model/src/main/java/com/mocoder/dingding/vo/CommonResponse.java
// public class CommonResponse<T> implements Serializable {
// private String code;
// private String msg;
// private T data;
//
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getMsg() {
// return msg;
// }
//
// public void setMsg(String msg) {
// this.msg = msg;
// }
//
// public void resolveErrorInfo(ErrorTypeEnum errorType) {
// this.code=String.valueOf(errorType.getCode());
// this.msg =errorType.getUiMsg();
// }
//
// public T getData() {
// return data;
// }
//
// public void setData(T data) {
// this.data = data;
// }
// }
// Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/web/WebUtil.java
import com.mocoder.dingding.vo.CommonResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Map;
/**
* 手否简单类型(字符串、基本类型以及其包装类型)
*
* @param obj 要判断的对象实例
* @return 是否简单类型
*/
public static boolean isSimpleType(Object obj) {
Class claz = obj.getClass();
if (claz.isPrimitive()) {//基本类型
return true;
}
try {
if (((Class) claz.getField("TYPE").get(null)).isPrimitive()) {//包装基本类型
return true;
}
} catch (Exception e) {
}
if (claz == String.class) {
return true;
}
return false;
}
/**
* 写出返回结果到response
* @param response
* @param result
* @throws IOException
*/ | public static void writeResponse(HttpServletResponse response, CommonResponse result) throws IOException { |
kong-jing/PreRect | app/src/main/java/xyz/kongjing/prerect/view/FaceView.java | // Path: app/src/main/java/xyz/kongjing/prerect/model/FaceInfo.java
// public class FaceInfo {
// public RectF rect;
// public int id;
// public int living;
// public int score;
//
// public RectF getRect() {
// return rect;
// }
//
// public void setRect(RectF rect) {
// this.rect = rect;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public int getLiving() {
// return living;
// }
//
// public void setLiving(int living) {
// this.living = living;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
// }
| import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import xyz.kongjing.prerect.model.FaceInfo; | package xyz.kongjing.prerect.view;
/**
* Created by Jing on 16/8/5.
*/
public class FaceView extends View {
Context mContext;
private Paint mLinePaint;
Paint textPaint; | // Path: app/src/main/java/xyz/kongjing/prerect/model/FaceInfo.java
// public class FaceInfo {
// public RectF rect;
// public int id;
// public int living;
// public int score;
//
// public RectF getRect() {
// return rect;
// }
//
// public void setRect(RectF rect) {
// this.rect = rect;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public int getLiving() {
// return living;
// }
//
// public void setLiving(int living) {
// this.living = living;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
// }
// Path: app/src/main/java/xyz/kongjing/prerect/view/FaceView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import xyz.kongjing.prerect.model.FaceInfo;
package xyz.kongjing.prerect.view;
/**
* Created by Jing on 16/8/5.
*/
public class FaceView extends View {
Context mContext;
private Paint mLinePaint;
Paint textPaint; | private FaceInfo[] mFaces; |
kong-jing/PreRect | app/src/main/java/xyz/kongjing/prerect/camera/CameraConfigurationManager.java | // Path: app/src/main/java/xyz/kongjing/prerect/callback/OnCaptureCallback.java
// public interface OnCaptureCallback {
//
// public void onCapture(byte[] jpgdata);
// }
| import android.util.Log;
import xyz.kongjing.prerect.callback.OnCaptureCallback;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.hardware.Camera.Size;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager; | parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0));
}
if (takingPictureZoomMaxString != null) {
parameters.set("taking-picture-zoom", tenDesiredZoom);
}
}
/**
* 设置照片尺寸为最接近指定尺寸
*
* @param list
* @return
*/
private void setPicutreSize(List<Size> list, int width, int height) {
int approach = Integer.MAX_VALUE;
for (Size size : list) {
int temp = Math.abs(size.width - width + size.height - height);
if (approach > temp) {
approach = temp;
pictureSize = size;
}
}
}
// 拍照
private ToneGenerator tone;
| // Path: app/src/main/java/xyz/kongjing/prerect/callback/OnCaptureCallback.java
// public interface OnCaptureCallback {
//
// public void onCapture(byte[] jpgdata);
// }
// Path: app/src/main/java/xyz/kongjing/prerect/camera/CameraConfigurationManager.java
import android.util.Log;
import xyz.kongjing.prerect.callback.OnCaptureCallback;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.hardware.Camera.Size;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0));
}
if (takingPictureZoomMaxString != null) {
parameters.set("taking-picture-zoom", tenDesiredZoom);
}
}
/**
* 设置照片尺寸为最接近指定尺寸
*
* @param list
* @return
*/
private void setPicutreSize(List<Size> list, int width, int height) {
int approach = Integer.MAX_VALUE;
for (Size size : list) {
int temp = Math.abs(size.width - width + size.height - height);
if (approach > temp) {
approach = temp;
pictureSize = size;
}
}
}
// 拍照
private ToneGenerator tone;
| public void tackPicture(Camera camera, final OnCaptureCallback callback) |
yale8848/RetrofitCache | retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/intercept/MockInterceptor.java | // Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
| import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import ren.yale.android.retrofitcachelibrx2.util.LogUtil; | package ren.yale.android.retrofitcachelibrx2.intercept;
/**
* Created by yale on 2019/7/24.
*/
public class MockInterceptor extends BaseInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response mockResponse = mockResponse(chain);
if (mockResponse!=null){
return mockResponse;
}
String mockUrl = mockUrl(chain);
if (mockUrl!=null){ | // Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
// Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/intercept/MockInterceptor.java
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import ren.yale.android.retrofitcachelibrx2.util.LogUtil;
package ren.yale.android.retrofitcachelibrx2.intercept;
/**
* Created by yale on 2019/7/24.
*/
public class MockInterceptor extends BaseInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response mockResponse = mockResponse(chain);
if (mockResponse!=null){
return mockResponse;
}
String mockUrl = mockUrl(chain);
if (mockUrl!=null){ | LogUtil.d("get data from mock url: "+mockUrl); |
yale8848/RetrofitCache | retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/RetrofitCache.java | // Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/bean/CacheConfig.java
// public class CacheConfig {
//
// private TimeUnit timeUnit = TimeUnit.NANOSECONDS;
// private Long time = 0L;
// private boolean forceCacheNoNet = true;
//
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(TimeUnit timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public Long getTime() {
// return time;
// }
//
// public void setTime(Long time) {
// this.time = time;
// }
//
// public boolean isForceCacheNoNet() {
// return forceCacheNoNet;
// }
//
// public void setForceCacheNoNet(boolean forceCacheNoNet) {
// this.forceCacheNoNet = forceCacheNoNet;
// }
// }
//
// Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
| import android.content.Context;
import android.text.TextUtils;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import okhttp3.Request;
import ren.yale.android.retrofitcachelibrx2.anno.Cache;
import ren.yale.android.retrofitcachelibrx2.anno.Mock;
import ren.yale.android.retrofitcachelibrx2.bean.CacheConfig;
import ren.yale.android.retrofitcachelibrx2.util.LogUtil;
import retrofit2.Retrofit; | package ren.yale.android.retrofitcachelibrx2;
/**
* Created by Yale on 2017/6/13.
*/
public class RetrofitCache {
private static volatile RetrofitCache mRetrofit;
private Vector<Map> mVector; | // Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/bean/CacheConfig.java
// public class CacheConfig {
//
// private TimeUnit timeUnit = TimeUnit.NANOSECONDS;
// private Long time = 0L;
// private boolean forceCacheNoNet = true;
//
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(TimeUnit timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public Long getTime() {
// return time;
// }
//
// public void setTime(Long time) {
// this.time = time;
// }
//
// public boolean isForceCacheNoNet() {
// return forceCacheNoNet;
// }
//
// public void setForceCacheNoNet(boolean forceCacheNoNet) {
// this.forceCacheNoNet = forceCacheNoNet;
// }
// }
//
// Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
// Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/RetrofitCache.java
import android.content.Context;
import android.text.TextUtils;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import okhttp3.Request;
import ren.yale.android.retrofitcachelibrx2.anno.Cache;
import ren.yale.android.retrofitcachelibrx2.anno.Mock;
import ren.yale.android.retrofitcachelibrx2.bean.CacheConfig;
import ren.yale.android.retrofitcachelibrx2.util.LogUtil;
import retrofit2.Retrofit;
package ren.yale.android.retrofitcachelibrx2;
/**
* Created by Yale on 2017/6/13.
*/
public class RetrofitCache {
private static volatile RetrofitCache mRetrofit;
private Vector<Map> mVector; | private Map<String,CacheConfig> mUrlMap; |
yale8848/RetrofitCache | retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/RetrofitCache.java | // Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/bean/CacheConfig.java
// public class CacheConfig {
//
// private TimeUnit timeUnit = TimeUnit.NANOSECONDS;
// private Long time = 0L;
// private boolean forceCacheNoNet = true;
//
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(TimeUnit timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public Long getTime() {
// return time;
// }
//
// public void setTime(Long time) {
// this.time = time;
// }
//
// public boolean isForceCacheNoNet() {
// return forceCacheNoNet;
// }
//
// public void setForceCacheNoNet(boolean forceCacheNoNet) {
// this.forceCacheNoNet = forceCacheNoNet;
// }
// }
//
// Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
| import android.content.Context;
import android.text.TextUtils;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import okhttp3.Request;
import ren.yale.android.retrofitcachelibrx2.anno.Cache;
import ren.yale.android.retrofitcachelibrx2.anno.Mock;
import ren.yale.android.retrofitcachelibrx2.bean.CacheConfig;
import ren.yale.android.retrofitcachelibrx2.util.LogUtil;
import retrofit2.Retrofit; | return mRetrofit;
}
public RetrofitCache init(Context context){
mContext = context.getApplicationContext();
return this;
}
public RetrofitCache enableMock(boolean mock){
mMock = mock;
return this;
}
public boolean canMock(){
return mMock;
}
public RetrofitCache addIgnoreParam(String param){
if (mIgnoreParam==null){
mIgnoreParam = new HashSet<>();
}
mIgnoreParam.add(param);
return this;
}
public Set<String> getIgnoreParam(){
return mIgnoreParam;
}
public void addMethodInfo(Object serviceMethod,Object[] args){
String url = "";
try {
url = buildRequestUrl(serviceMethod,args);
} catch (Exception e) { | // Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/bean/CacheConfig.java
// public class CacheConfig {
//
// private TimeUnit timeUnit = TimeUnit.NANOSECONDS;
// private Long time = 0L;
// private boolean forceCacheNoNet = true;
//
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(TimeUnit timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public Long getTime() {
// return time;
// }
//
// public void setTime(Long time) {
// this.time = time;
// }
//
// public boolean isForceCacheNoNet() {
// return forceCacheNoNet;
// }
//
// public void setForceCacheNoNet(boolean forceCacheNoNet) {
// this.forceCacheNoNet = forceCacheNoNet;
// }
// }
//
// Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
// Path: retrofitcachelibrx2/src/main/java/ren/yale/android/retrofitcachelibrx2/RetrofitCache.java
import android.content.Context;
import android.text.TextUtils;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import okhttp3.Request;
import ren.yale.android.retrofitcachelibrx2.anno.Cache;
import ren.yale.android.retrofitcachelibrx2.anno.Mock;
import ren.yale.android.retrofitcachelibrx2.bean.CacheConfig;
import ren.yale.android.retrofitcachelibrx2.util.LogUtil;
import retrofit2.Retrofit;
return mRetrofit;
}
public RetrofitCache init(Context context){
mContext = context.getApplicationContext();
return this;
}
public RetrofitCache enableMock(boolean mock){
mMock = mock;
return this;
}
public boolean canMock(){
return mMock;
}
public RetrofitCache addIgnoreParam(String param){
if (mIgnoreParam==null){
mIgnoreParam = new HashSet<>();
}
mIgnoreParam.add(param);
return this;
}
public Set<String> getIgnoreParam(){
return mIgnoreParam;
}
public void addMethodInfo(Object serviceMethod,Object[] args){
String url = "";
try {
url = buildRequestUrl(serviceMethod,args);
} catch (Exception e) { | LogUtil.l(e); |
yale8848/RetrofitCache | retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/intercept/MockInterceptor.java | // Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
| import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import ren.yale.android.retrofitcachelib.util.LogUtil; | package ren.yale.android.retrofitcachelib.intercept;
/**
* Created by yale on 2019/7/24.
*/
public class MockInterceptor extends BaseInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response mockResponse = mockResponse(chain);
if (mockResponse!=null){
return mockResponse;
}
String mockUrl = mockUrl(chain);
if (mockUrl!=null){ | // Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
// Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/intercept/MockInterceptor.java
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import ren.yale.android.retrofitcachelib.util.LogUtil;
package ren.yale.android.retrofitcachelib.intercept;
/**
* Created by yale on 2019/7/24.
*/
public class MockInterceptor extends BaseInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response mockResponse = mockResponse(chain);
if (mockResponse!=null){
return mockResponse;
}
String mockUrl = mockUrl(chain);
if (mockUrl!=null){ | LogUtil.d("get data from mock url: "+mockUrl); |
yale8848/RetrofitCache | retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/RetrofitCache.java | // Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/bean/CacheConfig.java
// public class CacheConfig {
//
// private TimeUnit timeUnit = TimeUnit.NANOSECONDS;
// private Long time = 0L;
// private boolean forceCacheNoNet = true;
//
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(TimeUnit timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public Long getTime() {
// return time;
// }
//
// public void setTime(Long time) {
// this.time = time;
// }
//
// public boolean isForceCacheNoNet() {
// return forceCacheNoNet;
// }
//
// public void setForceCacheNoNet(boolean forceCacheNoNet) {
// this.forceCacheNoNet = forceCacheNoNet;
// }
// }
//
// Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
| import android.content.Context;
import android.text.TextUtils;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import okhttp3.Request;
import ren.yale.android.retrofitcachelib.anno.Cache;
import ren.yale.android.retrofitcachelib.anno.Mock;
import ren.yale.android.retrofitcachelib.bean.CacheConfig;
import ren.yale.android.retrofitcachelib.util.LogUtil;
import retrofit2.Retrofit; | package ren.yale.android.retrofitcachelib;
/**
* Created by Yale on 2017/6/13.
*/
public class RetrofitCache {
private static volatile RetrofitCache mRetrofit;
private Vector<Map> mVector; | // Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/bean/CacheConfig.java
// public class CacheConfig {
//
// private TimeUnit timeUnit = TimeUnit.NANOSECONDS;
// private Long time = 0L;
// private boolean forceCacheNoNet = true;
//
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(TimeUnit timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public Long getTime() {
// return time;
// }
//
// public void setTime(Long time) {
// this.time = time;
// }
//
// public boolean isForceCacheNoNet() {
// return forceCacheNoNet;
// }
//
// public void setForceCacheNoNet(boolean forceCacheNoNet) {
// this.forceCacheNoNet = forceCacheNoNet;
// }
// }
//
// Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
// Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/RetrofitCache.java
import android.content.Context;
import android.text.TextUtils;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import okhttp3.Request;
import ren.yale.android.retrofitcachelib.anno.Cache;
import ren.yale.android.retrofitcachelib.anno.Mock;
import ren.yale.android.retrofitcachelib.bean.CacheConfig;
import ren.yale.android.retrofitcachelib.util.LogUtil;
import retrofit2.Retrofit;
package ren.yale.android.retrofitcachelib;
/**
* Created by Yale on 2017/6/13.
*/
public class RetrofitCache {
private static volatile RetrofitCache mRetrofit;
private Vector<Map> mVector; | private Map<String,CacheConfig> mUrlMap; |
yale8848/RetrofitCache | retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/RetrofitCache.java | // Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/bean/CacheConfig.java
// public class CacheConfig {
//
// private TimeUnit timeUnit = TimeUnit.NANOSECONDS;
// private Long time = 0L;
// private boolean forceCacheNoNet = true;
//
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(TimeUnit timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public Long getTime() {
// return time;
// }
//
// public void setTime(Long time) {
// this.time = time;
// }
//
// public boolean isForceCacheNoNet() {
// return forceCacheNoNet;
// }
//
// public void setForceCacheNoNet(boolean forceCacheNoNet) {
// this.forceCacheNoNet = forceCacheNoNet;
// }
// }
//
// Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
| import android.content.Context;
import android.text.TextUtils;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import okhttp3.Request;
import ren.yale.android.retrofitcachelib.anno.Cache;
import ren.yale.android.retrofitcachelib.anno.Mock;
import ren.yale.android.retrofitcachelib.bean.CacheConfig;
import ren.yale.android.retrofitcachelib.util.LogUtil;
import retrofit2.Retrofit; | return mRetrofit;
}
public RetrofitCache enableMock(boolean mock){
mMock = mock;
return this;
}
public boolean canMock(){
return mMock;
}
public RetrofitCache init(Context context){
mContext = context.getApplicationContext();
return this;
}
public RetrofitCache addIgnoreParam(String param){
if (mIgnoreParam==null){
mIgnoreParam = new HashSet<>();
}
mIgnoreParam.add(param);
return this;
}
public Set<String> getIgnoreParam(){
return mIgnoreParam;
}
public void addMethodInfo(Object serviceMethod,Object[] args){
String url = "";
try {
url = buildRequestUrl(serviceMethod,args);
} catch (Exception e) { | // Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/bean/CacheConfig.java
// public class CacheConfig {
//
// private TimeUnit timeUnit = TimeUnit.NANOSECONDS;
// private Long time = 0L;
// private boolean forceCacheNoNet = true;
//
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(TimeUnit timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public Long getTime() {
// return time;
// }
//
// public void setTime(Long time) {
// this.time = time;
// }
//
// public boolean isForceCacheNoNet() {
// return forceCacheNoNet;
// }
//
// public void setForceCacheNoNet(boolean forceCacheNoNet) {
// this.forceCacheNoNet = forceCacheNoNet;
// }
// }
//
// Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/util/LogUtil.java
// public class LogUtil {
// private static String TAG="retrofitcache";
// private static final boolean DEBUG = false;
// public static void d(String text){
// android.util.Log.d(TAG,text);
// }
// public static void w(String text){
// android.util.Log.w(TAG,text);
// }
//
// public static void l(Exception e){
// if (DEBUG){
// e.printStackTrace();
// }else{
// android.util.Log.w(TAG,e.toString());
// }
// }
// }
// Path: retrofitcachelib/src/main/java/ren/yale/android/retrofitcachelib/RetrofitCache.java
import android.content.Context;
import android.text.TextUtils;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import okhttp3.Request;
import ren.yale.android.retrofitcachelib.anno.Cache;
import ren.yale.android.retrofitcachelib.anno.Mock;
import ren.yale.android.retrofitcachelib.bean.CacheConfig;
import ren.yale.android.retrofitcachelib.util.LogUtil;
import retrofit2.Retrofit;
return mRetrofit;
}
public RetrofitCache enableMock(boolean mock){
mMock = mock;
return this;
}
public boolean canMock(){
return mMock;
}
public RetrofitCache init(Context context){
mContext = context.getApplicationContext();
return this;
}
public RetrofitCache addIgnoreParam(String param){
if (mIgnoreParam==null){
mIgnoreParam = new HashSet<>();
}
mIgnoreParam.add(param);
return this;
}
public Set<String> getIgnoreParam(){
return mIgnoreParam;
}
public void addMethodInfo(Object serviceMethod,Object[] args){
String url = "";
try {
url = buildRequestUrl(serviceMethod,args);
} catch (Exception e) { | LogUtil.l(e); |
nLight/jruby-http-kit | src/org/httpkit/client/IFilter.java | // Path: src/org/httpkit/DynamicBytes.java
// public class DynamicBytes {
// private byte[] data;
// private int idx = 0;
//
// public DynamicBytes(int size) {
// data = new byte[size];
// }
//
// private void expandIfNeeded(int more) {
// if (idx + more > data.length) {
// int after = (int) ((idx + more) * 1.33);
// // String msg = "expand memory, from " + data.length + " to " +
// // after + "; need " + more;
// // System.out.println(msg);
// data = Arrays.copyOf(data, after);
// }
// }
//
// public byte[] get() {
// return data;
// }
//
// public int length() {
// return idx;
// }
//
// public DynamicBytes append(byte b) {
// expandIfNeeded(1);
// data[idx++] = b;
// return this;
// }
//
// public void append(byte b1, byte b2) {
// expandIfNeeded(2);
// data[idx++] = b1;
// data[idx++] = b2;
// }
//
// @Override
// public String toString() {
// return "DynamicBytes[len=" + idx + ", cap=" + data.length + ']';
// }
//
// public DynamicBytes append(byte[] d, int length) {
// expandIfNeeded(length);
// System.arraycopy(d, 0, data, idx, length);
// idx += length;
// return this;
// }
//
// public DynamicBytes append(String str) {
// // ISO-8859-1. much faster than String.getBytes("ISO-8859-1")
// // less copy. 620ms vs 190ms
// int length = str.length();
// expandIfNeeded(length);
// for (int i = 0; i < length; i++) {
// char c = str.charAt(i);
// if (c < 128) {
// data[idx++] = (byte) c;
// } else {
// data[idx++] = (byte) '?'; // JDK uses ? to represent non ASCII
// }
// }
// return this;
// }
//
// public DynamicBytes append(String str, Charset c) {
// byte[] bs = str.getBytes(c);
// return append(bs, bs.length);
// }
// }
| import org.httpkit.DynamicBytes;
import java.util.Map; | package org.httpkit.client;
/**
* allow to abort the connection. for example, a crawler may abort the
* connection if not text
*
* @author feng
*/
public interface IFilter {
public final static IFilter ACCEPT_ALL = new IFilter() { | // Path: src/org/httpkit/DynamicBytes.java
// public class DynamicBytes {
// private byte[] data;
// private int idx = 0;
//
// public DynamicBytes(int size) {
// data = new byte[size];
// }
//
// private void expandIfNeeded(int more) {
// if (idx + more > data.length) {
// int after = (int) ((idx + more) * 1.33);
// // String msg = "expand memory, from " + data.length + " to " +
// // after + "; need " + more;
// // System.out.println(msg);
// data = Arrays.copyOf(data, after);
// }
// }
//
// public byte[] get() {
// return data;
// }
//
// public int length() {
// return idx;
// }
//
// public DynamicBytes append(byte b) {
// expandIfNeeded(1);
// data[idx++] = b;
// return this;
// }
//
// public void append(byte b1, byte b2) {
// expandIfNeeded(2);
// data[idx++] = b1;
// data[idx++] = b2;
// }
//
// @Override
// public String toString() {
// return "DynamicBytes[len=" + idx + ", cap=" + data.length + ']';
// }
//
// public DynamicBytes append(byte[] d, int length) {
// expandIfNeeded(length);
// System.arraycopy(d, 0, data, idx, length);
// idx += length;
// return this;
// }
//
// public DynamicBytes append(String str) {
// // ISO-8859-1. much faster than String.getBytes("ISO-8859-1")
// // less copy. 620ms vs 190ms
// int length = str.length();
// expandIfNeeded(length);
// for (int i = 0; i < length; i++) {
// char c = str.charAt(i);
// if (c < 128) {
// data[idx++] = (byte) c;
// } else {
// data[idx++] = (byte) '?'; // JDK uses ? to represent non ASCII
// }
// }
// return this;
// }
//
// public DynamicBytes append(String str, Charset c) {
// byte[] bs = str.getBytes(c);
// return append(bs, bs.length);
// }
// }
// Path: src/org/httpkit/client/IFilter.java
import org.httpkit.DynamicBytes;
import java.util.Map;
package org.httpkit.client;
/**
* allow to abort the connection. for example, a crawler may abort the
* connection if not text
*
* @author feng
*/
public interface IFilter {
public final static IFilter ACCEPT_ALL = new IFilter() { | public boolean accept(DynamicBytes partialBody) { |
nLight/jruby-http-kit | src/org/httpkit/HttpStatus.java | // Path: src/org/httpkit/HttpUtils.java
// public static final Charset ASCII = Charset.forName("US-ASCII");
| import static org.httpkit.HttpUtils.ASCII; | case 507:
return INSUFFICIENT_STORAGE;
case 510:
return NOT_EXTENDED;
}
final String reasonPhrase;
if (code < 100) {
reasonPhrase = "Unknown Status";
} else if (code < 200) {
reasonPhrase = "Informational";
} else if (code < 300) {
reasonPhrase = "Successful";
} else if (code < 400) {
reasonPhrase = "Redirection";
} else if (code < 500) {
reasonPhrase = "Client Error";
} else if (code < 600) {
reasonPhrase = "Server Error";
} else {
reasonPhrase = "Unknown Status";
}
return new HttpStatus(code, reasonPhrase + " (" + code + ')');
}
public HttpStatus(int code, String reasonPhrase) {
this.code = code;
this.reasonPhrase = reasonPhrase; | // Path: src/org/httpkit/HttpUtils.java
// public static final Charset ASCII = Charset.forName("US-ASCII");
// Path: src/org/httpkit/HttpStatus.java
import static org.httpkit.HttpUtils.ASCII;
case 507:
return INSUFFICIENT_STORAGE;
case 510:
return NOT_EXTENDED;
}
final String reasonPhrase;
if (code < 100) {
reasonPhrase = "Unknown Status";
} else if (code < 200) {
reasonPhrase = "Informational";
} else if (code < 300) {
reasonPhrase = "Successful";
} else if (code < 400) {
reasonPhrase = "Redirection";
} else if (code < 500) {
reasonPhrase = "Client Error";
} else if (code < 600) {
reasonPhrase = "Server Error";
} else {
reasonPhrase = "Unknown Status";
}
return new HttpStatus(code, reasonPhrase + " (" + code + ')');
}
public HttpStatus(int code, String reasonPhrase) {
this.code = code;
this.reasonPhrase = reasonPhrase; | bytes = ("HTTP/1.1 " + code + " " + reasonPhrase + "\r\n").getBytes(ASCII); |
nLight/jruby-http-kit | src/org/httpkit/LineReader.java | // Path: src/org/httpkit/HttpUtils.java
// public static final byte CR = 13; // \r
//
// Path: src/org/httpkit/HttpUtils.java
// public static final byte LF = 10; // \n
| import java.nio.ByteBuffer;
import java.util.Arrays;
import static org.httpkit.HttpUtils.CR;
import static org.httpkit.HttpUtils.LF; | package org.httpkit;
public class LineReader {
// 1k buffer, increase as necessary;
byte[] lineBuffer = new byte[1024];
int lineBufferIdx = 0;
private final int maxLine;
public LineReader(int maxLine) {
this.maxLine = maxLine;
}
public String readLine(ByteBuffer buffer) throws LineTooLargeException {
byte b;
boolean more = true;
while (buffer.hasRemaining() && more) {
b = buffer.get(); | // Path: src/org/httpkit/HttpUtils.java
// public static final byte CR = 13; // \r
//
// Path: src/org/httpkit/HttpUtils.java
// public static final byte LF = 10; // \n
// Path: src/org/httpkit/LineReader.java
import java.nio.ByteBuffer;
import java.util.Arrays;
import static org.httpkit.HttpUtils.CR;
import static org.httpkit.HttpUtils.LF;
package org.httpkit;
public class LineReader {
// 1k buffer, increase as necessary;
byte[] lineBuffer = new byte[1024];
int lineBufferIdx = 0;
private final int maxLine;
public LineReader(int maxLine) {
this.maxLine = maxLine;
}
public String readLine(ByteBuffer buffer) throws LineTooLargeException {
byte b;
boolean more = true;
while (buffer.hasRemaining() && more) {
b = buffer.get(); | if (b == CR) { |
nLight/jruby-http-kit | src/org/httpkit/LineReader.java | // Path: src/org/httpkit/HttpUtils.java
// public static final byte CR = 13; // \r
//
// Path: src/org/httpkit/HttpUtils.java
// public static final byte LF = 10; // \n
| import java.nio.ByteBuffer;
import java.util.Arrays;
import static org.httpkit.HttpUtils.CR;
import static org.httpkit.HttpUtils.LF; | package org.httpkit;
public class LineReader {
// 1k buffer, increase as necessary;
byte[] lineBuffer = new byte[1024];
int lineBufferIdx = 0;
private final int maxLine;
public LineReader(int maxLine) {
this.maxLine = maxLine;
}
public String readLine(ByteBuffer buffer) throws LineTooLargeException {
byte b;
boolean more = true;
while (buffer.hasRemaining() && more) {
b = buffer.get();
if (b == CR) { | // Path: src/org/httpkit/HttpUtils.java
// public static final byte CR = 13; // \r
//
// Path: src/org/httpkit/HttpUtils.java
// public static final byte LF = 10; // \n
// Path: src/org/httpkit/LineReader.java
import java.nio.ByteBuffer;
import java.util.Arrays;
import static org.httpkit.HttpUtils.CR;
import static org.httpkit.HttpUtils.LF;
package org.httpkit;
public class LineReader {
// 1k buffer, increase as necessary;
byte[] lineBuffer = new byte[1024];
int lineBufferIdx = 0;
private final int maxLine;
public LineReader(int maxLine) {
this.maxLine = maxLine;
}
public String readLine(ByteBuffer buffer) throws LineTooLargeException {
byte b;
boolean more = true;
while (buffer.hasRemaining() && more) {
b = buffer.get();
if (b == CR) { | if (buffer.hasRemaining() && buffer.get() == LF) { |
nLight/jruby-http-kit | src/org/httpkit/client/HttpClient.java | // Path: src/org/httpkit/ProtocolException.java
// public class ProtocolException extends HTTPException {
//
// private static final long serialVersionUID = 1L;
//
// public ProtocolException(String msg) {
// super(msg);
// }
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static final byte SP = 32;
//
// Path: src/org/httpkit/HttpUtils.java
// public static InetSocketAddress getServerAddr(URI uri) throws UnknownHostException {
// InetAddress host = getByName(uri.getHost());
// return new InetSocketAddress(host, getPort(uri));
// }
| import org.httpkit.*;
import org.httpkit.ProtocolException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.System.currentTimeMillis;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.SP;
import static org.httpkit.HttpUtils.getServerAddr;
import static org.httpkit.client.State.ALL_READ;
import static org.httpkit.client.State.READ_INITIAL; | if (!buffers[buffers.length - 1].hasRemaining()) {
key.interestOps(OP_READ);
}
}
} catch (IOException e) {
if (!cleanAndRetryIfBroken(key, req)) {
req.finish(e);
}
} catch (Exception e) { // rarely happen
req.finish(e);
}
}
public void exec(String url, RequestConfig cfg, SSLEngine engine, IRespListener cb) {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
cb.onThrowable(e);
return;
}
if (uri.getHost() == null) {
cb.onThrowable(new IllegalArgumentException("host is null: " + url));
return;
}
String scheme = uri.getScheme();
if (!"http".equals(scheme) && !"https".equals(scheme)) {
String message = (scheme == null) ? "No protocol specified" : scheme + " is not supported"; | // Path: src/org/httpkit/ProtocolException.java
// public class ProtocolException extends HTTPException {
//
// private static final long serialVersionUID = 1L;
//
// public ProtocolException(String msg) {
// super(msg);
// }
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static final byte SP = 32;
//
// Path: src/org/httpkit/HttpUtils.java
// public static InetSocketAddress getServerAddr(URI uri) throws UnknownHostException {
// InetAddress host = getByName(uri.getHost());
// return new InetSocketAddress(host, getPort(uri));
// }
// Path: src/org/httpkit/client/HttpClient.java
import org.httpkit.*;
import org.httpkit.ProtocolException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.System.currentTimeMillis;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.SP;
import static org.httpkit.HttpUtils.getServerAddr;
import static org.httpkit.client.State.ALL_READ;
import static org.httpkit.client.State.READ_INITIAL;
if (!buffers[buffers.length - 1].hasRemaining()) {
key.interestOps(OP_READ);
}
}
} catch (IOException e) {
if (!cleanAndRetryIfBroken(key, req)) {
req.finish(e);
}
} catch (Exception e) { // rarely happen
req.finish(e);
}
}
public void exec(String url, RequestConfig cfg, SSLEngine engine, IRespListener cb) {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
cb.onThrowable(e);
return;
}
if (uri.getHost() == null) {
cb.onThrowable(new IllegalArgumentException("host is null: " + url));
return;
}
String scheme = uri.getScheme();
if (!"http".equals(scheme) && !"https".equals(scheme)) {
String message = (scheme == null) ? "No protocol specified" : scheme + " is not supported"; | cb.onThrowable(new ProtocolException(message)); |
nLight/jruby-http-kit | src/org/httpkit/client/HttpClient.java | // Path: src/org/httpkit/ProtocolException.java
// public class ProtocolException extends HTTPException {
//
// private static final long serialVersionUID = 1L;
//
// public ProtocolException(String msg) {
// super(msg);
// }
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static final byte SP = 32;
//
// Path: src/org/httpkit/HttpUtils.java
// public static InetSocketAddress getServerAddr(URI uri) throws UnknownHostException {
// InetAddress host = getByName(uri.getHost());
// return new InetSocketAddress(host, getPort(uri));
// }
| import org.httpkit.*;
import org.httpkit.ProtocolException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.System.currentTimeMillis;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.SP;
import static org.httpkit.HttpUtils.getServerAddr;
import static org.httpkit.client.State.ALL_READ;
import static org.httpkit.client.State.READ_INITIAL; | req.finish(e);
}
} catch (Exception e) { // rarely happen
req.finish(e);
}
}
public void exec(String url, RequestConfig cfg, SSLEngine engine, IRespListener cb) {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
cb.onThrowable(e);
return;
}
if (uri.getHost() == null) {
cb.onThrowable(new IllegalArgumentException("host is null: " + url));
return;
}
String scheme = uri.getScheme();
if (!"http".equals(scheme) && !"https".equals(scheme)) {
String message = (scheme == null) ? "No protocol specified" : scheme + " is not supported";
cb.onThrowable(new ProtocolException(message));
return;
}
InetSocketAddress addr;
try { | // Path: src/org/httpkit/ProtocolException.java
// public class ProtocolException extends HTTPException {
//
// private static final long serialVersionUID = 1L;
//
// public ProtocolException(String msg) {
// super(msg);
// }
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static final byte SP = 32;
//
// Path: src/org/httpkit/HttpUtils.java
// public static InetSocketAddress getServerAddr(URI uri) throws UnknownHostException {
// InetAddress host = getByName(uri.getHost());
// return new InetSocketAddress(host, getPort(uri));
// }
// Path: src/org/httpkit/client/HttpClient.java
import org.httpkit.*;
import org.httpkit.ProtocolException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.System.currentTimeMillis;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.SP;
import static org.httpkit.HttpUtils.getServerAddr;
import static org.httpkit.client.State.ALL_READ;
import static org.httpkit.client.State.READ_INITIAL;
req.finish(e);
}
} catch (Exception e) { // rarely happen
req.finish(e);
}
}
public void exec(String url, RequestConfig cfg, SSLEngine engine, IRespListener cb) {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
cb.onThrowable(e);
return;
}
if (uri.getHost() == null) {
cb.onThrowable(new IllegalArgumentException("host is null: " + url));
return;
}
String scheme = uri.getScheme();
if (!"http".equals(scheme) && !"https".equals(scheme)) {
String message = (scheme == null) ? "No protocol specified" : scheme + " is not supported";
cb.onThrowable(new ProtocolException(message));
return;
}
InetSocketAddress addr;
try { | addr = getServerAddr(uri); |
nLight/jruby-http-kit | src/org/httpkit/client/HttpClient.java | // Path: src/org/httpkit/ProtocolException.java
// public class ProtocolException extends HTTPException {
//
// private static final long serialVersionUID = 1L;
//
// public ProtocolException(String msg) {
// super(msg);
// }
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static final byte SP = 32;
//
// Path: src/org/httpkit/HttpUtils.java
// public static InetSocketAddress getServerAddr(URI uri) throws UnknownHostException {
// InetAddress host = getByName(uri.getHost());
// return new InetSocketAddress(host, getPort(uri));
// }
| import org.httpkit.*;
import org.httpkit.ProtocolException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.System.currentTimeMillis;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.SP;
import static org.httpkit.HttpUtils.getServerAddr;
import static org.httpkit.client.State.ALL_READ;
import static org.httpkit.client.State.READ_INITIAL; | try {
request = encode(cfg.method, headers, cfg.body, uri);
} catch (IOException e) {
cb.onThrowable(e);
return;
}
if ("https".equals(scheme)) {
if (engine == null) {
engine = DEFAULT_CONTEXT.createSSLEngine();
}
engine.setUseClientMode(true);
pending.offer(new HttpsRequest(addr, request, cb, requests, cfg, engine));
} else {
pending.offer(new Request(addr, request, cb, requests, cfg));
}
// pending.offer(new Request(addr, request, cb, requests, cfg));
selector.wakeup();
}
private ByteBuffer[] encode(HttpMethod method, HeaderMap headers, Object body,
URI uri) throws IOException {
ByteBuffer bodyBuffer = HttpUtils.bodyBuffer(body);
if (body != null) {
headers.put("Content-Length", Integer.toString(bodyBuffer.remaining()));
} else {
headers.put("Content-Length", "0");
}
DynamicBytes bytes = new DynamicBytes(196); | // Path: src/org/httpkit/ProtocolException.java
// public class ProtocolException extends HTTPException {
//
// private static final long serialVersionUID = 1L;
//
// public ProtocolException(String msg) {
// super(msg);
// }
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static final byte SP = 32;
//
// Path: src/org/httpkit/HttpUtils.java
// public static InetSocketAddress getServerAddr(URI uri) throws UnknownHostException {
// InetAddress host = getByName(uri.getHost());
// return new InetSocketAddress(host, getPort(uri));
// }
// Path: src/org/httpkit/client/HttpClient.java
import org.httpkit.*;
import org.httpkit.ProtocolException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.System.currentTimeMillis;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.SP;
import static org.httpkit.HttpUtils.getServerAddr;
import static org.httpkit.client.State.ALL_READ;
import static org.httpkit.client.State.READ_INITIAL;
try {
request = encode(cfg.method, headers, cfg.body, uri);
} catch (IOException e) {
cb.onThrowable(e);
return;
}
if ("https".equals(scheme)) {
if (engine == null) {
engine = DEFAULT_CONTEXT.createSSLEngine();
}
engine.setUseClientMode(true);
pending.offer(new HttpsRequest(addr, request, cb, requests, cfg, engine));
} else {
pending.offer(new Request(addr, request, cb, requests, cfg));
}
// pending.offer(new Request(addr, request, cb, requests, cfg));
selector.wakeup();
}
private ByteBuffer[] encode(HttpMethod method, HeaderMap headers, Object body,
URI uri) throws IOException {
ByteBuffer bodyBuffer = HttpUtils.bodyBuffer(body);
if (body != null) {
headers.put("Content-Length", Integer.toString(bodyBuffer.remaining()));
} else {
headers.put("Content-Length", "0");
}
DynamicBytes bytes = new DynamicBytes(196); | bytes.append(method.toString()).append(SP).append(HttpUtils.getPath(uri)); |
nLight/jruby-http-kit | src/org/httpkit/client/RespListener.java | // Path: src/org/httpkit/HttpUtils.java
// public static final String CONTENT_ENCODING = "content-encoding";
//
// Path: src/org/httpkit/HttpUtils.java
// public static final String CONTENT_TYPE = "content-type";
| import org.httpkit.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import static org.httpkit.HttpUtils.CONTENT_ENCODING;
import static org.httpkit.HttpUtils.CONTENT_TYPE; | package org.httpkit.client;
class Handler implements Runnable {
private final int status;
private final Map<String, Object> headers;
private final Object body;
private final IResponseHandler handler;
public Handler(IResponseHandler handler, int status, Map<String, Object> headers,
Object body) {
this.handler = handler;
this.status = status;
this.headers = headers;
this.body = body;
}
public Handler(IResponseHandler handler, Throwable e) {
this(handler, 0, null, e);
}
public void run() {
if (body instanceof Throwable) {
handler.onThrowable((Throwable) body);
} else {
handler.onSuccess(status, headers, body);
}
}
}
/**
* Accumulate all the response, call upper logic at once, for easy use
*/
public class RespListener implements IRespListener {
private boolean isText() {
if (status.getCode() == 200) { | // Path: src/org/httpkit/HttpUtils.java
// public static final String CONTENT_ENCODING = "content-encoding";
//
// Path: src/org/httpkit/HttpUtils.java
// public static final String CONTENT_TYPE = "content-type";
// Path: src/org/httpkit/client/RespListener.java
import org.httpkit.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import static org.httpkit.HttpUtils.CONTENT_ENCODING;
import static org.httpkit.HttpUtils.CONTENT_TYPE;
package org.httpkit.client;
class Handler implements Runnable {
private final int status;
private final Map<String, Object> headers;
private final Object body;
private final IResponseHandler handler;
public Handler(IResponseHandler handler, int status, Map<String, Object> headers,
Object body) {
this.handler = handler;
this.status = status;
this.headers = headers;
this.body = body;
}
public Handler(IResponseHandler handler, Throwable e) {
this(handler, 0, null, e);
}
public void run() {
if (body instanceof Throwable) {
handler.onThrowable((Throwable) body);
} else {
handler.onSuccess(status, headers, body);
}
}
}
/**
* Accumulate all the response, call upper logic at once, for easy use
*/
public class RespListener implements IRespListener {
private boolean isText() {
if (status.getCode() == 200) { | String type = HttpUtils.getStringValue(headers, CONTENT_TYPE); |
nLight/jruby-http-kit | src/org/httpkit/client/RespListener.java | // Path: src/org/httpkit/HttpUtils.java
// public static final String CONTENT_ENCODING = "content-encoding";
//
// Path: src/org/httpkit/HttpUtils.java
// public static final String CONTENT_TYPE = "content-type";
| import org.httpkit.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import static org.httpkit.HttpUtils.CONTENT_ENCODING;
import static org.httpkit.HttpUtils.CONTENT_TYPE; | public void run() {
if (body instanceof Throwable) {
handler.onThrowable((Throwable) body);
} else {
handler.onSuccess(status, headers, body);
}
}
}
/**
* Accumulate all the response, call upper logic at once, for easy use
*/
public class RespListener implements IRespListener {
private boolean isText() {
if (status.getCode() == 200) {
String type = HttpUtils.getStringValue(headers, CONTENT_TYPE);
if (type != null) {
type = type.toLowerCase();
// TODO may miss something
return type.contains("text") || type.contains("json") || type.contains("xml");
} else {
return false;
}
} else { // non 200: treat as text
return true;
}
}
private DynamicBytes unzipBody() throws IOException { | // Path: src/org/httpkit/HttpUtils.java
// public static final String CONTENT_ENCODING = "content-encoding";
//
// Path: src/org/httpkit/HttpUtils.java
// public static final String CONTENT_TYPE = "content-type";
// Path: src/org/httpkit/client/RespListener.java
import org.httpkit.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import static org.httpkit.HttpUtils.CONTENT_ENCODING;
import static org.httpkit.HttpUtils.CONTENT_TYPE;
public void run() {
if (body instanceof Throwable) {
handler.onThrowable((Throwable) body);
} else {
handler.onSuccess(status, headers, body);
}
}
}
/**
* Accumulate all the response, call upper logic at once, for easy use
*/
public class RespListener implements IRespListener {
private boolean isText() {
if (status.getCode() == 200) {
String type = HttpUtils.getStringValue(headers, CONTENT_TYPE);
if (type != null) {
type = type.toLowerCase();
// TODO may miss something
return type.contains("text") || type.contains("json") || type.contains("xml");
} else {
return false;
}
} else { // non 200: treat as text
return true;
}
}
private DynamicBytes unzipBody() throws IOException { | String encoding = HttpUtils.getStringValue(headers, CONTENT_ENCODING); |
nLight/jruby-http-kit | src/org/httpkit/server/WSDecoder.java | // Path: src/org/httpkit/ProtocolException.java
// public class ProtocolException extends HTTPException {
//
// private static final long serialVersionUID = 1L;
//
// public ProtocolException(String msg) {
// super(msg);
// }
// }
| import org.httpkit.ProtocolException;
import java.nio.ByteBuffer;
import java.util.Arrays; | FRAME_START, READ_LENGTH, READ_2_LENGTH, READ_8_LENGTH, MASKING_KEY, PAYLOAD, CORRUPT
}
private State state = State.FRAME_START;
private byte[] content;
private int idx = 0;
private int payloadLength;
private int payloadRead;
private int maskingKey;
private boolean finalFlag;
private int opcode = -1;
private int framePayloadIndex; // masking per frame
// 8 bytes are enough
// protect against long/short/int are not fully received
private ByteBuffer tmpBuffer = ByteBuffer.allocate(8);
private boolean isAvailable(ByteBuffer src, int length) {
while (tmpBuffer.position() < length) {
if (src.hasRemaining()) {
tmpBuffer.put(src.get());
} else {
return false;
}
}
tmpBuffer.flip(); // for read
return true;
}
| // Path: src/org/httpkit/ProtocolException.java
// public class ProtocolException extends HTTPException {
//
// private static final long serialVersionUID = 1L;
//
// public ProtocolException(String msg) {
// super(msg);
// }
// }
// Path: src/org/httpkit/server/WSDecoder.java
import org.httpkit.ProtocolException;
import java.nio.ByteBuffer;
import java.util.Arrays;
FRAME_START, READ_LENGTH, READ_2_LENGTH, READ_8_LENGTH, MASKING_KEY, PAYLOAD, CORRUPT
}
private State state = State.FRAME_START;
private byte[] content;
private int idx = 0;
private int payloadLength;
private int payloadRead;
private int maskingKey;
private boolean finalFlag;
private int opcode = -1;
private int framePayloadIndex; // masking per frame
// 8 bytes are enough
// protect against long/short/int are not fully received
private ByteBuffer tmpBuffer = ByteBuffer.allocate(8);
private boolean isAvailable(ByteBuffer src, int length) {
while (tmpBuffer.position() < length) {
if (src.hasRemaining()) {
tmpBuffer.put(src.get());
} else {
return false;
}
}
tmpBuffer.flip(); // for read
return true;
}
| public Frame decode(ByteBuffer buffer) throws ProtocolException { |
nLight/jruby-http-kit | src/org/httpkit/server/HttpServer.java | // Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer[] HttpEncode(int status, HeaderMap headers, Object body) {
// ByteBuffer bodyBuffer;
// try {
// bodyBuffer = bodyBuffer(body);
// // only write length if not chunked
// if (!CHUNKED.equals(headers.get("Transfer-Encoding"))) {
// if (bodyBuffer != null) {
// headers.put(CL, Integer.toString(bodyBuffer.remaining()));
// }
// }
// } catch (IOException e) {
// byte[] b = e.getMessage().getBytes(ASCII);
// status = 500;
// headers.clear();
// headers.put(CL, Integer.toString(b.length));
// bodyBuffer = ByteBuffer.wrap(b);
// }
// headers.put("Server", "http-kit");
// headers.put("Date", DateFormatter.getDate()); // rfc says the Date is needed
//
// DynamicBytes bytes = new DynamicBytes(196);
// byte[] bs = HttpStatus.valueOf(status).getInitialLineBytes();
// bytes.append(bs, bs.length);
// headers.encodeHeaders(bytes);
// ByteBuffer headBuffer = ByteBuffer.wrap(bytes.get(), 0, bytes.length());
//
// if (bodyBuffer != null)
// return new ByteBuffer[]{headBuffer, bodyBuffer};
// else
// return new ByteBuffer[]{headBuffer};
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer WsEncode(byte opcode, byte[] data, int length) {
// byte b0 = 0;
// b0 |= 1 << 7; // FIN
// b0 |= opcode;
// ByteBuffer buffer = ByteBuffer.allocate(length + 10); // max
// buffer.put(b0);
//
// if (length <= 125) {
// buffer.put((byte) (length));
// } else if (length <= 0xFFFF) {
// buffer.put((byte) 126);
// buffer.putShort((short) length);
// } else {
// buffer.put((byte) 127);
// buffer.putLong(length);
// }
// buffer.put(data, 0, length);
// buffer.flip();
// return buffer;
// }
//
// Path: src/org/httpkit/server/Frame.java
// public static class CloseFrame extends Frame {
//
// public final static short CLOSE_NORMAL = 1000;
// // indicates that an endpoint is "going away", such as a server going down
// // or a browser having navigated away from a page.
// public final static short CLOSE_AWAY = 1001;
// // public final static short CLOSE_PROTOCOL_ERROR = 1002;
// // public final static short CLOSE_NOT_IMPL = 1003;
// // This is a generic status code that can be returned when there is no other
// // more suitable status code (e.g., 1003 or 1009)
// // public final static short CLOSE_VIOLATES_POLICY = 1008;
// public final static short CLOSE_MESG_BIG = 1009;
// // public final static short CLOSE_SEVER_ERROR = 1011;
//
// // private static byte[] bytes(short code) {
// // return ByteBuffer.allocate(2).putShort(code).array();
// // }
//
// // public static final CloseFrame NORMAL = new CloseFrame(bytes(CLOSE_NORMAL));
// // public static final CloseFrame AWAY = new CloseFrame(bytes(CLOSE_AWAY));
// // public static final CloseFrame MESG_BIG = new CloseFrame(bytes(CLOSE_MESG_BIG));
// // public static final CloseFrame SERVER_ERROR = new CloseFrame(bytes(CLOSE_MESG_BIG));
//
// public CloseFrame(byte[] data) {
// super(data);
// }
//
// public int getStatus() {
// if (data.length >= 2) {
// return ByteBuffer.wrap(data, 0, 2).getShort();
// }
// return CLOSE_NORMAL;
// }
// }
| import org.httpkit.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.HttpEncode;
import static org.httpkit.HttpUtils.WsEncode;
import static org.httpkit.server.Frame.CloseFrame.*; | if (att instanceof HttpAtta) {
handler.clientClose(att.channel, -1);
} else {
handler.clientClose(att.channel, status);
}
}
private void decodeHttp(HttpAtta atta, SelectionKey key, SocketChannel ch) {
try {
do {
AsyncChannel channel = atta.channel;
HttpRequest request = atta.decoder.decode(buffer);
if (request != null) {
channel.reset(request);
if (request.isWebSocket) {
key.attach(new WsAtta(channel));
} else {
atta.keepalive = request.isKeepAlive;
}
request.channel = channel;
request.remoteAddr = (InetSocketAddress) ch.socket().getRemoteSocketAddress();
handler.handle(request, new RespCallback(key, this));
// pipelining not supported : need queue to ensure order
atta.decoder.reset();
}
} while (buffer.hasRemaining()); // consume all
} catch (ProtocolException e) {
closeKey(key, -1);
} catch (RequestTooLargeException e) {
atta.keepalive = false; | // Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer[] HttpEncode(int status, HeaderMap headers, Object body) {
// ByteBuffer bodyBuffer;
// try {
// bodyBuffer = bodyBuffer(body);
// // only write length if not chunked
// if (!CHUNKED.equals(headers.get("Transfer-Encoding"))) {
// if (bodyBuffer != null) {
// headers.put(CL, Integer.toString(bodyBuffer.remaining()));
// }
// }
// } catch (IOException e) {
// byte[] b = e.getMessage().getBytes(ASCII);
// status = 500;
// headers.clear();
// headers.put(CL, Integer.toString(b.length));
// bodyBuffer = ByteBuffer.wrap(b);
// }
// headers.put("Server", "http-kit");
// headers.put("Date", DateFormatter.getDate()); // rfc says the Date is needed
//
// DynamicBytes bytes = new DynamicBytes(196);
// byte[] bs = HttpStatus.valueOf(status).getInitialLineBytes();
// bytes.append(bs, bs.length);
// headers.encodeHeaders(bytes);
// ByteBuffer headBuffer = ByteBuffer.wrap(bytes.get(), 0, bytes.length());
//
// if (bodyBuffer != null)
// return new ByteBuffer[]{headBuffer, bodyBuffer};
// else
// return new ByteBuffer[]{headBuffer};
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer WsEncode(byte opcode, byte[] data, int length) {
// byte b0 = 0;
// b0 |= 1 << 7; // FIN
// b0 |= opcode;
// ByteBuffer buffer = ByteBuffer.allocate(length + 10); // max
// buffer.put(b0);
//
// if (length <= 125) {
// buffer.put((byte) (length));
// } else if (length <= 0xFFFF) {
// buffer.put((byte) 126);
// buffer.putShort((short) length);
// } else {
// buffer.put((byte) 127);
// buffer.putLong(length);
// }
// buffer.put(data, 0, length);
// buffer.flip();
// return buffer;
// }
//
// Path: src/org/httpkit/server/Frame.java
// public static class CloseFrame extends Frame {
//
// public final static short CLOSE_NORMAL = 1000;
// // indicates that an endpoint is "going away", such as a server going down
// // or a browser having navigated away from a page.
// public final static short CLOSE_AWAY = 1001;
// // public final static short CLOSE_PROTOCOL_ERROR = 1002;
// // public final static short CLOSE_NOT_IMPL = 1003;
// // This is a generic status code that can be returned when there is no other
// // more suitable status code (e.g., 1003 or 1009)
// // public final static short CLOSE_VIOLATES_POLICY = 1008;
// public final static short CLOSE_MESG_BIG = 1009;
// // public final static short CLOSE_SEVER_ERROR = 1011;
//
// // private static byte[] bytes(short code) {
// // return ByteBuffer.allocate(2).putShort(code).array();
// // }
//
// // public static final CloseFrame NORMAL = new CloseFrame(bytes(CLOSE_NORMAL));
// // public static final CloseFrame AWAY = new CloseFrame(bytes(CLOSE_AWAY));
// // public static final CloseFrame MESG_BIG = new CloseFrame(bytes(CLOSE_MESG_BIG));
// // public static final CloseFrame SERVER_ERROR = new CloseFrame(bytes(CLOSE_MESG_BIG));
//
// public CloseFrame(byte[] data) {
// super(data);
// }
//
// public int getStatus() {
// if (data.length >= 2) {
// return ByteBuffer.wrap(data, 0, 2).getShort();
// }
// return CLOSE_NORMAL;
// }
// }
// Path: src/org/httpkit/server/HttpServer.java
import org.httpkit.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.HttpEncode;
import static org.httpkit.HttpUtils.WsEncode;
import static org.httpkit.server.Frame.CloseFrame.*;
if (att instanceof HttpAtta) {
handler.clientClose(att.channel, -1);
} else {
handler.clientClose(att.channel, status);
}
}
private void decodeHttp(HttpAtta atta, SelectionKey key, SocketChannel ch) {
try {
do {
AsyncChannel channel = atta.channel;
HttpRequest request = atta.decoder.decode(buffer);
if (request != null) {
channel.reset(request);
if (request.isWebSocket) {
key.attach(new WsAtta(channel));
} else {
atta.keepalive = request.isKeepAlive;
}
request.channel = channel;
request.remoteAddr = (InetSocketAddress) ch.socket().getRemoteSocketAddress();
handler.handle(request, new RespCallback(key, this));
// pipelining not supported : need queue to ensure order
atta.decoder.reset();
}
} while (buffer.hasRemaining()); // consume all
} catch (ProtocolException e) {
closeKey(key, -1);
} catch (RequestTooLargeException e) {
atta.keepalive = false; | tryWrite(key, HttpEncode(413, new HeaderMap(), e.getMessage())); |
nLight/jruby-http-kit | src/org/httpkit/server/HttpServer.java | // Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer[] HttpEncode(int status, HeaderMap headers, Object body) {
// ByteBuffer bodyBuffer;
// try {
// bodyBuffer = bodyBuffer(body);
// // only write length if not chunked
// if (!CHUNKED.equals(headers.get("Transfer-Encoding"))) {
// if (bodyBuffer != null) {
// headers.put(CL, Integer.toString(bodyBuffer.remaining()));
// }
// }
// } catch (IOException e) {
// byte[] b = e.getMessage().getBytes(ASCII);
// status = 500;
// headers.clear();
// headers.put(CL, Integer.toString(b.length));
// bodyBuffer = ByteBuffer.wrap(b);
// }
// headers.put("Server", "http-kit");
// headers.put("Date", DateFormatter.getDate()); // rfc says the Date is needed
//
// DynamicBytes bytes = new DynamicBytes(196);
// byte[] bs = HttpStatus.valueOf(status).getInitialLineBytes();
// bytes.append(bs, bs.length);
// headers.encodeHeaders(bytes);
// ByteBuffer headBuffer = ByteBuffer.wrap(bytes.get(), 0, bytes.length());
//
// if (bodyBuffer != null)
// return new ByteBuffer[]{headBuffer, bodyBuffer};
// else
// return new ByteBuffer[]{headBuffer};
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer WsEncode(byte opcode, byte[] data, int length) {
// byte b0 = 0;
// b0 |= 1 << 7; // FIN
// b0 |= opcode;
// ByteBuffer buffer = ByteBuffer.allocate(length + 10); // max
// buffer.put(b0);
//
// if (length <= 125) {
// buffer.put((byte) (length));
// } else if (length <= 0xFFFF) {
// buffer.put((byte) 126);
// buffer.putShort((short) length);
// } else {
// buffer.put((byte) 127);
// buffer.putLong(length);
// }
// buffer.put(data, 0, length);
// buffer.flip();
// return buffer;
// }
//
// Path: src/org/httpkit/server/Frame.java
// public static class CloseFrame extends Frame {
//
// public final static short CLOSE_NORMAL = 1000;
// // indicates that an endpoint is "going away", such as a server going down
// // or a browser having navigated away from a page.
// public final static short CLOSE_AWAY = 1001;
// // public final static short CLOSE_PROTOCOL_ERROR = 1002;
// // public final static short CLOSE_NOT_IMPL = 1003;
// // This is a generic status code that can be returned when there is no other
// // more suitable status code (e.g., 1003 or 1009)
// // public final static short CLOSE_VIOLATES_POLICY = 1008;
// public final static short CLOSE_MESG_BIG = 1009;
// // public final static short CLOSE_SEVER_ERROR = 1011;
//
// // private static byte[] bytes(short code) {
// // return ByteBuffer.allocate(2).putShort(code).array();
// // }
//
// // public static final CloseFrame NORMAL = new CloseFrame(bytes(CLOSE_NORMAL));
// // public static final CloseFrame AWAY = new CloseFrame(bytes(CLOSE_AWAY));
// // public static final CloseFrame MESG_BIG = new CloseFrame(bytes(CLOSE_MESG_BIG));
// // public static final CloseFrame SERVER_ERROR = new CloseFrame(bytes(CLOSE_MESG_BIG));
//
// public CloseFrame(byte[] data) {
// super(data);
// }
//
// public int getStatus() {
// if (data.length >= 2) {
// return ByteBuffer.wrap(data, 0, 2).getShort();
// }
// return CLOSE_NORMAL;
// }
// }
| import org.httpkit.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.HttpEncode;
import static org.httpkit.HttpUtils.WsEncode;
import static org.httpkit.server.Frame.CloseFrame.*; | } else {
atta.keepalive = request.isKeepAlive;
}
request.channel = channel;
request.remoteAddr = (InetSocketAddress) ch.socket().getRemoteSocketAddress();
handler.handle(request, new RespCallback(key, this));
// pipelining not supported : need queue to ensure order
atta.decoder.reset();
}
} while (buffer.hasRemaining()); // consume all
} catch (ProtocolException e) {
closeKey(key, -1);
} catch (RequestTooLargeException e) {
atta.keepalive = false;
tryWrite(key, HttpEncode(413, new HeaderMap(), e.getMessage()));
} catch (LineTooLargeException e) {
atta.keepalive = false; // close after write
tryWrite(key, HttpEncode(414, new HeaderMap(), e.getMessage()));
}
}
private void decodeWs(WsAtta atta, SelectionKey key) {
try {
do {
Frame frame = atta.decoder.decode(buffer);
if (frame instanceof TextFrame || frame instanceof BinaryFrame) {
handler.handle(atta.channel, frame);
atta.decoder.reset();
} else if (frame instanceof PingFrame) {
atta.decoder.reset(); | // Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer[] HttpEncode(int status, HeaderMap headers, Object body) {
// ByteBuffer bodyBuffer;
// try {
// bodyBuffer = bodyBuffer(body);
// // only write length if not chunked
// if (!CHUNKED.equals(headers.get("Transfer-Encoding"))) {
// if (bodyBuffer != null) {
// headers.put(CL, Integer.toString(bodyBuffer.remaining()));
// }
// }
// } catch (IOException e) {
// byte[] b = e.getMessage().getBytes(ASCII);
// status = 500;
// headers.clear();
// headers.put(CL, Integer.toString(b.length));
// bodyBuffer = ByteBuffer.wrap(b);
// }
// headers.put("Server", "http-kit");
// headers.put("Date", DateFormatter.getDate()); // rfc says the Date is needed
//
// DynamicBytes bytes = new DynamicBytes(196);
// byte[] bs = HttpStatus.valueOf(status).getInitialLineBytes();
// bytes.append(bs, bs.length);
// headers.encodeHeaders(bytes);
// ByteBuffer headBuffer = ByteBuffer.wrap(bytes.get(), 0, bytes.length());
//
// if (bodyBuffer != null)
// return new ByteBuffer[]{headBuffer, bodyBuffer};
// else
// return new ByteBuffer[]{headBuffer};
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer WsEncode(byte opcode, byte[] data, int length) {
// byte b0 = 0;
// b0 |= 1 << 7; // FIN
// b0 |= opcode;
// ByteBuffer buffer = ByteBuffer.allocate(length + 10); // max
// buffer.put(b0);
//
// if (length <= 125) {
// buffer.put((byte) (length));
// } else if (length <= 0xFFFF) {
// buffer.put((byte) 126);
// buffer.putShort((short) length);
// } else {
// buffer.put((byte) 127);
// buffer.putLong(length);
// }
// buffer.put(data, 0, length);
// buffer.flip();
// return buffer;
// }
//
// Path: src/org/httpkit/server/Frame.java
// public static class CloseFrame extends Frame {
//
// public final static short CLOSE_NORMAL = 1000;
// // indicates that an endpoint is "going away", such as a server going down
// // or a browser having navigated away from a page.
// public final static short CLOSE_AWAY = 1001;
// // public final static short CLOSE_PROTOCOL_ERROR = 1002;
// // public final static short CLOSE_NOT_IMPL = 1003;
// // This is a generic status code that can be returned when there is no other
// // more suitable status code (e.g., 1003 or 1009)
// // public final static short CLOSE_VIOLATES_POLICY = 1008;
// public final static short CLOSE_MESG_BIG = 1009;
// // public final static short CLOSE_SEVER_ERROR = 1011;
//
// // private static byte[] bytes(short code) {
// // return ByteBuffer.allocate(2).putShort(code).array();
// // }
//
// // public static final CloseFrame NORMAL = new CloseFrame(bytes(CLOSE_NORMAL));
// // public static final CloseFrame AWAY = new CloseFrame(bytes(CLOSE_AWAY));
// // public static final CloseFrame MESG_BIG = new CloseFrame(bytes(CLOSE_MESG_BIG));
// // public static final CloseFrame SERVER_ERROR = new CloseFrame(bytes(CLOSE_MESG_BIG));
//
// public CloseFrame(byte[] data) {
// super(data);
// }
//
// public int getStatus() {
// if (data.length >= 2) {
// return ByteBuffer.wrap(data, 0, 2).getShort();
// }
// return CLOSE_NORMAL;
// }
// }
// Path: src/org/httpkit/server/HttpServer.java
import org.httpkit.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.HttpEncode;
import static org.httpkit.HttpUtils.WsEncode;
import static org.httpkit.server.Frame.CloseFrame.*;
} else {
atta.keepalive = request.isKeepAlive;
}
request.channel = channel;
request.remoteAddr = (InetSocketAddress) ch.socket().getRemoteSocketAddress();
handler.handle(request, new RespCallback(key, this));
// pipelining not supported : need queue to ensure order
atta.decoder.reset();
}
} while (buffer.hasRemaining()); // consume all
} catch (ProtocolException e) {
closeKey(key, -1);
} catch (RequestTooLargeException e) {
atta.keepalive = false;
tryWrite(key, HttpEncode(413, new HeaderMap(), e.getMessage()));
} catch (LineTooLargeException e) {
atta.keepalive = false; // close after write
tryWrite(key, HttpEncode(414, new HeaderMap(), e.getMessage()));
}
}
private void decodeWs(WsAtta atta, SelectionKey key) {
try {
do {
Frame frame = atta.decoder.decode(buffer);
if (frame instanceof TextFrame || frame instanceof BinaryFrame) {
handler.handle(atta.channel, frame);
atta.decoder.reset();
} else if (frame instanceof PingFrame) {
atta.decoder.reset(); | tryWrite(key, WsEncode(WSDecoder.OPCODE_PONG, frame.data)); |
nLight/jruby-http-kit | src/org/httpkit/server/HttpServer.java | // Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer[] HttpEncode(int status, HeaderMap headers, Object body) {
// ByteBuffer bodyBuffer;
// try {
// bodyBuffer = bodyBuffer(body);
// // only write length if not chunked
// if (!CHUNKED.equals(headers.get("Transfer-Encoding"))) {
// if (bodyBuffer != null) {
// headers.put(CL, Integer.toString(bodyBuffer.remaining()));
// }
// }
// } catch (IOException e) {
// byte[] b = e.getMessage().getBytes(ASCII);
// status = 500;
// headers.clear();
// headers.put(CL, Integer.toString(b.length));
// bodyBuffer = ByteBuffer.wrap(b);
// }
// headers.put("Server", "http-kit");
// headers.put("Date", DateFormatter.getDate()); // rfc says the Date is needed
//
// DynamicBytes bytes = new DynamicBytes(196);
// byte[] bs = HttpStatus.valueOf(status).getInitialLineBytes();
// bytes.append(bs, bs.length);
// headers.encodeHeaders(bytes);
// ByteBuffer headBuffer = ByteBuffer.wrap(bytes.get(), 0, bytes.length());
//
// if (bodyBuffer != null)
// return new ByteBuffer[]{headBuffer, bodyBuffer};
// else
// return new ByteBuffer[]{headBuffer};
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer WsEncode(byte opcode, byte[] data, int length) {
// byte b0 = 0;
// b0 |= 1 << 7; // FIN
// b0 |= opcode;
// ByteBuffer buffer = ByteBuffer.allocate(length + 10); // max
// buffer.put(b0);
//
// if (length <= 125) {
// buffer.put((byte) (length));
// } else if (length <= 0xFFFF) {
// buffer.put((byte) 126);
// buffer.putShort((short) length);
// } else {
// buffer.put((byte) 127);
// buffer.putLong(length);
// }
// buffer.put(data, 0, length);
// buffer.flip();
// return buffer;
// }
//
// Path: src/org/httpkit/server/Frame.java
// public static class CloseFrame extends Frame {
//
// public final static short CLOSE_NORMAL = 1000;
// // indicates that an endpoint is "going away", such as a server going down
// // or a browser having navigated away from a page.
// public final static short CLOSE_AWAY = 1001;
// // public final static short CLOSE_PROTOCOL_ERROR = 1002;
// // public final static short CLOSE_NOT_IMPL = 1003;
// // This is a generic status code that can be returned when there is no other
// // more suitable status code (e.g., 1003 or 1009)
// // public final static short CLOSE_VIOLATES_POLICY = 1008;
// public final static short CLOSE_MESG_BIG = 1009;
// // public final static short CLOSE_SEVER_ERROR = 1011;
//
// // private static byte[] bytes(short code) {
// // return ByteBuffer.allocate(2).putShort(code).array();
// // }
//
// // public static final CloseFrame NORMAL = new CloseFrame(bytes(CLOSE_NORMAL));
// // public static final CloseFrame AWAY = new CloseFrame(bytes(CLOSE_AWAY));
// // public static final CloseFrame MESG_BIG = new CloseFrame(bytes(CLOSE_MESG_BIG));
// // public static final CloseFrame SERVER_ERROR = new CloseFrame(bytes(CLOSE_MESG_BIG));
//
// public CloseFrame(byte[] data) {
// super(data);
// }
//
// public int getStatus() {
// if (data.length >= 2) {
// return ByteBuffer.wrap(data, 0, 2).getShort();
// }
// return CLOSE_NORMAL;
// }
// }
| import org.httpkit.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.HttpEncode;
import static org.httpkit.HttpUtils.WsEncode;
import static org.httpkit.server.Frame.CloseFrame.*; | atta.keepalive = request.isKeepAlive;
}
request.channel = channel;
request.remoteAddr = (InetSocketAddress) ch.socket().getRemoteSocketAddress();
handler.handle(request, new RespCallback(key, this));
// pipelining not supported : need queue to ensure order
atta.decoder.reset();
}
} while (buffer.hasRemaining()); // consume all
} catch (ProtocolException e) {
closeKey(key, -1);
} catch (RequestTooLargeException e) {
atta.keepalive = false;
tryWrite(key, HttpEncode(413, new HeaderMap(), e.getMessage()));
} catch (LineTooLargeException e) {
atta.keepalive = false; // close after write
tryWrite(key, HttpEncode(414, new HeaderMap(), e.getMessage()));
}
}
private void decodeWs(WsAtta atta, SelectionKey key) {
try {
do {
Frame frame = atta.decoder.decode(buffer);
if (frame instanceof TextFrame || frame instanceof BinaryFrame) {
handler.handle(atta.channel, frame);
atta.decoder.reset();
} else if (frame instanceof PingFrame) {
atta.decoder.reset();
tryWrite(key, WsEncode(WSDecoder.OPCODE_PONG, frame.data)); | // Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer[] HttpEncode(int status, HeaderMap headers, Object body) {
// ByteBuffer bodyBuffer;
// try {
// bodyBuffer = bodyBuffer(body);
// // only write length if not chunked
// if (!CHUNKED.equals(headers.get("Transfer-Encoding"))) {
// if (bodyBuffer != null) {
// headers.put(CL, Integer.toString(bodyBuffer.remaining()));
// }
// }
// } catch (IOException e) {
// byte[] b = e.getMessage().getBytes(ASCII);
// status = 500;
// headers.clear();
// headers.put(CL, Integer.toString(b.length));
// bodyBuffer = ByteBuffer.wrap(b);
// }
// headers.put("Server", "http-kit");
// headers.put("Date", DateFormatter.getDate()); // rfc says the Date is needed
//
// DynamicBytes bytes = new DynamicBytes(196);
// byte[] bs = HttpStatus.valueOf(status).getInitialLineBytes();
// bytes.append(bs, bs.length);
// headers.encodeHeaders(bytes);
// ByteBuffer headBuffer = ByteBuffer.wrap(bytes.get(), 0, bytes.length());
//
// if (bodyBuffer != null)
// return new ByteBuffer[]{headBuffer, bodyBuffer};
// else
// return new ByteBuffer[]{headBuffer};
// }
//
// Path: src/org/httpkit/HttpUtils.java
// public static ByteBuffer WsEncode(byte opcode, byte[] data, int length) {
// byte b0 = 0;
// b0 |= 1 << 7; // FIN
// b0 |= opcode;
// ByteBuffer buffer = ByteBuffer.allocate(length + 10); // max
// buffer.put(b0);
//
// if (length <= 125) {
// buffer.put((byte) (length));
// } else if (length <= 0xFFFF) {
// buffer.put((byte) 126);
// buffer.putShort((short) length);
// } else {
// buffer.put((byte) 127);
// buffer.putLong(length);
// }
// buffer.put(data, 0, length);
// buffer.flip();
// return buffer;
// }
//
// Path: src/org/httpkit/server/Frame.java
// public static class CloseFrame extends Frame {
//
// public final static short CLOSE_NORMAL = 1000;
// // indicates that an endpoint is "going away", such as a server going down
// // or a browser having navigated away from a page.
// public final static short CLOSE_AWAY = 1001;
// // public final static short CLOSE_PROTOCOL_ERROR = 1002;
// // public final static short CLOSE_NOT_IMPL = 1003;
// // This is a generic status code that can be returned when there is no other
// // more suitable status code (e.g., 1003 or 1009)
// // public final static short CLOSE_VIOLATES_POLICY = 1008;
// public final static short CLOSE_MESG_BIG = 1009;
// // public final static short CLOSE_SEVER_ERROR = 1011;
//
// // private static byte[] bytes(short code) {
// // return ByteBuffer.allocate(2).putShort(code).array();
// // }
//
// // public static final CloseFrame NORMAL = new CloseFrame(bytes(CLOSE_NORMAL));
// // public static final CloseFrame AWAY = new CloseFrame(bytes(CLOSE_AWAY));
// // public static final CloseFrame MESG_BIG = new CloseFrame(bytes(CLOSE_MESG_BIG));
// // public static final CloseFrame SERVER_ERROR = new CloseFrame(bytes(CLOSE_MESG_BIG));
//
// public CloseFrame(byte[] data) {
// super(data);
// }
//
// public int getStatus() {
// if (data.length >= 2) {
// return ByteBuffer.wrap(data, 0, 2).getShort();
// }
// return CLOSE_NORMAL;
// }
// }
// Path: src/org/httpkit/server/HttpServer.java
import org.httpkit.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.HttpEncode;
import static org.httpkit.HttpUtils.WsEncode;
import static org.httpkit.server.Frame.CloseFrame.*;
atta.keepalive = request.isKeepAlive;
}
request.channel = channel;
request.remoteAddr = (InetSocketAddress) ch.socket().getRemoteSocketAddress();
handler.handle(request, new RespCallback(key, this));
// pipelining not supported : need queue to ensure order
atta.decoder.reset();
}
} while (buffer.hasRemaining()); // consume all
} catch (ProtocolException e) {
closeKey(key, -1);
} catch (RequestTooLargeException e) {
atta.keepalive = false;
tryWrite(key, HttpEncode(413, new HeaderMap(), e.getMessage()));
} catch (LineTooLargeException e) {
atta.keepalive = false; // close after write
tryWrite(key, HttpEncode(414, new HeaderMap(), e.getMessage()));
}
}
private void decodeWs(WsAtta atta, SelectionKey key) {
try {
do {
Frame frame = atta.decoder.decode(buffer);
if (frame instanceof TextFrame || frame instanceof BinaryFrame) {
handler.handle(atta.channel, frame);
atta.decoder.reset();
} else if (frame instanceof PingFrame) {
atta.decoder.reset();
tryWrite(key, WsEncode(WSDecoder.OPCODE_PONG, frame.data)); | } else if (frame instanceof CloseFrame) { |
nLight/jruby-http-kit | src/org/httpkit/client/RequestConfig.java | // Path: src/org/httpkit/HttpMethod.java
// public enum HttpMethod {
//
// GET(intern("get")), HEAD(intern("head")), POST(intern("post")), PUT(intern("put")),
// DELETE(intern("delete")), TRACE(intern("trace")), OPTIONS(intern("options")),
// CONNECT(intern("connect")), PATCH(intern("patch"));
//
// public final Keyword KEY;
//
// private HttpMethod(Keyword key) {
// this.KEY = key;
// }
//
// public static HttpMethod fromKeyword(Keyword k) {
// HttpMethod[] values = HttpMethod.values();
// for (HttpMethod m : values) {
// if (m.KEY.equals(k)) {
// return m;
// }
// }
// throw new RuntimeException("unsupported method " + k);
// }
// }
| import org.httpkit.HttpMethod;
import java.util.Map; | package org.httpkit.client;
public class RequestConfig {
public static String DEFAULT_USER_AGENT = "http-kit/2.0";
final int timeout;
final int keepAlive;
final Object body;
final Map<String, Object> headers; | // Path: src/org/httpkit/HttpMethod.java
// public enum HttpMethod {
//
// GET(intern("get")), HEAD(intern("head")), POST(intern("post")), PUT(intern("put")),
// DELETE(intern("delete")), TRACE(intern("trace")), OPTIONS(intern("options")),
// CONNECT(intern("connect")), PATCH(intern("patch"));
//
// public final Keyword KEY;
//
// private HttpMethod(Keyword key) {
// this.KEY = key;
// }
//
// public static HttpMethod fromKeyword(Keyword k) {
// HttpMethod[] values = HttpMethod.values();
// for (HttpMethod m : values) {
// if (m.KEY.equals(k)) {
// return m;
// }
// }
// throw new RuntimeException("unsupported method " + k);
// }
// }
// Path: src/org/httpkit/client/RequestConfig.java
import org.httpkit.HttpMethod;
import java.util.Map;
package org.httpkit.client;
public class RequestConfig {
public static String DEFAULT_USER_AGENT = "http-kit/2.0";
final int timeout;
final int keepAlive;
final Object body;
final Map<String, Object> headers; | final HttpMethod method; |
fodroid/XDroid-Databinding | app/src/main/java/cn/droidlover/xdroid/demo/ui/HomeFragment.java | // Path: library/src/main/java/cn/droidlover/xdroid/base/SimpleRecBindingViewHolder.java
// public class SimpleRecBindingViewHolder<V extends ViewDataBinding> extends RecyclerView.ViewHolder {
// private V binding;
//
// public SimpleRecBindingViewHolder(V binding) {
// super(binding.getRoot());
// this.binding = binding;
// }
//
// public SimpleRecBindingViewHolder(View itemView) {
// super(itemView);
// this.binding = DataBindingUtil.bind(itemView);
// }
//
// public V getBinding() {
// return binding;
// }
// }
//
// Path: app/src/main/java/cn/droidlover/xdroid/demo/adapter/HomeAdapter.java
// public class HomeAdapter extends SimpleRecAdapter<GankResults.Item, SimpleRecBindingViewHolder<AdapterHomeBinding>> {
//
// public static final int TAG_VIEW = 0;
//
// public HomeAdapter(Context context) {
// super(context);
// }
//
// @Override
// public SimpleRecBindingViewHolder newViewHolder(View itemView) {
// return new SimpleRecBindingViewHolder(itemView);
// }
//
// @Override
// public int getLayoutId() {
// return R.layout.adapter_home;
// }
//
// @Override
// public void onBindViewHolder(final SimpleRecBindingViewHolder<AdapterHomeBinding> holder, final int position) {
// final GankResults.Item item = data.get(position);
//
// String type = item.getType();
// switch (type) {
// case "休息视频":
// holder.getBinding().rlMessage.setVisibility(View.VISIBLE);
// holder.getBinding().ivPart.setVisibility(View.GONE);
// holder.getBinding().ivVedio.setVisibility(View.VISIBLE);
// holder.getBinding().tvItem.setText(item.getDesc());
// break;
// case "福利":
// holder.getBinding().rlMessage.setVisibility(View.GONE);
// holder.getBinding().ivPart.setVisibility(View.VISIBLE);
// holder.getBinding().ivVedio.setVisibility(View.GONE);
//
// ILFactory.getLoader().loadNet(holder.getBinding().ivPart, item.getUrl(), null);
// holder.getBinding().tvItem.setText("瞧瞧妹纸,扩展扩展视野......");
// break;
// default:
// holder.getBinding().rlMessage.setVisibility(View.VISIBLE);
// holder.getBinding().ivPart.setVisibility(View.GONE);
// holder.getBinding().ivVedio.setVisibility(View.GONE);
// holder.getBinding().tvItem.setText(item.getDesc());
// break;
// }
// Uri uri = null;
// switch (item.getType()) {
// case "Android":
// holder.getBinding().ivType.setImageResource(R.mipmap.android_icon);
// break;
// case "iOS":
// holder.getBinding().ivType.setImageResource(R.mipmap.ios_icon);
// break;
// case "前端":
// holder.getBinding().ivType.setImageResource(R.mipmap.js_icon);
// break;
// case "拓展资源":
// holder.getBinding().ivType.setImageResource(R.mipmap.other_icon);
// break;
// }
//
// String author = item.getWho();
// if (author != null) {
// holder.getBinding().tvAuthor.setText(author);
// holder.getBinding().tvAuthor.setTextColor(Color.parseColor("#87000000"));
// } else {
// holder.getBinding().tvAuthor.setText("");
// }
//
// holder.getBinding().tvTime.setText(item.getCreatedAt());
//
// holder.getBinding().tvType.setText(type);
//
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (getSimpleItemClick() != null) {
// getSimpleItemClick().onItemClick(position, item, TAG_VIEW, holder);
// }
// }
// });
//
// }
//
// }
| import cn.droidlover.xdroid.base.SimpleRecBindingViewHolder;
import cn.droidlover.xdroid.demo.adapter.HomeAdapter;
import cn.droidlover.xdroid.demo.databinding.AdapterHomeBinding;
import cn.droidlover.xdroid.demo.model.GankResults;
import cn.droidlover.xdroidbase.base.SimpleItemCallback;
import cn.droidlover.xdroidbase.base.SimpleRecAdapter;
import cn.droidlover.xrecyclerview.RecyclerItemCallback;
import cn.droidlover.xrecyclerview.XRecyclerView; | package cn.droidlover.xdroid.demo.ui;
/**
* Created by wanglei on 2016/12/10.
*/
public class HomeFragment extends BasePagerFragment {
HomeAdapter adapter;
@Override
public SimpleRecAdapter getAdapter() {
if (adapter == null) {
adapter = new HomeAdapter(context);
adapter.setItemClick(new SimpleItemCallback<GankResults.Item, | // Path: library/src/main/java/cn/droidlover/xdroid/base/SimpleRecBindingViewHolder.java
// public class SimpleRecBindingViewHolder<V extends ViewDataBinding> extends RecyclerView.ViewHolder {
// private V binding;
//
// public SimpleRecBindingViewHolder(V binding) {
// super(binding.getRoot());
// this.binding = binding;
// }
//
// public SimpleRecBindingViewHolder(View itemView) {
// super(itemView);
// this.binding = DataBindingUtil.bind(itemView);
// }
//
// public V getBinding() {
// return binding;
// }
// }
//
// Path: app/src/main/java/cn/droidlover/xdroid/demo/adapter/HomeAdapter.java
// public class HomeAdapter extends SimpleRecAdapter<GankResults.Item, SimpleRecBindingViewHolder<AdapterHomeBinding>> {
//
// public static final int TAG_VIEW = 0;
//
// public HomeAdapter(Context context) {
// super(context);
// }
//
// @Override
// public SimpleRecBindingViewHolder newViewHolder(View itemView) {
// return new SimpleRecBindingViewHolder(itemView);
// }
//
// @Override
// public int getLayoutId() {
// return R.layout.adapter_home;
// }
//
// @Override
// public void onBindViewHolder(final SimpleRecBindingViewHolder<AdapterHomeBinding> holder, final int position) {
// final GankResults.Item item = data.get(position);
//
// String type = item.getType();
// switch (type) {
// case "休息视频":
// holder.getBinding().rlMessage.setVisibility(View.VISIBLE);
// holder.getBinding().ivPart.setVisibility(View.GONE);
// holder.getBinding().ivVedio.setVisibility(View.VISIBLE);
// holder.getBinding().tvItem.setText(item.getDesc());
// break;
// case "福利":
// holder.getBinding().rlMessage.setVisibility(View.GONE);
// holder.getBinding().ivPart.setVisibility(View.VISIBLE);
// holder.getBinding().ivVedio.setVisibility(View.GONE);
//
// ILFactory.getLoader().loadNet(holder.getBinding().ivPart, item.getUrl(), null);
// holder.getBinding().tvItem.setText("瞧瞧妹纸,扩展扩展视野......");
// break;
// default:
// holder.getBinding().rlMessage.setVisibility(View.VISIBLE);
// holder.getBinding().ivPart.setVisibility(View.GONE);
// holder.getBinding().ivVedio.setVisibility(View.GONE);
// holder.getBinding().tvItem.setText(item.getDesc());
// break;
// }
// Uri uri = null;
// switch (item.getType()) {
// case "Android":
// holder.getBinding().ivType.setImageResource(R.mipmap.android_icon);
// break;
// case "iOS":
// holder.getBinding().ivType.setImageResource(R.mipmap.ios_icon);
// break;
// case "前端":
// holder.getBinding().ivType.setImageResource(R.mipmap.js_icon);
// break;
// case "拓展资源":
// holder.getBinding().ivType.setImageResource(R.mipmap.other_icon);
// break;
// }
//
// String author = item.getWho();
// if (author != null) {
// holder.getBinding().tvAuthor.setText(author);
// holder.getBinding().tvAuthor.setTextColor(Color.parseColor("#87000000"));
// } else {
// holder.getBinding().tvAuthor.setText("");
// }
//
// holder.getBinding().tvTime.setText(item.getCreatedAt());
//
// holder.getBinding().tvType.setText(type);
//
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (getSimpleItemClick() != null) {
// getSimpleItemClick().onItemClick(position, item, TAG_VIEW, holder);
// }
// }
// });
//
// }
//
// }
// Path: app/src/main/java/cn/droidlover/xdroid/demo/ui/HomeFragment.java
import cn.droidlover.xdroid.base.SimpleRecBindingViewHolder;
import cn.droidlover.xdroid.demo.adapter.HomeAdapter;
import cn.droidlover.xdroid.demo.databinding.AdapterHomeBinding;
import cn.droidlover.xdroid.demo.model.GankResults;
import cn.droidlover.xdroidbase.base.SimpleItemCallback;
import cn.droidlover.xdroidbase.base.SimpleRecAdapter;
import cn.droidlover.xrecyclerview.RecyclerItemCallback;
import cn.droidlover.xrecyclerview.XRecyclerView;
package cn.droidlover.xdroid.demo.ui;
/**
* Created by wanglei on 2016/12/10.
*/
public class HomeFragment extends BasePagerFragment {
HomeAdapter adapter;
@Override
public SimpleRecAdapter getAdapter() {
if (adapter == null) {
adapter = new HomeAdapter(context);
adapter.setItemClick(new SimpleItemCallback<GankResults.Item, | SimpleRecBindingViewHolder<AdapterHomeBinding>>() { |
fodroid/XDroid-Databinding | library/src/main/java/cn/droidlover/xdroid/net/converter/gson/GsonResponseBodyConverter.java | // Path: library/src/main/java/cn/droidlover/xdroid/net/exception/ResultErrorException.java
// public class ResultErrorException extends IOException {
//
// /**
// * 网络错误
// */
// public static final int CODE_HTTP_ERROR = -100;
// /**
// * 数据解析失败
// */
// public static final int CODE_PARSE_ERROR = -101;
// /**
// * 网络连接错误
// */
// public static final int CODE_CONNECT_ERROR = -102;
//
//
// public int code;
// public String msg;
//
// public ResultErrorException() {
//
// }
//
// public ResultErrorException(int code, String msg) {
// this.code = code;
// this.msg = msg;
// }
//
// public ResultErrorException(String msg) {
// this.msg = msg;
// }
// }
//
// Path: library/src/main/java/cn/droidlover/xdroid/net/model/SimpleModel.java
// public interface SimpleModel {
//
// /**
// * 数据是否有效
// *
// * @return true 有效
// */
// boolean isValid();
//
// /**
// * 获取结果码
// *
// * @return
// */
// int getResultCode();
//
// /**
// * 获取结果信息
// *
// * @return
// */
// String getResultMsg();
// }
| import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import cn.droidlover.xdroid.net.exception.ResultErrorException;
import cn.droidlover.xdroid.net.model.SimpleModel;
import okhttp3.ResponseBody;
import retrofit2.Converter; | package cn.droidlover.xdroid.net.converter.gson;
final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public T convert(ResponseBody value) throws IOException {
JsonReader jsonReader = gson.newJsonReader(value.charStream());
try {
T t = adapter.read(jsonReader); | // Path: library/src/main/java/cn/droidlover/xdroid/net/exception/ResultErrorException.java
// public class ResultErrorException extends IOException {
//
// /**
// * 网络错误
// */
// public static final int CODE_HTTP_ERROR = -100;
// /**
// * 数据解析失败
// */
// public static final int CODE_PARSE_ERROR = -101;
// /**
// * 网络连接错误
// */
// public static final int CODE_CONNECT_ERROR = -102;
//
//
// public int code;
// public String msg;
//
// public ResultErrorException() {
//
// }
//
// public ResultErrorException(int code, String msg) {
// this.code = code;
// this.msg = msg;
// }
//
// public ResultErrorException(String msg) {
// this.msg = msg;
// }
// }
//
// Path: library/src/main/java/cn/droidlover/xdroid/net/model/SimpleModel.java
// public interface SimpleModel {
//
// /**
// * 数据是否有效
// *
// * @return true 有效
// */
// boolean isValid();
//
// /**
// * 获取结果码
// *
// * @return
// */
// int getResultCode();
//
// /**
// * 获取结果信息
// *
// * @return
// */
// String getResultMsg();
// }
// Path: library/src/main/java/cn/droidlover/xdroid/net/converter/gson/GsonResponseBodyConverter.java
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import cn.droidlover.xdroid.net.exception.ResultErrorException;
import cn.droidlover.xdroid.net.model.SimpleModel;
import okhttp3.ResponseBody;
import retrofit2.Converter;
package cn.droidlover.xdroid.net.converter.gson;
final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public T convert(ResponseBody value) throws IOException {
JsonReader jsonReader = gson.newJsonReader(value.charStream());
try {
T t = adapter.read(jsonReader); | if (t instanceof SimpleModel && !((SimpleModel) t).isValid()) { |
fodroid/XDroid-Databinding | library/src/main/java/cn/droidlover/xdroid/net/converter/gson/GsonResponseBodyConverter.java | // Path: library/src/main/java/cn/droidlover/xdroid/net/exception/ResultErrorException.java
// public class ResultErrorException extends IOException {
//
// /**
// * 网络错误
// */
// public static final int CODE_HTTP_ERROR = -100;
// /**
// * 数据解析失败
// */
// public static final int CODE_PARSE_ERROR = -101;
// /**
// * 网络连接错误
// */
// public static final int CODE_CONNECT_ERROR = -102;
//
//
// public int code;
// public String msg;
//
// public ResultErrorException() {
//
// }
//
// public ResultErrorException(int code, String msg) {
// this.code = code;
// this.msg = msg;
// }
//
// public ResultErrorException(String msg) {
// this.msg = msg;
// }
// }
//
// Path: library/src/main/java/cn/droidlover/xdroid/net/model/SimpleModel.java
// public interface SimpleModel {
//
// /**
// * 数据是否有效
// *
// * @return true 有效
// */
// boolean isValid();
//
// /**
// * 获取结果码
// *
// * @return
// */
// int getResultCode();
//
// /**
// * 获取结果信息
// *
// * @return
// */
// String getResultMsg();
// }
| import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import cn.droidlover.xdroid.net.exception.ResultErrorException;
import cn.droidlover.xdroid.net.model.SimpleModel;
import okhttp3.ResponseBody;
import retrofit2.Converter; | package cn.droidlover.xdroid.net.converter.gson;
final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public T convert(ResponseBody value) throws IOException {
JsonReader jsonReader = gson.newJsonReader(value.charStream());
try {
T t = adapter.read(jsonReader);
if (t instanceof SimpleModel && !((SimpleModel) t).isValid()) { | // Path: library/src/main/java/cn/droidlover/xdroid/net/exception/ResultErrorException.java
// public class ResultErrorException extends IOException {
//
// /**
// * 网络错误
// */
// public static final int CODE_HTTP_ERROR = -100;
// /**
// * 数据解析失败
// */
// public static final int CODE_PARSE_ERROR = -101;
// /**
// * 网络连接错误
// */
// public static final int CODE_CONNECT_ERROR = -102;
//
//
// public int code;
// public String msg;
//
// public ResultErrorException() {
//
// }
//
// public ResultErrorException(int code, String msg) {
// this.code = code;
// this.msg = msg;
// }
//
// public ResultErrorException(String msg) {
// this.msg = msg;
// }
// }
//
// Path: library/src/main/java/cn/droidlover/xdroid/net/model/SimpleModel.java
// public interface SimpleModel {
//
// /**
// * 数据是否有效
// *
// * @return true 有效
// */
// boolean isValid();
//
// /**
// * 获取结果码
// *
// * @return
// */
// int getResultCode();
//
// /**
// * 获取结果信息
// *
// * @return
// */
// String getResultMsg();
// }
// Path: library/src/main/java/cn/droidlover/xdroid/net/converter/gson/GsonResponseBodyConverter.java
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import cn.droidlover.xdroid.net.exception.ResultErrorException;
import cn.droidlover.xdroid.net.model.SimpleModel;
import okhttp3.ResponseBody;
import retrofit2.Converter;
package cn.droidlover.xdroid.net.converter.gson;
final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public T convert(ResponseBody value) throws IOException {
JsonReader jsonReader = gson.newJsonReader(value.charStream());
try {
T t = adapter.read(jsonReader);
if (t instanceof SimpleModel && !((SimpleModel) t).isValid()) { | throw new ResultErrorException(((SimpleModel) t).getResultCode(), ((SimpleModel) t).getResultMsg()); |
fodroid/XDroid-Databinding | app/src/main/java/cn/droidlover/xdroid/demo/ui/GirlFragment.java | // Path: library/src/main/java/cn/droidlover/xdroid/base/SimpleRecBindingViewHolder.java
// public class SimpleRecBindingViewHolder<V extends ViewDataBinding> extends RecyclerView.ViewHolder {
// private V binding;
//
// public SimpleRecBindingViewHolder(V binding) {
// super(binding.getRoot());
// this.binding = binding;
// }
//
// public SimpleRecBindingViewHolder(View itemView) {
// super(itemView);
// this.binding = DataBindingUtil.bind(itemView);
// }
//
// public V getBinding() {
// return binding;
// }
// }
//
// Path: app/src/main/java/cn/droidlover/xdroid/demo/adapter/GirlAdapter.java
// public class GirlAdapter extends SimpleRecAdapter<GankResults.Item, SimpleRecBindingViewHolder<AdapterGirlBinding>> {
//
//
// public GirlAdapter(Context context) {
// super(context);
// }
//
// @Override
// public SimpleRecBindingViewHolder newViewHolder(View itemView) {
// return new SimpleRecBindingViewHolder(itemView);
// }
//
// @Override
// public int getLayoutId() {
// return R.layout.adapter_girl;
// }
//
// @Override
// public void onBindViewHolder(SimpleRecBindingViewHolder<AdapterGirlBinding> holder, int position) {
// GankResults.Item item = data.get(position);
// ILFactory.getLoader().loadNet(holder.getBinding().ivGirl, item.getUrl(), null);
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (getSimpleItemClick() != null) {
//
// }
// }
// });
// }
//
// }
| import cn.droidlover.xdroid.base.SimpleRecBindingViewHolder;
import cn.droidlover.xdroid.demo.adapter.GirlAdapter;
import cn.droidlover.xdroid.demo.databinding.AdapterGirlBinding;
import cn.droidlover.xdroid.demo.model.GankResults;
import cn.droidlover.xdroidbase.base.SimpleItemCallback;
import cn.droidlover.xdroidbase.base.SimpleRecAdapter;
import cn.droidlover.xrecyclerview.RecyclerItemCallback;
import cn.droidlover.xrecyclerview.XRecyclerView; | package cn.droidlover.xdroid.demo.ui;
/**
* Created by wanglei on 2016/12/10.
*/
public class GirlFragment extends BasePagerFragment {
GirlAdapter adapter;
@Override
public SimpleRecAdapter getAdapter() {
if (adapter == null) {
adapter = new GirlAdapter(context);
adapter.setItemClick(new SimpleItemCallback<GankResults.Item, | // Path: library/src/main/java/cn/droidlover/xdroid/base/SimpleRecBindingViewHolder.java
// public class SimpleRecBindingViewHolder<V extends ViewDataBinding> extends RecyclerView.ViewHolder {
// private V binding;
//
// public SimpleRecBindingViewHolder(V binding) {
// super(binding.getRoot());
// this.binding = binding;
// }
//
// public SimpleRecBindingViewHolder(View itemView) {
// super(itemView);
// this.binding = DataBindingUtil.bind(itemView);
// }
//
// public V getBinding() {
// return binding;
// }
// }
//
// Path: app/src/main/java/cn/droidlover/xdroid/demo/adapter/GirlAdapter.java
// public class GirlAdapter extends SimpleRecAdapter<GankResults.Item, SimpleRecBindingViewHolder<AdapterGirlBinding>> {
//
//
// public GirlAdapter(Context context) {
// super(context);
// }
//
// @Override
// public SimpleRecBindingViewHolder newViewHolder(View itemView) {
// return new SimpleRecBindingViewHolder(itemView);
// }
//
// @Override
// public int getLayoutId() {
// return R.layout.adapter_girl;
// }
//
// @Override
// public void onBindViewHolder(SimpleRecBindingViewHolder<AdapterGirlBinding> holder, int position) {
// GankResults.Item item = data.get(position);
// ILFactory.getLoader().loadNet(holder.getBinding().ivGirl, item.getUrl(), null);
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (getSimpleItemClick() != null) {
//
// }
// }
// });
// }
//
// }
// Path: app/src/main/java/cn/droidlover/xdroid/demo/ui/GirlFragment.java
import cn.droidlover.xdroid.base.SimpleRecBindingViewHolder;
import cn.droidlover.xdroid.demo.adapter.GirlAdapter;
import cn.droidlover.xdroid.demo.databinding.AdapterGirlBinding;
import cn.droidlover.xdroid.demo.model.GankResults;
import cn.droidlover.xdroidbase.base.SimpleItemCallback;
import cn.droidlover.xdroidbase.base.SimpleRecAdapter;
import cn.droidlover.xrecyclerview.RecyclerItemCallback;
import cn.droidlover.xrecyclerview.XRecyclerView;
package cn.droidlover.xdroid.demo.ui;
/**
* Created by wanglei on 2016/12/10.
*/
public class GirlFragment extends BasePagerFragment {
GirlAdapter adapter;
@Override
public SimpleRecAdapter getAdapter() {
if (adapter == null) {
adapter = new GirlAdapter(context);
adapter.setItemClick(new SimpleItemCallback<GankResults.Item, | SimpleRecBindingViewHolder<AdapterGirlBinding>>() { |
ndimiduk/orderly | orderly-examples/src/main/java/orderly/example/DoubleExample.java | // Path: orderly-core/src/main/java/orderly/DoubleRowKey.java
// public class DoubleRowKey extends DoubleWritableRowKey
// {
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return Double.class; }
//
// protected Object toDoubleWritable(Object o) {
// if (o == null || o instanceof DoubleWritable)
// return o;
// if (dw == null)
// dw = new DoubleWritable();
// dw.set((Double)o);
// return dw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toDoubleWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toDoubleWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// DoubleWritable dw = (DoubleWritable) super.deserialize(w);
// if (dw == null)
// return dw;
//
// return Double.valueOf(dw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/DoubleWritableRowKey.java
// public class DoubleWritableRowKey extends RowKey
// {
// private static final long NULL = 0;
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return DoubleWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// if (o == null && !terminate())
// return 0;
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
// long l;
//
// if (o == null) {
// if (!terminate())
// return;
// l = NULL;
// } else {
// l = Double.doubleToLongBits(((DoubleWritable)o).get());
// l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1;
// }
//
// Bytes.putLong(b, offset, l ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// if (w.getLength() <= 0)
// return;
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// byte[] s = w.get();
// int offset = w.getOffset();
// if (w.getLength() <= 0)
// return null;
//
// try {
// long l = Bytes.toLong(s, offset) ^ order.mask();
// if (l == NULL)
// return null;
//
// if (dw == null)
// dw = new DoubleWritable();
//
// l--;
// l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE;
// dw.set(Double.longBitsToDouble(l));
// return dw;
// } finally {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
| import orderly.DoubleRowKey;
import orderly.DoubleWritableRowKey;
import orderly.Order;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable; | /* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class DoubleExample
{
/* Simple examples showing serialization lengths with Double Row Key */
public void lengthExamples() throws Exception { | // Path: orderly-core/src/main/java/orderly/DoubleRowKey.java
// public class DoubleRowKey extends DoubleWritableRowKey
// {
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return Double.class; }
//
// protected Object toDoubleWritable(Object o) {
// if (o == null || o instanceof DoubleWritable)
// return o;
// if (dw == null)
// dw = new DoubleWritable();
// dw.set((Double)o);
// return dw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toDoubleWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toDoubleWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// DoubleWritable dw = (DoubleWritable) super.deserialize(w);
// if (dw == null)
// return dw;
//
// return Double.valueOf(dw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/DoubleWritableRowKey.java
// public class DoubleWritableRowKey extends RowKey
// {
// private static final long NULL = 0;
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return DoubleWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// if (o == null && !terminate())
// return 0;
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
// long l;
//
// if (o == null) {
// if (!terminate())
// return;
// l = NULL;
// } else {
// l = Double.doubleToLongBits(((DoubleWritable)o).get());
// l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1;
// }
//
// Bytes.putLong(b, offset, l ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// if (w.getLength() <= 0)
// return;
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// byte[] s = w.get();
// int offset = w.getOffset();
// if (w.getLength() <= 0)
// return null;
//
// try {
// long l = Bytes.toLong(s, offset) ^ order.mask();
// if (l == NULL)
// return null;
//
// if (dw == null)
// dw = new DoubleWritable();
//
// l--;
// l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE;
// dw.set(Double.longBitsToDouble(l));
// return dw;
// } finally {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
// Path: orderly-examples/src/main/java/orderly/example/DoubleExample.java
import orderly.DoubleRowKey;
import orderly.DoubleWritableRowKey;
import orderly.Order;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class DoubleExample
{
/* Simple examples showing serialization lengths with Double Row Key */
public void lengthExamples() throws Exception { | DoubleRowKey d = new DoubleRowKey(); |
ndimiduk/orderly | orderly-examples/src/main/java/orderly/example/DoubleExample.java | // Path: orderly-core/src/main/java/orderly/DoubleRowKey.java
// public class DoubleRowKey extends DoubleWritableRowKey
// {
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return Double.class; }
//
// protected Object toDoubleWritable(Object o) {
// if (o == null || o instanceof DoubleWritable)
// return o;
// if (dw == null)
// dw = new DoubleWritable();
// dw.set((Double)o);
// return dw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toDoubleWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toDoubleWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// DoubleWritable dw = (DoubleWritable) super.deserialize(w);
// if (dw == null)
// return dw;
//
// return Double.valueOf(dw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/DoubleWritableRowKey.java
// public class DoubleWritableRowKey extends RowKey
// {
// private static final long NULL = 0;
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return DoubleWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// if (o == null && !terminate())
// return 0;
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
// long l;
//
// if (o == null) {
// if (!terminate())
// return;
// l = NULL;
// } else {
// l = Double.doubleToLongBits(((DoubleWritable)o).get());
// l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1;
// }
//
// Bytes.putLong(b, offset, l ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// if (w.getLength() <= 0)
// return;
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// byte[] s = w.get();
// int offset = w.getOffset();
// if (w.getLength() <= 0)
// return null;
//
// try {
// long l = Bytes.toLong(s, offset) ^ order.mask();
// if (l == NULL)
// return null;
//
// if (dw == null)
// dw = new DoubleWritable();
//
// l--;
// l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE;
// dw.set(Double.longBitsToDouble(l));
// return dw;
// } finally {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
| import orderly.DoubleRowKey;
import orderly.DoubleWritableRowKey;
import orderly.Order;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable; | /* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class DoubleExample
{
/* Simple examples showing serialization lengths with Double Row Key */
public void lengthExamples() throws Exception {
DoubleRowKey d = new DoubleRowKey();
System.out.println("serialize(null) length - " + d.serialize(null).length);
System.out.println("serialize(57.190235) length - " +
d.serialize(57.923924).length);
System.out.println("serialize(1000000.999) length - " +
d.serialize(1000000.99).length);
| // Path: orderly-core/src/main/java/orderly/DoubleRowKey.java
// public class DoubleRowKey extends DoubleWritableRowKey
// {
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return Double.class; }
//
// protected Object toDoubleWritable(Object o) {
// if (o == null || o instanceof DoubleWritable)
// return o;
// if (dw == null)
// dw = new DoubleWritable();
// dw.set((Double)o);
// return dw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toDoubleWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toDoubleWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// DoubleWritable dw = (DoubleWritable) super.deserialize(w);
// if (dw == null)
// return dw;
//
// return Double.valueOf(dw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/DoubleWritableRowKey.java
// public class DoubleWritableRowKey extends RowKey
// {
// private static final long NULL = 0;
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return DoubleWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// if (o == null && !terminate())
// return 0;
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
// long l;
//
// if (o == null) {
// if (!terminate())
// return;
// l = NULL;
// } else {
// l = Double.doubleToLongBits(((DoubleWritable)o).get());
// l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1;
// }
//
// Bytes.putLong(b, offset, l ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// if (w.getLength() <= 0)
// return;
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// byte[] s = w.get();
// int offset = w.getOffset();
// if (w.getLength() <= 0)
// return null;
//
// try {
// long l = Bytes.toLong(s, offset) ^ order.mask();
// if (l == NULL)
// return null;
//
// if (dw == null)
// dw = new DoubleWritable();
//
// l--;
// l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE;
// dw.set(Double.longBitsToDouble(l));
// return dw;
// } finally {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
// Path: orderly-examples/src/main/java/orderly/example/DoubleExample.java
import orderly.DoubleRowKey;
import orderly.DoubleWritableRowKey;
import orderly.Order;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class DoubleExample
{
/* Simple examples showing serialization lengths with Double Row Key */
public void lengthExamples() throws Exception {
DoubleRowKey d = new DoubleRowKey();
System.out.println("serialize(null) length - " + d.serialize(null).length);
System.out.println("serialize(57.190235) length - " +
d.serialize(57.923924).length);
System.out.println("serialize(1000000.999) length - " +
d.serialize(1000000.99).length);
| d.setOrder(Order.DESCENDING); |
ndimiduk/orderly | orderly-examples/src/main/java/orderly/example/DoubleExample.java | // Path: orderly-core/src/main/java/orderly/DoubleRowKey.java
// public class DoubleRowKey extends DoubleWritableRowKey
// {
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return Double.class; }
//
// protected Object toDoubleWritable(Object o) {
// if (o == null || o instanceof DoubleWritable)
// return o;
// if (dw == null)
// dw = new DoubleWritable();
// dw.set((Double)o);
// return dw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toDoubleWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toDoubleWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// DoubleWritable dw = (DoubleWritable) super.deserialize(w);
// if (dw == null)
// return dw;
//
// return Double.valueOf(dw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/DoubleWritableRowKey.java
// public class DoubleWritableRowKey extends RowKey
// {
// private static final long NULL = 0;
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return DoubleWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// if (o == null && !terminate())
// return 0;
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
// long l;
//
// if (o == null) {
// if (!terminate())
// return;
// l = NULL;
// } else {
// l = Double.doubleToLongBits(((DoubleWritable)o).get());
// l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1;
// }
//
// Bytes.putLong(b, offset, l ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// if (w.getLength() <= 0)
// return;
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// byte[] s = w.get();
// int offset = w.getOffset();
// if (w.getLength() <= 0)
// return null;
//
// try {
// long l = Bytes.toLong(s, offset) ^ order.mask();
// if (l == NULL)
// return null;
//
// if (dw == null)
// dw = new DoubleWritable();
//
// l--;
// l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE;
// dw.set(Double.longBitsToDouble(l));
// return dw;
// } finally {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
| import orderly.DoubleRowKey;
import orderly.DoubleWritableRowKey;
import orderly.Order;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable; | /* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class DoubleExample
{
/* Simple examples showing serialization lengths with Double Row Key */
public void lengthExamples() throws Exception {
DoubleRowKey d = new DoubleRowKey();
System.out.println("serialize(null) length - " + d.serialize(null).length);
System.out.println("serialize(57.190235) length - " +
d.serialize(57.923924).length);
System.out.println("serialize(1000000.999) length - " +
d.serialize(1000000.99).length);
d.setOrder(Order.DESCENDING);
System.out.println("descending serialize (null) - length " +
d.serialize(null).length);
System.out.println("descending serialize (57) - length " +
d.serialize(57d).length);
}
/* Simple examples showing serialization tests with DoubleWritable Row Key */
public void serializationExamples() throws Exception { | // Path: orderly-core/src/main/java/orderly/DoubleRowKey.java
// public class DoubleRowKey extends DoubleWritableRowKey
// {
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return Double.class; }
//
// protected Object toDoubleWritable(Object o) {
// if (o == null || o instanceof DoubleWritable)
// return o;
// if (dw == null)
// dw = new DoubleWritable();
// dw.set((Double)o);
// return dw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toDoubleWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toDoubleWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// DoubleWritable dw = (DoubleWritable) super.deserialize(w);
// if (dw == null)
// return dw;
//
// return Double.valueOf(dw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/DoubleWritableRowKey.java
// public class DoubleWritableRowKey extends RowKey
// {
// private static final long NULL = 0;
// private DoubleWritable dw;
//
// @Override
// public Class<?> getSerializedClass() { return DoubleWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// if (o == null && !terminate())
// return 0;
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
// long l;
//
// if (o == null) {
// if (!terminate())
// return;
// l = NULL;
// } else {
// l = Double.doubleToLongBits(((DoubleWritable)o).get());
// l = (l ^ ((l >> Long.SIZE - 1) | Long.MIN_VALUE)) + 1;
// }
//
// Bytes.putLong(b, offset, l ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// if (w.getLength() <= 0)
// return;
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// byte[] s = w.get();
// int offset = w.getOffset();
// if (w.getLength() <= 0)
// return null;
//
// try {
// long l = Bytes.toLong(s, offset) ^ order.mask();
// if (l == NULL)
// return null;
//
// if (dw == null)
// dw = new DoubleWritable();
//
// l--;
// l ^= (~l >> Long.SIZE - 1) | Long.MIN_VALUE;
// dw.set(Double.longBitsToDouble(l));
// return dw;
// } finally {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
// Path: orderly-examples/src/main/java/orderly/example/DoubleExample.java
import orderly.DoubleRowKey;
import orderly.DoubleWritableRowKey;
import orderly.Order;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class DoubleExample
{
/* Simple examples showing serialization lengths with Double Row Key */
public void lengthExamples() throws Exception {
DoubleRowKey d = new DoubleRowKey();
System.out.println("serialize(null) length - " + d.serialize(null).length);
System.out.println("serialize(57.190235) length - " +
d.serialize(57.923924).length);
System.out.println("serialize(1000000.999) length - " +
d.serialize(1000000.99).length);
d.setOrder(Order.DESCENDING);
System.out.println("descending serialize (null) - length " +
d.serialize(null).length);
System.out.println("descending serialize (57) - length " +
d.serialize(57d).length);
}
/* Simple examples showing serialization tests with DoubleWritable Row Key */
public void serializationExamples() throws Exception { | DoubleWritableRowKey d = new DoubleWritableRowKey(); |
ndimiduk/orderly | orderly-examples/src/main/java/orderly/example/FixedLongExample.java | // Path: orderly-core/src/main/java/orderly/FixedLongWritableRowKey.java
// public class FixedLongWritableRowKey extends RowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return LongWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
//
// long l = ((LongWritable)o).get();
// Bytes.putLong(b, offset, l ^ Long.MIN_VALUE ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// int offset = w.getOffset();
// byte[] s = w.get();
//
// long l = Bytes.toLong(s, offset) ^ Long.MIN_VALUE ^ order.mask();
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
//
// if (lw == null)
// lw = new LongWritable();
// lw.set(l);
// return lw;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/FixedUnsignedLongRowKey.java
// public class FixedUnsignedLongRowKey extends FixedUnsignedLongWritableRowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return Long.class; }
//
// protected Object toLongWritable(Object o) {
// if (o == null || o instanceof LongWritable)
// return o;
// if (lw == null)
// lw = new LongWritable();
// lw.set((Long)o);
// return lw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toLongWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toLongWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// LongWritable lw = (LongWritable) super.deserialize(w);
// if (lw == null)
// return lw;
//
// return Long.valueOf(lw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
| import orderly.FixedLongWritableRowKey;
import orderly.FixedUnsignedLongRowKey;
import orderly.Order;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable; | /* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class FixedLongExample
{
/* Simple examples showing serialization lengths with
* FixedUnsignedLongRow Key
*/
public void lengthExamples() throws Exception { | // Path: orderly-core/src/main/java/orderly/FixedLongWritableRowKey.java
// public class FixedLongWritableRowKey extends RowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return LongWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
//
// long l = ((LongWritable)o).get();
// Bytes.putLong(b, offset, l ^ Long.MIN_VALUE ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// int offset = w.getOffset();
// byte[] s = w.get();
//
// long l = Bytes.toLong(s, offset) ^ Long.MIN_VALUE ^ order.mask();
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
//
// if (lw == null)
// lw = new LongWritable();
// lw.set(l);
// return lw;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/FixedUnsignedLongRowKey.java
// public class FixedUnsignedLongRowKey extends FixedUnsignedLongWritableRowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return Long.class; }
//
// protected Object toLongWritable(Object o) {
// if (o == null || o instanceof LongWritable)
// return o;
// if (lw == null)
// lw = new LongWritable();
// lw.set((Long)o);
// return lw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toLongWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toLongWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// LongWritable lw = (LongWritable) super.deserialize(w);
// if (lw == null)
// return lw;
//
// return Long.valueOf(lw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
// Path: orderly-examples/src/main/java/orderly/example/FixedLongExample.java
import orderly.FixedLongWritableRowKey;
import orderly.FixedUnsignedLongRowKey;
import orderly.Order;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class FixedLongExample
{
/* Simple examples showing serialization lengths with
* FixedUnsignedLongRow Key
*/
public void lengthExamples() throws Exception { | FixedUnsignedLongRowKey i = new FixedUnsignedLongRowKey(); |
ndimiduk/orderly | orderly-examples/src/main/java/orderly/example/FixedLongExample.java | // Path: orderly-core/src/main/java/orderly/FixedLongWritableRowKey.java
// public class FixedLongWritableRowKey extends RowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return LongWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
//
// long l = ((LongWritable)o).get();
// Bytes.putLong(b, offset, l ^ Long.MIN_VALUE ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// int offset = w.getOffset();
// byte[] s = w.get();
//
// long l = Bytes.toLong(s, offset) ^ Long.MIN_VALUE ^ order.mask();
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
//
// if (lw == null)
// lw = new LongWritable();
// lw.set(l);
// return lw;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/FixedUnsignedLongRowKey.java
// public class FixedUnsignedLongRowKey extends FixedUnsignedLongWritableRowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return Long.class; }
//
// protected Object toLongWritable(Object o) {
// if (o == null || o instanceof LongWritable)
// return o;
// if (lw == null)
// lw = new LongWritable();
// lw.set((Long)o);
// return lw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toLongWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toLongWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// LongWritable lw = (LongWritable) super.deserialize(w);
// if (lw == null)
// return lw;
//
// return Long.valueOf(lw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
| import orderly.FixedLongWritableRowKey;
import orderly.FixedUnsignedLongRowKey;
import orderly.Order;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable; | /* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class FixedLongExample
{
/* Simple examples showing serialization lengths with
* FixedUnsignedLongRow Key
*/
public void lengthExamples() throws Exception {
FixedUnsignedLongRowKey i = new FixedUnsignedLongRowKey();
System.out.println("serialize(2^63) length - " +
i.serialize(Long.MIN_VALUE).length);
System.out.println("serialize(57) length - " + i.serialize(57l).length);
System.out.println("serialize(293) length - " + i.serialize(293l).length);
| // Path: orderly-core/src/main/java/orderly/FixedLongWritableRowKey.java
// public class FixedLongWritableRowKey extends RowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return LongWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
//
// long l = ((LongWritable)o).get();
// Bytes.putLong(b, offset, l ^ Long.MIN_VALUE ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// int offset = w.getOffset();
// byte[] s = w.get();
//
// long l = Bytes.toLong(s, offset) ^ Long.MIN_VALUE ^ order.mask();
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
//
// if (lw == null)
// lw = new LongWritable();
// lw.set(l);
// return lw;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/FixedUnsignedLongRowKey.java
// public class FixedUnsignedLongRowKey extends FixedUnsignedLongWritableRowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return Long.class; }
//
// protected Object toLongWritable(Object o) {
// if (o == null || o instanceof LongWritable)
// return o;
// if (lw == null)
// lw = new LongWritable();
// lw.set((Long)o);
// return lw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toLongWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toLongWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// LongWritable lw = (LongWritable) super.deserialize(w);
// if (lw == null)
// return lw;
//
// return Long.valueOf(lw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
// Path: orderly-examples/src/main/java/orderly/example/FixedLongExample.java
import orderly.FixedLongWritableRowKey;
import orderly.FixedUnsignedLongRowKey;
import orderly.Order;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class FixedLongExample
{
/* Simple examples showing serialization lengths with
* FixedUnsignedLongRow Key
*/
public void lengthExamples() throws Exception {
FixedUnsignedLongRowKey i = new FixedUnsignedLongRowKey();
System.out.println("serialize(2^63) length - " +
i.serialize(Long.MIN_VALUE).length);
System.out.println("serialize(57) length - " + i.serialize(57l).length);
System.out.println("serialize(293) length - " + i.serialize(293l).length);
| i.setOrder(Order.DESCENDING); |
ndimiduk/orderly | orderly-examples/src/main/java/orderly/example/FixedLongExample.java | // Path: orderly-core/src/main/java/orderly/FixedLongWritableRowKey.java
// public class FixedLongWritableRowKey extends RowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return LongWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
//
// long l = ((LongWritable)o).get();
// Bytes.putLong(b, offset, l ^ Long.MIN_VALUE ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// int offset = w.getOffset();
// byte[] s = w.get();
//
// long l = Bytes.toLong(s, offset) ^ Long.MIN_VALUE ^ order.mask();
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
//
// if (lw == null)
// lw = new LongWritable();
// lw.set(l);
// return lw;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/FixedUnsignedLongRowKey.java
// public class FixedUnsignedLongRowKey extends FixedUnsignedLongWritableRowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return Long.class; }
//
// protected Object toLongWritable(Object o) {
// if (o == null || o instanceof LongWritable)
// return o;
// if (lw == null)
// lw = new LongWritable();
// lw.set((Long)o);
// return lw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toLongWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toLongWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// LongWritable lw = (LongWritable) super.deserialize(w);
// if (lw == null)
// return lw;
//
// return Long.valueOf(lw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
| import orderly.FixedLongWritableRowKey;
import orderly.FixedUnsignedLongRowKey;
import orderly.Order;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable; | /* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class FixedLongExample
{
/* Simple examples showing serialization lengths with
* FixedUnsignedLongRow Key
*/
public void lengthExamples() throws Exception {
FixedUnsignedLongRowKey i = new FixedUnsignedLongRowKey();
System.out.println("serialize(2^63) length - " +
i.serialize(Long.MIN_VALUE).length);
System.out.println("serialize(57) length - " + i.serialize(57l).length);
System.out.println("serialize(293) length - " + i.serialize(293l).length);
i.setOrder(Order.DESCENDING);
System.out.println("descending serialize (57) - length " +
i.serialize(57l).length);
System.out.println("descending serialize (2^32) - length " +
i.serialize(1l << 32).length);
}
/* Simple examples showing serialization tests with FixedLongWritable */
public void serializationExamples() throws Exception { | // Path: orderly-core/src/main/java/orderly/FixedLongWritableRowKey.java
// public class FixedLongWritableRowKey extends RowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return LongWritable.class; }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return Bytes.SIZEOF_LONG;
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w)
// throws IOException
// {
// byte[] b = w.get();
// int offset = w.getOffset();
//
// long l = ((LongWritable)o).get();
// Bytes.putLong(b, offset, l ^ Long.MIN_VALUE ^ order.mask());
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public void skip(ImmutableBytesWritable w) throws IOException {
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// int offset = w.getOffset();
// byte[] s = w.get();
//
// long l = Bytes.toLong(s, offset) ^ Long.MIN_VALUE ^ order.mask();
// RowKeyUtils.seek(w, Bytes.SIZEOF_LONG);
//
// if (lw == null)
// lw = new LongWritable();
// lw.set(l);
// return lw;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/FixedUnsignedLongRowKey.java
// public class FixedUnsignedLongRowKey extends FixedUnsignedLongWritableRowKey
// {
// private LongWritable lw;
//
// @Override
// public Class<?> getSerializedClass() { return Long.class; }
//
// protected Object toLongWritable(Object o) {
// if (o == null || o instanceof LongWritable)
// return o;
// if (lw == null)
// lw = new LongWritable();
// lw.set((Long)o);
// return lw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toLongWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toLongWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// LongWritable lw = (LongWritable) super.deserialize(w);
// if (lw == null)
// return lw;
//
// return Long.valueOf(lw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
// Path: orderly-examples/src/main/java/orderly/example/FixedLongExample.java
import orderly.FixedLongWritableRowKey;
import orderly.FixedUnsignedLongRowKey;
import orderly.Order;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class FixedLongExample
{
/* Simple examples showing serialization lengths with
* FixedUnsignedLongRow Key
*/
public void lengthExamples() throws Exception {
FixedUnsignedLongRowKey i = new FixedUnsignedLongRowKey();
System.out.println("serialize(2^63) length - " +
i.serialize(Long.MIN_VALUE).length);
System.out.println("serialize(57) length - " + i.serialize(57l).length);
System.out.println("serialize(293) length - " + i.serialize(293l).length);
i.setOrder(Order.DESCENDING);
System.out.println("descending serialize (57) - length " +
i.serialize(57l).length);
System.out.println("descending serialize (2^32) - length " +
i.serialize(1l << 32).length);
}
/* Simple examples showing serialization tests with FixedLongWritable */
public void serializationExamples() throws Exception { | FixedLongWritableRowKey l = new FixedLongWritableRowKey(); |
ndimiduk/orderly | orderly-examples/src/main/java/orderly/example/IntExample.java | // Path: orderly-core/src/main/java/orderly/IntWritableRowKey.java
// public class IntWritableRowKey extends AbstractVarIntRowKey
// {
// /** Header flags */
// protected static final byte INT_SIGN = (byte) 0x80;
// protected static final byte INT_SINGLE = (byte) 0x40;
// protected static final byte INT_DOUBLE = (byte) 0x20;
//
// /** Header data bits for each header type */
// protected static final int INT_SINGLE_DATA_BITS = 0x6;
// protected static final int INT_DOUBLE_DATA_BITS = 0x5;
// protected static final int INT_EXT_DATA_BITS = 0x3;
//
// /** Extended (3-9) byte length attributes */
// /** Number of bits in the length field */
// protected static final int INT_EXT_LENGTH_BITS = 0x2;
//
// public IntWritableRowKey() {
// super(INT_SINGLE, INT_SINGLE_DATA_BITS, INT_DOUBLE,
// INT_DOUBLE_DATA_BITS, INT_EXT_LENGTH_BITS,
// INT_EXT_DATA_BITS);
// }
//
// @Override
// public Class<?> getSerializedClass() { return IntWritable.class; }
//
// @Override
// Writable createWritable() { return new IntWritable(); }
//
// @Override
// void setWritable(long x, Writable w) { ((IntWritable)w).set((int)x); }
//
// @Override
// long getWritable(Writable w) { return ((IntWritable)w).get(); }
//
// @Override
// long getSign(long l) { return l & Long.MIN_VALUE; }
//
// @Override
// protected byte initHeader(boolean sign) {
// return sign ? 0 : INT_SIGN; /* sign bit is negated in header */
// }
//
// @Override
// protected byte getSign(byte h) {
// return (h & INT_SIGN) != 0 ? 0 : Byte.MIN_VALUE;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/IntegerRowKey.java
// public class IntegerRowKey extends IntWritableRowKey
// {
// private IntWritable iw;
//
// @Override
// public Class<?> getSerializedClass() { return Integer.class; }
//
// protected Object toIntWritable(Object o) {
// if (o == null || o instanceof IntWritable)
// return o;
// if (iw == null)
// iw = new IntWritable();
// iw.set((Integer)o);
// return iw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toIntWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toIntWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// IntWritable iw = (IntWritable) super.deserialize(w);
// if (iw == null)
// return iw;
//
// return Integer.valueOf(iw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
| import orderly.IntWritableRowKey;
import orderly.IntegerRowKey;
import orderly.Order;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable; | /* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class IntExample
{
/* Simple examples showing serialization lengths with Integer Row Key */
public void lengthExamples() throws Exception { | // Path: orderly-core/src/main/java/orderly/IntWritableRowKey.java
// public class IntWritableRowKey extends AbstractVarIntRowKey
// {
// /** Header flags */
// protected static final byte INT_SIGN = (byte) 0x80;
// protected static final byte INT_SINGLE = (byte) 0x40;
// protected static final byte INT_DOUBLE = (byte) 0x20;
//
// /** Header data bits for each header type */
// protected static final int INT_SINGLE_DATA_BITS = 0x6;
// protected static final int INT_DOUBLE_DATA_BITS = 0x5;
// protected static final int INT_EXT_DATA_BITS = 0x3;
//
// /** Extended (3-9) byte length attributes */
// /** Number of bits in the length field */
// protected static final int INT_EXT_LENGTH_BITS = 0x2;
//
// public IntWritableRowKey() {
// super(INT_SINGLE, INT_SINGLE_DATA_BITS, INT_DOUBLE,
// INT_DOUBLE_DATA_BITS, INT_EXT_LENGTH_BITS,
// INT_EXT_DATA_BITS);
// }
//
// @Override
// public Class<?> getSerializedClass() { return IntWritable.class; }
//
// @Override
// Writable createWritable() { return new IntWritable(); }
//
// @Override
// void setWritable(long x, Writable w) { ((IntWritable)w).set((int)x); }
//
// @Override
// long getWritable(Writable w) { return ((IntWritable)w).get(); }
//
// @Override
// long getSign(long l) { return l & Long.MIN_VALUE; }
//
// @Override
// protected byte initHeader(boolean sign) {
// return sign ? 0 : INT_SIGN; /* sign bit is negated in header */
// }
//
// @Override
// protected byte getSign(byte h) {
// return (h & INT_SIGN) != 0 ? 0 : Byte.MIN_VALUE;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/IntegerRowKey.java
// public class IntegerRowKey extends IntWritableRowKey
// {
// private IntWritable iw;
//
// @Override
// public Class<?> getSerializedClass() { return Integer.class; }
//
// protected Object toIntWritable(Object o) {
// if (o == null || o instanceof IntWritable)
// return o;
// if (iw == null)
// iw = new IntWritable();
// iw.set((Integer)o);
// return iw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toIntWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toIntWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// IntWritable iw = (IntWritable) super.deserialize(w);
// if (iw == null)
// return iw;
//
// return Integer.valueOf(iw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
// Path: orderly-examples/src/main/java/orderly/example/IntExample.java
import orderly.IntWritableRowKey;
import orderly.IntegerRowKey;
import orderly.Order;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class IntExample
{
/* Simple examples showing serialization lengths with Integer Row Key */
public void lengthExamples() throws Exception { | IntegerRowKey i = new IntegerRowKey(); |
ndimiduk/orderly | orderly-examples/src/main/java/orderly/example/IntExample.java | // Path: orderly-core/src/main/java/orderly/IntWritableRowKey.java
// public class IntWritableRowKey extends AbstractVarIntRowKey
// {
// /** Header flags */
// protected static final byte INT_SIGN = (byte) 0x80;
// protected static final byte INT_SINGLE = (byte) 0x40;
// protected static final byte INT_DOUBLE = (byte) 0x20;
//
// /** Header data bits for each header type */
// protected static final int INT_SINGLE_DATA_BITS = 0x6;
// protected static final int INT_DOUBLE_DATA_BITS = 0x5;
// protected static final int INT_EXT_DATA_BITS = 0x3;
//
// /** Extended (3-9) byte length attributes */
// /** Number of bits in the length field */
// protected static final int INT_EXT_LENGTH_BITS = 0x2;
//
// public IntWritableRowKey() {
// super(INT_SINGLE, INT_SINGLE_DATA_BITS, INT_DOUBLE,
// INT_DOUBLE_DATA_BITS, INT_EXT_LENGTH_BITS,
// INT_EXT_DATA_BITS);
// }
//
// @Override
// public Class<?> getSerializedClass() { return IntWritable.class; }
//
// @Override
// Writable createWritable() { return new IntWritable(); }
//
// @Override
// void setWritable(long x, Writable w) { ((IntWritable)w).set((int)x); }
//
// @Override
// long getWritable(Writable w) { return ((IntWritable)w).get(); }
//
// @Override
// long getSign(long l) { return l & Long.MIN_VALUE; }
//
// @Override
// protected byte initHeader(boolean sign) {
// return sign ? 0 : INT_SIGN; /* sign bit is negated in header */
// }
//
// @Override
// protected byte getSign(byte h) {
// return (h & INT_SIGN) != 0 ? 0 : Byte.MIN_VALUE;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/IntegerRowKey.java
// public class IntegerRowKey extends IntWritableRowKey
// {
// private IntWritable iw;
//
// @Override
// public Class<?> getSerializedClass() { return Integer.class; }
//
// protected Object toIntWritable(Object o) {
// if (o == null || o instanceof IntWritable)
// return o;
// if (iw == null)
// iw = new IntWritable();
// iw.set((Integer)o);
// return iw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toIntWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toIntWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// IntWritable iw = (IntWritable) super.deserialize(w);
// if (iw == null)
// return iw;
//
// return Integer.valueOf(iw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
| import orderly.IntWritableRowKey;
import orderly.IntegerRowKey;
import orderly.Order;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable; | /* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class IntExample
{
/* Simple examples showing serialization lengths with Integer Row Key */
public void lengthExamples() throws Exception {
IntegerRowKey i = new IntegerRowKey();
System.out.println("serialize(null) length - " + i.serialize(null).length);
System.out.println("serialize(57) length - " + i.serialize(57).length);
System.out.println("serialize(293) length - " + i.serialize(293).length);
| // Path: orderly-core/src/main/java/orderly/IntWritableRowKey.java
// public class IntWritableRowKey extends AbstractVarIntRowKey
// {
// /** Header flags */
// protected static final byte INT_SIGN = (byte) 0x80;
// protected static final byte INT_SINGLE = (byte) 0x40;
// protected static final byte INT_DOUBLE = (byte) 0x20;
//
// /** Header data bits for each header type */
// protected static final int INT_SINGLE_DATA_BITS = 0x6;
// protected static final int INT_DOUBLE_DATA_BITS = 0x5;
// protected static final int INT_EXT_DATA_BITS = 0x3;
//
// /** Extended (3-9) byte length attributes */
// /** Number of bits in the length field */
// protected static final int INT_EXT_LENGTH_BITS = 0x2;
//
// public IntWritableRowKey() {
// super(INT_SINGLE, INT_SINGLE_DATA_BITS, INT_DOUBLE,
// INT_DOUBLE_DATA_BITS, INT_EXT_LENGTH_BITS,
// INT_EXT_DATA_BITS);
// }
//
// @Override
// public Class<?> getSerializedClass() { return IntWritable.class; }
//
// @Override
// Writable createWritable() { return new IntWritable(); }
//
// @Override
// void setWritable(long x, Writable w) { ((IntWritable)w).set((int)x); }
//
// @Override
// long getWritable(Writable w) { return ((IntWritable)w).get(); }
//
// @Override
// long getSign(long l) { return l & Long.MIN_VALUE; }
//
// @Override
// protected byte initHeader(boolean sign) {
// return sign ? 0 : INT_SIGN; /* sign bit is negated in header */
// }
//
// @Override
// protected byte getSign(byte h) {
// return (h & INT_SIGN) != 0 ? 0 : Byte.MIN_VALUE;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/IntegerRowKey.java
// public class IntegerRowKey extends IntWritableRowKey
// {
// private IntWritable iw;
//
// @Override
// public Class<?> getSerializedClass() { return Integer.class; }
//
// protected Object toIntWritable(Object o) {
// if (o == null || o instanceof IntWritable)
// return o;
// if (iw == null)
// iw = new IntWritable();
// iw.set((Integer)o);
// return iw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toIntWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toIntWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// IntWritable iw = (IntWritable) super.deserialize(w);
// if (iw == null)
// return iw;
//
// return Integer.valueOf(iw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
// Path: orderly-examples/src/main/java/orderly/example/IntExample.java
import orderly.IntWritableRowKey;
import orderly.IntegerRowKey;
import orderly.Order;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class IntExample
{
/* Simple examples showing serialization lengths with Integer Row Key */
public void lengthExamples() throws Exception {
IntegerRowKey i = new IntegerRowKey();
System.out.println("serialize(null) length - " + i.serialize(null).length);
System.out.println("serialize(57) length - " + i.serialize(57).length);
System.out.println("serialize(293) length - " + i.serialize(293).length);
| i.setOrder(Order.DESCENDING); |
ndimiduk/orderly | orderly-examples/src/main/java/orderly/example/IntExample.java | // Path: orderly-core/src/main/java/orderly/IntWritableRowKey.java
// public class IntWritableRowKey extends AbstractVarIntRowKey
// {
// /** Header flags */
// protected static final byte INT_SIGN = (byte) 0x80;
// protected static final byte INT_SINGLE = (byte) 0x40;
// protected static final byte INT_DOUBLE = (byte) 0x20;
//
// /** Header data bits for each header type */
// protected static final int INT_SINGLE_DATA_BITS = 0x6;
// protected static final int INT_DOUBLE_DATA_BITS = 0x5;
// protected static final int INT_EXT_DATA_BITS = 0x3;
//
// /** Extended (3-9) byte length attributes */
// /** Number of bits in the length field */
// protected static final int INT_EXT_LENGTH_BITS = 0x2;
//
// public IntWritableRowKey() {
// super(INT_SINGLE, INT_SINGLE_DATA_BITS, INT_DOUBLE,
// INT_DOUBLE_DATA_BITS, INT_EXT_LENGTH_BITS,
// INT_EXT_DATA_BITS);
// }
//
// @Override
// public Class<?> getSerializedClass() { return IntWritable.class; }
//
// @Override
// Writable createWritable() { return new IntWritable(); }
//
// @Override
// void setWritable(long x, Writable w) { ((IntWritable)w).set((int)x); }
//
// @Override
// long getWritable(Writable w) { return ((IntWritable)w).get(); }
//
// @Override
// long getSign(long l) { return l & Long.MIN_VALUE; }
//
// @Override
// protected byte initHeader(boolean sign) {
// return sign ? 0 : INT_SIGN; /* sign bit is negated in header */
// }
//
// @Override
// protected byte getSign(byte h) {
// return (h & INT_SIGN) != 0 ? 0 : Byte.MIN_VALUE;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/IntegerRowKey.java
// public class IntegerRowKey extends IntWritableRowKey
// {
// private IntWritable iw;
//
// @Override
// public Class<?> getSerializedClass() { return Integer.class; }
//
// protected Object toIntWritable(Object o) {
// if (o == null || o instanceof IntWritable)
// return o;
// if (iw == null)
// iw = new IntWritable();
// iw.set((Integer)o);
// return iw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toIntWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toIntWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// IntWritable iw = (IntWritable) super.deserialize(w);
// if (iw == null)
// return iw;
//
// return Integer.valueOf(iw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
| import orderly.IntWritableRowKey;
import orderly.IntegerRowKey;
import orderly.Order;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable; | /* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class IntExample
{
/* Simple examples showing serialization lengths with Integer Row Key */
public void lengthExamples() throws Exception {
IntegerRowKey i = new IntegerRowKey();
System.out.println("serialize(null) length - " + i.serialize(null).length);
System.out.println("serialize(57) length - " + i.serialize(57).length);
System.out.println("serialize(293) length - " + i.serialize(293).length);
i.setOrder(Order.DESCENDING);
System.out.println("descending serialize (null) - length " +
i.serialize(null).length);
System.out.println("descending serialize (57) - length " +
i.serialize(57).length);
}
/* Simple examples showing serialization tests with IntWritable Row Key */
public void serializationExamples() throws Exception { | // Path: orderly-core/src/main/java/orderly/IntWritableRowKey.java
// public class IntWritableRowKey extends AbstractVarIntRowKey
// {
// /** Header flags */
// protected static final byte INT_SIGN = (byte) 0x80;
// protected static final byte INT_SINGLE = (byte) 0x40;
// protected static final byte INT_DOUBLE = (byte) 0x20;
//
// /** Header data bits for each header type */
// protected static final int INT_SINGLE_DATA_BITS = 0x6;
// protected static final int INT_DOUBLE_DATA_BITS = 0x5;
// protected static final int INT_EXT_DATA_BITS = 0x3;
//
// /** Extended (3-9) byte length attributes */
// /** Number of bits in the length field */
// protected static final int INT_EXT_LENGTH_BITS = 0x2;
//
// public IntWritableRowKey() {
// super(INT_SINGLE, INT_SINGLE_DATA_BITS, INT_DOUBLE,
// INT_DOUBLE_DATA_BITS, INT_EXT_LENGTH_BITS,
// INT_EXT_DATA_BITS);
// }
//
// @Override
// public Class<?> getSerializedClass() { return IntWritable.class; }
//
// @Override
// Writable createWritable() { return new IntWritable(); }
//
// @Override
// void setWritable(long x, Writable w) { ((IntWritable)w).set((int)x); }
//
// @Override
// long getWritable(Writable w) { return ((IntWritable)w).get(); }
//
// @Override
// long getSign(long l) { return l & Long.MIN_VALUE; }
//
// @Override
// protected byte initHeader(boolean sign) {
// return sign ? 0 : INT_SIGN; /* sign bit is negated in header */
// }
//
// @Override
// protected byte getSign(byte h) {
// return (h & INT_SIGN) != 0 ? 0 : Byte.MIN_VALUE;
// }
// }
//
// Path: orderly-core/src/main/java/orderly/IntegerRowKey.java
// public class IntegerRowKey extends IntWritableRowKey
// {
// private IntWritable iw;
//
// @Override
// public Class<?> getSerializedClass() { return Integer.class; }
//
// protected Object toIntWritable(Object o) {
// if (o == null || o instanceof IntWritable)
// return o;
// if (iw == null)
// iw = new IntWritable();
// iw.set((Integer)o);
// return iw;
// }
//
// @Override
// public int getSerializedLength(Object o) throws IOException {
// return super.getSerializedLength(toIntWritable(o));
// }
//
// @Override
// public void serialize(Object o, ImmutableBytesWritable w) throws IOException {
// super.serialize(toIntWritable(o), w);
// }
//
// @Override
// public Object deserialize(ImmutableBytesWritable w) throws IOException {
// IntWritable iw = (IntWritable) super.deserialize(w);
// if (iw == null)
// return iw;
//
// return Integer.valueOf(iw.get());
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
// Path: orderly-examples/src/main/java/orderly/example/IntExample.java
import orderly.IntWritableRowKey;
import orderly.IntegerRowKey;
import orderly.Order;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly.example;
public class IntExample
{
/* Simple examples showing serialization lengths with Integer Row Key */
public void lengthExamples() throws Exception {
IntegerRowKey i = new IntegerRowKey();
System.out.println("serialize(null) length - " + i.serialize(null).length);
System.out.println("serialize(57) length - " + i.serialize(57).length);
System.out.println("serialize(293) length - " + i.serialize(293).length);
i.setOrder(Order.DESCENDING);
System.out.println("descending serialize (null) - length " +
i.serialize(null).length);
System.out.println("descending serialize (57) - length " +
i.serialize(57).length);
}
/* Simple examples showing serialization tests with IntWritable Row Key */
public void serializationExamples() throws Exception { | IntWritableRowKey i = new IntWritableRowKey(); |
ndimiduk/orderly | orderly-core/src/test/java/orderly/RandomRowKeyTestCase.java | // Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
//
// Path: orderly-core/src/main/java/orderly/RowKeyUtils.java
// public class RowKeyUtils
// {
// /** Shared (immutable) zero-length byte array singleton. */
// public static final byte[] EMPTY = new byte[0];
//
// /** Converts a (byte array, offset, length) triple into a byte array,
// * copying only if necessary. No copy is performed if offset is 0 and
// * length is array.length.
// */
// public static byte[] toBytes(byte[] b, int offset, int length) {
// if (offset == 0 && length == b.length)
// return b;
// else if (offset == 0)
// return Arrays.copyOf(b, length);
// return Arrays.copyOfRange(b, offset, offset + length);
// }
//
// /** Converts an ImmutableBytesWritable to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(ImmutableBytesWritable w) {
// return toBytes(w.get(), w.getOffset(), w.getLength());
// }
//
// /** Converts a Text object to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(Text t) {
// return toBytes(t.getBytes(), 0, t.getLength());
// }
//
// /** Seeks forward/backward within an ImmutableBytesWritable. After
// * seek is complete, the position (length) of the byte array is
// * incremented (decremented) by the seek amount.
// * @param w immutable byte array used for seek
// * @param offset number of bytes to seek (relative to current position)
// */
// public static void seek(ImmutableBytesWritable w, int offset) {
// w.set(w.get(), w.getOffset() + offset, w.getLength() - offset);
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Termination.java
// public enum Termination {
// AUTO, MUST, SHOULD_NOT
// }
| import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import orderly.Order;
import orderly.RowKeyUtils;
import orderly.Termination;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.junit.Before;
import org.junit.Test; | /* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly;
public abstract class RandomRowKeyTestCase extends RowKeyTestCase
{
protected Random r;
protected int numTests, maxRedZone;
@Before
@Override
public void setUp() {
if (r == null)
r = new Random(Long.valueOf(System.getProperty("test.random.seed", "0")));
numTests = Integer.valueOf(System.getProperty("test.random.count", "8192"));
maxRedZone = Integer.valueOf(System.getProperty("test.random.maxredzone",
"16"));
super.setUp();
}
public RandomRowKeyTestCase setRandom(Random r) {
this.r = r;
return this;
}
public RandomRowKeyTestCase setNumTests(int numTests) {
this.numTests = numTests;
return this;
}
public RandomRowKeyTestCase setMaxRedZone(int maxRedZone) {
this.maxRedZone = maxRedZone;
return this;
}
@Override
public ImmutableBytesWritable allocateBuffer(Object o) throws IOException {
return new RedZoneImmutableBytesWritable(key.getSerializedLength(o), | // Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
//
// Path: orderly-core/src/main/java/orderly/RowKeyUtils.java
// public class RowKeyUtils
// {
// /** Shared (immutable) zero-length byte array singleton. */
// public static final byte[] EMPTY = new byte[0];
//
// /** Converts a (byte array, offset, length) triple into a byte array,
// * copying only if necessary. No copy is performed if offset is 0 and
// * length is array.length.
// */
// public static byte[] toBytes(byte[] b, int offset, int length) {
// if (offset == 0 && length == b.length)
// return b;
// else if (offset == 0)
// return Arrays.copyOf(b, length);
// return Arrays.copyOfRange(b, offset, offset + length);
// }
//
// /** Converts an ImmutableBytesWritable to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(ImmutableBytesWritable w) {
// return toBytes(w.get(), w.getOffset(), w.getLength());
// }
//
// /** Converts a Text object to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(Text t) {
// return toBytes(t.getBytes(), 0, t.getLength());
// }
//
// /** Seeks forward/backward within an ImmutableBytesWritable. After
// * seek is complete, the position (length) of the byte array is
// * incremented (decremented) by the seek amount.
// * @param w immutable byte array used for seek
// * @param offset number of bytes to seek (relative to current position)
// */
// public static void seek(ImmutableBytesWritable w, int offset) {
// w.set(w.get(), w.getOffset() + offset, w.getLength() - offset);
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Termination.java
// public enum Termination {
// AUTO, MUST, SHOULD_NOT
// }
// Path: orderly-core/src/test/java/orderly/RandomRowKeyTestCase.java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import orderly.Order;
import orderly.RowKeyUtils;
import orderly.Termination;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.junit.Before;
import org.junit.Test;
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 orderly;
public abstract class RandomRowKeyTestCase extends RowKeyTestCase
{
protected Random r;
protected int numTests, maxRedZone;
@Before
@Override
public void setUp() {
if (r == null)
r = new Random(Long.valueOf(System.getProperty("test.random.seed", "0")));
numTests = Integer.valueOf(System.getProperty("test.random.count", "8192"));
maxRedZone = Integer.valueOf(System.getProperty("test.random.maxredzone",
"16"));
super.setUp();
}
public RandomRowKeyTestCase setRandom(Random r) {
this.r = r;
return this;
}
public RandomRowKeyTestCase setNumTests(int numTests) {
this.numTests = numTests;
return this;
}
public RandomRowKeyTestCase setMaxRedZone(int maxRedZone) {
this.maxRedZone = maxRedZone;
return this;
}
@Override
public ImmutableBytesWritable allocateBuffer(Object o) throws IOException {
return new RedZoneImmutableBytesWritable(key.getSerializedLength(o), | key.getTermination() == Termination.MUST); |
ndimiduk/orderly | orderly-core/src/test/java/orderly/RandomRowKeyTestCase.java | // Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
//
// Path: orderly-core/src/main/java/orderly/RowKeyUtils.java
// public class RowKeyUtils
// {
// /** Shared (immutable) zero-length byte array singleton. */
// public static final byte[] EMPTY = new byte[0];
//
// /** Converts a (byte array, offset, length) triple into a byte array,
// * copying only if necessary. No copy is performed if offset is 0 and
// * length is array.length.
// */
// public static byte[] toBytes(byte[] b, int offset, int length) {
// if (offset == 0 && length == b.length)
// return b;
// else if (offset == 0)
// return Arrays.copyOf(b, length);
// return Arrays.copyOfRange(b, offset, offset + length);
// }
//
// /** Converts an ImmutableBytesWritable to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(ImmutableBytesWritable w) {
// return toBytes(w.get(), w.getOffset(), w.getLength());
// }
//
// /** Converts a Text object to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(Text t) {
// return toBytes(t.getBytes(), 0, t.getLength());
// }
//
// /** Seeks forward/backward within an ImmutableBytesWritable. After
// * seek is complete, the position (length) of the byte array is
// * incremented (decremented) by the seek amount.
// * @param w immutable byte array used for seek
// * @param offset number of bytes to seek (relative to current position)
// */
// public static void seek(ImmutableBytesWritable w, int offset) {
// w.set(w.get(), w.getOffset() + offset, w.getLength() - offset);
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Termination.java
// public enum Termination {
// AUTO, MUST, SHOULD_NOT
// }
| import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import orderly.Order;
import orderly.RowKeyUtils;
import orderly.Termination;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.junit.Before;
import org.junit.Test; | public RandomRowKeyTestCase setNumTests(int numTests) {
this.numTests = numTests;
return this;
}
public RandomRowKeyTestCase setMaxRedZone(int maxRedZone) {
this.maxRedZone = maxRedZone;
return this;
}
@Override
public ImmutableBytesWritable allocateBuffer(Object o) throws IOException {
return new RedZoneImmutableBytesWritable(key.getSerializedLength(o),
key.getTermination() == Termination.MUST);
}
@Override
public void serialize(Object o, ImmutableBytesWritable w) throws IOException
{
byte[] b;
int len;
switch(r.nextInt(4)) {
case 0: /* serialize(Object, ImmutableBytesWritable) */
key.serialize(o, w);
break;
case 1: /* serialize(Object) */
b = key.serialize(o);
System.arraycopy(b, 0, w.get(), w.getOffset(), b.length); | // Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
//
// Path: orderly-core/src/main/java/orderly/RowKeyUtils.java
// public class RowKeyUtils
// {
// /** Shared (immutable) zero-length byte array singleton. */
// public static final byte[] EMPTY = new byte[0];
//
// /** Converts a (byte array, offset, length) triple into a byte array,
// * copying only if necessary. No copy is performed if offset is 0 and
// * length is array.length.
// */
// public static byte[] toBytes(byte[] b, int offset, int length) {
// if (offset == 0 && length == b.length)
// return b;
// else if (offset == 0)
// return Arrays.copyOf(b, length);
// return Arrays.copyOfRange(b, offset, offset + length);
// }
//
// /** Converts an ImmutableBytesWritable to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(ImmutableBytesWritable w) {
// return toBytes(w.get(), w.getOffset(), w.getLength());
// }
//
// /** Converts a Text object to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(Text t) {
// return toBytes(t.getBytes(), 0, t.getLength());
// }
//
// /** Seeks forward/backward within an ImmutableBytesWritable. After
// * seek is complete, the position (length) of the byte array is
// * incremented (decremented) by the seek amount.
// * @param w immutable byte array used for seek
// * @param offset number of bytes to seek (relative to current position)
// */
// public static void seek(ImmutableBytesWritable w, int offset) {
// w.set(w.get(), w.getOffset() + offset, w.getLength() - offset);
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Termination.java
// public enum Termination {
// AUTO, MUST, SHOULD_NOT
// }
// Path: orderly-core/src/test/java/orderly/RandomRowKeyTestCase.java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import orderly.Order;
import orderly.RowKeyUtils;
import orderly.Termination;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.junit.Before;
import org.junit.Test;
public RandomRowKeyTestCase setNumTests(int numTests) {
this.numTests = numTests;
return this;
}
public RandomRowKeyTestCase setMaxRedZone(int maxRedZone) {
this.maxRedZone = maxRedZone;
return this;
}
@Override
public ImmutableBytesWritable allocateBuffer(Object o) throws IOException {
return new RedZoneImmutableBytesWritable(key.getSerializedLength(o),
key.getTermination() == Termination.MUST);
}
@Override
public void serialize(Object o, ImmutableBytesWritable w) throws IOException
{
byte[] b;
int len;
switch(r.nextInt(4)) {
case 0: /* serialize(Object, ImmutableBytesWritable) */
key.serialize(o, w);
break;
case 1: /* serialize(Object) */
b = key.serialize(o);
System.arraycopy(b, 0, w.get(), w.getOffset(), b.length); | RowKeyUtils.seek(w, b.length); |
ndimiduk/orderly | orderly-core/src/test/java/orderly/RandomRowKeyTestCase.java | // Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
//
// Path: orderly-core/src/main/java/orderly/RowKeyUtils.java
// public class RowKeyUtils
// {
// /** Shared (immutable) zero-length byte array singleton. */
// public static final byte[] EMPTY = new byte[0];
//
// /** Converts a (byte array, offset, length) triple into a byte array,
// * copying only if necessary. No copy is performed if offset is 0 and
// * length is array.length.
// */
// public static byte[] toBytes(byte[] b, int offset, int length) {
// if (offset == 0 && length == b.length)
// return b;
// else if (offset == 0)
// return Arrays.copyOf(b, length);
// return Arrays.copyOfRange(b, offset, offset + length);
// }
//
// /** Converts an ImmutableBytesWritable to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(ImmutableBytesWritable w) {
// return toBytes(w.get(), w.getOffset(), w.getLength());
// }
//
// /** Converts a Text object to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(Text t) {
// return toBytes(t.getBytes(), 0, t.getLength());
// }
//
// /** Seeks forward/backward within an ImmutableBytesWritable. After
// * seek is complete, the position (length) of the byte array is
// * incremented (decremented) by the seek amount.
// * @param w immutable byte array used for seek
// * @param offset number of bytes to seek (relative to current position)
// */
// public static void seek(ImmutableBytesWritable w, int offset) {
// w.set(w.get(), w.getOffset() + offset, w.getLength() - offset);
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Termination.java
// public enum Termination {
// AUTO, MUST, SHOULD_NOT
// }
| import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import orderly.Order;
import orderly.RowKeyUtils;
import orderly.Termination;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.junit.Before;
import org.junit.Test; | public void testSkip(Object o, ImmutableBytesWritable w)
throws IOException
{
super.testSkip(o, w);
((RedZoneImmutableBytesWritable)w).verify();
}
@Override
public void testSort(Object o1, ImmutableBytesWritable w1, Object o2,
ImmutableBytesWritable w2) throws IOException
{
RedZoneImmutableBytesWritable r1 = (RedZoneImmutableBytesWritable) w1,
r2 = (RedZoneImmutableBytesWritable) w2;
int r1Length = r1.getLength(),
r2Length = r2.getLength();
r1.set(r1.get(), r1.getOffset(), r1.getBufferLength());
r2.set(r2.get(), r2.getOffset(), r2.getBufferLength());
super.testSort(o1, r1, o2, r2);
r1.set(r1.get(), r1.getOffset(), r1Length);
r1.verify();
r2.set(r2.get(), r2.getOffset(), r2Length);
r2.verify();
}
@Test
@Override
public void testRowKey() throws IOException {
for (int i = 0; i < numTests; i++) { | // Path: orderly-core/src/main/java/orderly/Order.java
// public enum Order
// {
// ASCENDING((byte)0),
// DESCENDING((byte)0xff);
//
// private final byte mask;
//
// Order(byte mask) { this.mask = mask; }
//
// /** Gets the byte mask associated with the sort order. When a
// * serialized byte is XOR'd with the mask, the result is the same byte
// * but sorted in the direction specified by the Order object.
// * @see RowKey#serialize
// */
// byte mask() { return mask; }
//
// }
//
// Path: orderly-core/src/main/java/orderly/RowKeyUtils.java
// public class RowKeyUtils
// {
// /** Shared (immutable) zero-length byte array singleton. */
// public static final byte[] EMPTY = new byte[0];
//
// /** Converts a (byte array, offset, length) triple into a byte array,
// * copying only if necessary. No copy is performed if offset is 0 and
// * length is array.length.
// */
// public static byte[] toBytes(byte[] b, int offset, int length) {
// if (offset == 0 && length == b.length)
// return b;
// else if (offset == 0)
// return Arrays.copyOf(b, length);
// return Arrays.copyOfRange(b, offset, offset + length);
// }
//
// /** Converts an ImmutableBytesWritable to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(ImmutableBytesWritable w) {
// return toBytes(w.get(), w.getOffset(), w.getLength());
// }
//
// /** Converts a Text object to a byte array, copying only if
// * necessary.
// */
// public static byte[] toBytes(Text t) {
// return toBytes(t.getBytes(), 0, t.getLength());
// }
//
// /** Seeks forward/backward within an ImmutableBytesWritable. After
// * seek is complete, the position (length) of the byte array is
// * incremented (decremented) by the seek amount.
// * @param w immutable byte array used for seek
// * @param offset number of bytes to seek (relative to current position)
// */
// public static void seek(ImmutableBytesWritable w, int offset) {
// w.set(w.get(), w.getOffset() + offset, w.getLength() - offset);
// }
// }
//
// Path: orderly-core/src/main/java/orderly/Termination.java
// public enum Termination {
// AUTO, MUST, SHOULD_NOT
// }
// Path: orderly-core/src/test/java/orderly/RandomRowKeyTestCase.java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import orderly.Order;
import orderly.RowKeyUtils;
import orderly.Termination;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.junit.Before;
import org.junit.Test;
public void testSkip(Object o, ImmutableBytesWritable w)
throws IOException
{
super.testSkip(o, w);
((RedZoneImmutableBytesWritable)w).verify();
}
@Override
public void testSort(Object o1, ImmutableBytesWritable w1, Object o2,
ImmutableBytesWritable w2) throws IOException
{
RedZoneImmutableBytesWritable r1 = (RedZoneImmutableBytesWritable) w1,
r2 = (RedZoneImmutableBytesWritable) w2;
int r1Length = r1.getLength(),
r2Length = r2.getLength();
r1.set(r1.get(), r1.getOffset(), r1.getBufferLength());
r2.set(r2.get(), r2.getOffset(), r2.getBufferLength());
super.testSort(o1, r1, o2, r2);
r1.set(r1.get(), r1.getOffset(), r1Length);
r1.verify();
r2.set(r2.get(), r2.getOffset(), r2Length);
r2.verify();
}
@Test
@Override
public void testRowKey() throws IOException {
for (int i = 0; i < numTests; i++) { | setRowKey(createRowKey().setOrder(r.nextBoolean() ? Order.ASCENDING : |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/collector/ScriptFile.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration.collector;
/**
* This file represents a script inside the <code>MigrationRepository</code>
* while it is initialized and the collector for script files is done.
*
* This file only includes the files metadata, currently the version number,
* the resource name and the script name. The content of the script files is read in
* case migration scripts are requested from the repository. For performance reasons
* it is not done during the collector as it might not be required to read the files
* in case the database schema is up to date.
*
* This class implements the {@link Comparable} interface in order to sort the
* scripts by the version.
*
* @author Patrick Kranz
*/
public class ScriptFile implements Comparable {
private final int version;
private final String resourceName;
private final String scriptName;
/**
* A constructor taken all relevant information for a script. All
* arguments are required.
*
* @param version the version that this script represents. This is the number in the
* beginning of the file name.
* @param resourceName the name of the resource that represents the script inside the classpath
* @param scriptName the name of the script itself. Normally everything from the file name except
* the version
*/
public ScriptFile(int version, String resourceName, String scriptName) {
this.version = version; | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/collector/ScriptFile.java
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration.collector;
/**
* This file represents a script inside the <code>MigrationRepository</code>
* while it is initialized and the collector for script files is done.
*
* This file only includes the files metadata, currently the version number,
* the resource name and the script name. The content of the script files is read in
* case migration scripts are requested from the repository. For performance reasons
* it is not done during the collector as it might not be required to read the files
* in case the database schema is up to date.
*
* This class implements the {@link Comparable} interface in order to sort the
* scripts by the version.
*
* @author Patrick Kranz
*/
public class ScriptFile implements Comparable {
private final int version;
private final String resourceName;
private final String scriptName;
/**
* A constructor taken all relevant information for a script. All
* arguments are required.
*
* @param version the version that this script represents. This is the number in the
* beginning of the file name.
* @param resourceName the name of the resource that represents the script inside the classpath
* @param scriptName the name of the script itself. Normally everything from the file name except
* the version
*/
public ScriptFile(int version, String resourceName, String scriptName) {
this.version = version; | this.resourceName = notNullOrEmpty(resourceName, "resourceName"); |
patka/cassandra-migration | cassandra-migration-spring-boot-starter/src/test/java/org/cognitor/cassandra/migration/spring/CassandraMigrationAutoConfigurationTest.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationTask.java
// public class MigrationTask {
// private static final Logger LOGGER = getLogger(MigrationTask.class);
//
// private final Database database;
// private final MigrationRepository repository;
// private final boolean withConsensus;
//
// /**
// * Creates a migration task that uses the given database and repository and no consensus
// * protocol enabled.
// *
// * @param database the database that should be migrated
// * @param repository the repository that contains the migration scripts
// */
// public MigrationTask(Database database, MigrationRepository repository) {
// this(database, repository, false);
// }
//
// /**
// * Creates a migration task that uses the given database and repository.
// *
// * @param database the database that should be migrated
// * @param repository the repository that contains the migration scripts
// * @param withConsensus if the migration should be handled by a single process at once, using LWT based leader election
// */
// public MigrationTask(Database database, MigrationRepository repository, boolean withConsensus) {
// this.database = notNull(database, "database");
// this.repository = notNull(repository, "repository");
// this.withConsensus = withConsensus;
// }
//
// /**
// * Start the actual migration. Take the version of the database, get all required migrations and execute them or do
// * nothing if the DB is already up to date.
// * <p>
// * At the end the underlying database instance is closed.
// *
// * @throws MigrationException if a migration fails
// */
// public void migrate() {
// if (databaseIsUpToDate()) {
// LOGGER.info(format("Keyspace %s is already up to date at version %d", database.getKeyspaceName(),
// database.getVersion()));
// database.close();
// return;
// }
//
// try {
// if (!instanceHasLead()) {
// return;
// }
// if (!databaseIsUpToDate()) {
// List<DbMigration> migrations = repository.getMigrationsSinceVersion(database.getVersion());
// migrations.forEach(database::execute);
// LOGGER.info(format("Migrated keyspace %s to version %d", database.getKeyspaceName(),
// database.getVersion()));
// }
// } finally {
// if (withConsensus) {
// database.removeLeadOnMigrations();
// }
// database.close();
// }
// }
//
// private boolean instanceHasLead() {
// return !withConsensus || database.takeLeadOnMigrations(repository.getLatestVersion());
// }
//
// private boolean databaseIsUpToDate() {
// return database.getVersion() >= repository.getLatestVersion();
// }
// }
//
// Path: cassandra-migration-spring-boot-starter/src/main/java/org/cognitor/cassandra/migration/spring/CassandraMigrationAutoConfiguration.java
// public static final String CQL_SESSION_BEAN_NAME = "cassandraMigrationCqlSession";
| import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.CqlSessionBuilder;
import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.cql.Row;
import org.cognitor.cassandra.migration.MigrationTask;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.List;
import static org.cognitor.cassandra.migration.spring.CassandraMigrationAutoConfiguration.CQL_SESSION_BEAN_NAME;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; | package org.cognitor.cassandra.migration.spring;
/**
* @author Patrick Kranz
*/
public class CassandraMigrationAutoConfigurationTest {
private static final String KEYSPACE = "test_keyspace";
@Before
public void before() {
CqlSession session = createSession();
session.execute("CREATE KEYSPACE test_keyspace WITH REPLICATION = " +
"{ 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
session.close();
}
@After
public void after() {
CqlSession session = createSession();
session.execute("DROP KEYSPACE IF EXISTS " + KEYSPACE + ";");
session.close();
}
@Test
public void shouldMigrateDatabaseWhenClusterGiven() {
// GIVEN
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
TestPropertyValues testValues = TestPropertyValues.of("cassandra.migration.keyspace-name:" + KEYSPACE);
testValues.applyTo(context);
context.register(ClusterConfig.class, CassandraMigrationAutoConfiguration.class);
context.refresh();
// WHEN | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationTask.java
// public class MigrationTask {
// private static final Logger LOGGER = getLogger(MigrationTask.class);
//
// private final Database database;
// private final MigrationRepository repository;
// private final boolean withConsensus;
//
// /**
// * Creates a migration task that uses the given database and repository and no consensus
// * protocol enabled.
// *
// * @param database the database that should be migrated
// * @param repository the repository that contains the migration scripts
// */
// public MigrationTask(Database database, MigrationRepository repository) {
// this(database, repository, false);
// }
//
// /**
// * Creates a migration task that uses the given database and repository.
// *
// * @param database the database that should be migrated
// * @param repository the repository that contains the migration scripts
// * @param withConsensus if the migration should be handled by a single process at once, using LWT based leader election
// */
// public MigrationTask(Database database, MigrationRepository repository, boolean withConsensus) {
// this.database = notNull(database, "database");
// this.repository = notNull(repository, "repository");
// this.withConsensus = withConsensus;
// }
//
// /**
// * Start the actual migration. Take the version of the database, get all required migrations and execute them or do
// * nothing if the DB is already up to date.
// * <p>
// * At the end the underlying database instance is closed.
// *
// * @throws MigrationException if a migration fails
// */
// public void migrate() {
// if (databaseIsUpToDate()) {
// LOGGER.info(format("Keyspace %s is already up to date at version %d", database.getKeyspaceName(),
// database.getVersion()));
// database.close();
// return;
// }
//
// try {
// if (!instanceHasLead()) {
// return;
// }
// if (!databaseIsUpToDate()) {
// List<DbMigration> migrations = repository.getMigrationsSinceVersion(database.getVersion());
// migrations.forEach(database::execute);
// LOGGER.info(format("Migrated keyspace %s to version %d", database.getKeyspaceName(),
// database.getVersion()));
// }
// } finally {
// if (withConsensus) {
// database.removeLeadOnMigrations();
// }
// database.close();
// }
// }
//
// private boolean instanceHasLead() {
// return !withConsensus || database.takeLeadOnMigrations(repository.getLatestVersion());
// }
//
// private boolean databaseIsUpToDate() {
// return database.getVersion() >= repository.getLatestVersion();
// }
// }
//
// Path: cassandra-migration-spring-boot-starter/src/main/java/org/cognitor/cassandra/migration/spring/CassandraMigrationAutoConfiguration.java
// public static final String CQL_SESSION_BEAN_NAME = "cassandraMigrationCqlSession";
// Path: cassandra-migration-spring-boot-starter/src/test/java/org/cognitor/cassandra/migration/spring/CassandraMigrationAutoConfigurationTest.java
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.CqlSessionBuilder;
import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.cql.Row;
import org.cognitor.cassandra.migration.MigrationTask;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.List;
import static org.cognitor.cassandra.migration.spring.CassandraMigrationAutoConfiguration.CQL_SESSION_BEAN_NAME;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
package org.cognitor.cassandra.migration.spring;
/**
* @author Patrick Kranz
*/
public class CassandraMigrationAutoConfigurationTest {
private static final String KEYSPACE = "test_keyspace";
@Before
public void before() {
CqlSession session = createSession();
session.execute("CREATE KEYSPACE test_keyspace WITH REPLICATION = " +
"{ 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
session.close();
}
@After
public void after() {
CqlSession session = createSession();
session.execute("DROP KEYSPACE IF EXISTS " + KEYSPACE + ";");
session.close();
}
@Test
public void shouldMigrateDatabaseWhenClusterGiven() {
// GIVEN
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
TestPropertyValues testValues = TestPropertyValues.of("cassandra.migration.keyspace-name:" + KEYSPACE);
testValues.applyTo(context);
context.register(ClusterConfig.class, CassandraMigrationAutoConfiguration.class);
context.refresh();
// WHEN | context.getBean(MigrationTask.class); |
patka/cassandra-migration | cassandra-migration-spring-boot-starter/src/test/java/org/cognitor/cassandra/migration/spring/CassandraMigrationAutoConfigurationTest.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationTask.java
// public class MigrationTask {
// private static final Logger LOGGER = getLogger(MigrationTask.class);
//
// private final Database database;
// private final MigrationRepository repository;
// private final boolean withConsensus;
//
// /**
// * Creates a migration task that uses the given database and repository and no consensus
// * protocol enabled.
// *
// * @param database the database that should be migrated
// * @param repository the repository that contains the migration scripts
// */
// public MigrationTask(Database database, MigrationRepository repository) {
// this(database, repository, false);
// }
//
// /**
// * Creates a migration task that uses the given database and repository.
// *
// * @param database the database that should be migrated
// * @param repository the repository that contains the migration scripts
// * @param withConsensus if the migration should be handled by a single process at once, using LWT based leader election
// */
// public MigrationTask(Database database, MigrationRepository repository, boolean withConsensus) {
// this.database = notNull(database, "database");
// this.repository = notNull(repository, "repository");
// this.withConsensus = withConsensus;
// }
//
// /**
// * Start the actual migration. Take the version of the database, get all required migrations and execute them or do
// * nothing if the DB is already up to date.
// * <p>
// * At the end the underlying database instance is closed.
// *
// * @throws MigrationException if a migration fails
// */
// public void migrate() {
// if (databaseIsUpToDate()) {
// LOGGER.info(format("Keyspace %s is already up to date at version %d", database.getKeyspaceName(),
// database.getVersion()));
// database.close();
// return;
// }
//
// try {
// if (!instanceHasLead()) {
// return;
// }
// if (!databaseIsUpToDate()) {
// List<DbMigration> migrations = repository.getMigrationsSinceVersion(database.getVersion());
// migrations.forEach(database::execute);
// LOGGER.info(format("Migrated keyspace %s to version %d", database.getKeyspaceName(),
// database.getVersion()));
// }
// } finally {
// if (withConsensus) {
// database.removeLeadOnMigrations();
// }
// database.close();
// }
// }
//
// private boolean instanceHasLead() {
// return !withConsensus || database.takeLeadOnMigrations(repository.getLatestVersion());
// }
//
// private boolean databaseIsUpToDate() {
// return database.getVersion() >= repository.getLatestVersion();
// }
// }
//
// Path: cassandra-migration-spring-boot-starter/src/main/java/org/cognitor/cassandra/migration/spring/CassandraMigrationAutoConfiguration.java
// public static final String CQL_SESSION_BEAN_NAME = "cassandraMigrationCqlSession";
| import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.CqlSessionBuilder;
import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.cql.Row;
import org.cognitor.cassandra.migration.MigrationTask;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.List;
import static org.cognitor.cassandra.migration.spring.CassandraMigrationAutoConfiguration.CQL_SESSION_BEAN_NAME;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; | new AnnotationConfigApplicationContext();
TestPropertyValues testValues = TestPropertyValues.of("cassandra.migration.keyspace-name:" + KEYSPACE)
.and("cassandra.migration.table-prefix:test");
testValues.applyTo(context);
context.register(ClusterConfig.class, CassandraMigrationAutoConfiguration.class);
context.refresh();
// WHEN
context.getBean(MigrationTask.class);
// THEN
CqlSession session = createSession();
List<Row> rows = session.execute("SELECT * FROM " + KEYSPACE + ".test_schema_migration").all();
assertThat(rows.size(), is(equalTo(1)));
Row migration = rows.get(0);
assertThat(migration.getBoolean("applied_successful"), is(true));
assertThat(migration.getInstant("executed_at"), is(not(nullValue())));
assertThat(migration.getString("script_name"), is(CoreMatchers.equalTo("001_create_person_table.cql")));
assertThat(migration.getString("script"), startsWith("CREATE TABLE"));
}
private CqlSession createSession() {
return new ClusterConfig().session();
}
@Configuration
static class ClusterConfig {
private static final String CASSANDRA_HOST = "127.0.0.1";
private static final int REQUEST_TIMEOUT_IN_SECONDS = 30;
| // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationTask.java
// public class MigrationTask {
// private static final Logger LOGGER = getLogger(MigrationTask.class);
//
// private final Database database;
// private final MigrationRepository repository;
// private final boolean withConsensus;
//
// /**
// * Creates a migration task that uses the given database and repository and no consensus
// * protocol enabled.
// *
// * @param database the database that should be migrated
// * @param repository the repository that contains the migration scripts
// */
// public MigrationTask(Database database, MigrationRepository repository) {
// this(database, repository, false);
// }
//
// /**
// * Creates a migration task that uses the given database and repository.
// *
// * @param database the database that should be migrated
// * @param repository the repository that contains the migration scripts
// * @param withConsensus if the migration should be handled by a single process at once, using LWT based leader election
// */
// public MigrationTask(Database database, MigrationRepository repository, boolean withConsensus) {
// this.database = notNull(database, "database");
// this.repository = notNull(repository, "repository");
// this.withConsensus = withConsensus;
// }
//
// /**
// * Start the actual migration. Take the version of the database, get all required migrations and execute them or do
// * nothing if the DB is already up to date.
// * <p>
// * At the end the underlying database instance is closed.
// *
// * @throws MigrationException if a migration fails
// */
// public void migrate() {
// if (databaseIsUpToDate()) {
// LOGGER.info(format("Keyspace %s is already up to date at version %d", database.getKeyspaceName(),
// database.getVersion()));
// database.close();
// return;
// }
//
// try {
// if (!instanceHasLead()) {
// return;
// }
// if (!databaseIsUpToDate()) {
// List<DbMigration> migrations = repository.getMigrationsSinceVersion(database.getVersion());
// migrations.forEach(database::execute);
// LOGGER.info(format("Migrated keyspace %s to version %d", database.getKeyspaceName(),
// database.getVersion()));
// }
// } finally {
// if (withConsensus) {
// database.removeLeadOnMigrations();
// }
// database.close();
// }
// }
//
// private boolean instanceHasLead() {
// return !withConsensus || database.takeLeadOnMigrations(repository.getLatestVersion());
// }
//
// private boolean databaseIsUpToDate() {
// return database.getVersion() >= repository.getLatestVersion();
// }
// }
//
// Path: cassandra-migration-spring-boot-starter/src/main/java/org/cognitor/cassandra/migration/spring/CassandraMigrationAutoConfiguration.java
// public static final String CQL_SESSION_BEAN_NAME = "cassandraMigrationCqlSession";
// Path: cassandra-migration-spring-boot-starter/src/test/java/org/cognitor/cassandra/migration/spring/CassandraMigrationAutoConfigurationTest.java
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.CqlSessionBuilder;
import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.cql.Row;
import org.cognitor.cassandra.migration.MigrationTask;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.List;
import static org.cognitor.cassandra.migration.spring.CassandraMigrationAutoConfiguration.CQL_SESSION_BEAN_NAME;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
new AnnotationConfigApplicationContext();
TestPropertyValues testValues = TestPropertyValues.of("cassandra.migration.keyspace-name:" + KEYSPACE)
.and("cassandra.migration.table-prefix:test");
testValues.applyTo(context);
context.register(ClusterConfig.class, CassandraMigrationAutoConfiguration.class);
context.refresh();
// WHEN
context.getBean(MigrationTask.class);
// THEN
CqlSession session = createSession();
List<Row> rows = session.execute("SELECT * FROM " + KEYSPACE + ".test_schema_migration").all();
assertThat(rows.size(), is(equalTo(1)));
Row migration = rows.get(0);
assertThat(migration.getBoolean("applied_successful"), is(true));
assertThat(migration.getInstant("executed_at"), is(not(nullValue())));
assertThat(migration.getString("script_name"), is(CoreMatchers.equalTo("001_create_person_table.cql")));
assertThat(migration.getString("script"), startsWith("CREATE TABLE"));
}
private CqlSession createSession() {
return new ClusterConfig().session();
}
@Configuration
static class ClusterConfig {
private static final String CASSANDRA_HOST = "127.0.0.1";
private static final int REQUEST_TIMEOUT_IN_SECONDS = 30;
| @Bean(name = CQL_SESSION_BEAN_NAME) |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationTask.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
| import org.slf4j.Logger;
import java.util.List;
import static java.lang.String.format;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.slf4j.LoggerFactory.getLogger; | package org.cognitor.cassandra.migration;
/**
* The migration task is managing the database migrations. It checks which
* schema version is in the database and retrieves the migrations that
* need to be applied from the repository. Those migrations are than
* executed against the database.
*
* @author Patrick Kranz
*/
public class MigrationTask {
private static final Logger LOGGER = getLogger(MigrationTask.class);
private final Database database;
private final MigrationRepository repository;
private final boolean withConsensus;
/**
* Creates a migration task that uses the given database and repository and no consensus
* protocol enabled.
*
* @param database the database that should be migrated
* @param repository the repository that contains the migration scripts
*/
public MigrationTask(Database database, MigrationRepository repository) {
this(database, repository, false);
}
/**
* Creates a migration task that uses the given database and repository.
*
* @param database the database that should be migrated
* @param repository the repository that contains the migration scripts
* @param withConsensus if the migration should be handled by a single process at once, using LWT based leader election
*/
public MigrationTask(Database database, MigrationRepository repository, boolean withConsensus) { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationTask.java
import org.slf4j.Logger;
import java.util.List;
import static java.lang.String.format;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.slf4j.LoggerFactory.getLogger;
package org.cognitor.cassandra.migration;
/**
* The migration task is managing the database migrations. It checks which
* schema version is in the database and retrieves the migrations that
* need to be applied from the repository. Those migrations are than
* executed against the database.
*
* @author Patrick Kranz
*/
public class MigrationTask {
private static final Logger LOGGER = getLogger(MigrationTask.class);
private final Database database;
private final MigrationRepository repository;
private final boolean withConsensus;
/**
* Creates a migration task that uses the given database and repository and no consensus
* protocol enabled.
*
* @param database the database that should be migrated
* @param repository the repository that contains the migration scripts
*/
public MigrationTask(Database database, MigrationRepository repository) {
this(database, repository, false);
}
/**
* Creates a migration task that uses the given database and repository.
*
* @param database the database that should be migrated
* @param repository the repository that contains the migration scripts
* @param withConsensus if the migration should be handled by a single process at once, using LWT based leader election
*/
public MigrationTask(Database database, MigrationRepository repository, boolean withConsensus) { | this.database = notNull(database, "database"); |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/collector/FailOnDuplicatesCollector.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationException.java
// public class MigrationException extends RuntimeException {
// private final String scriptName;
// private final String statement;
//
// public MigrationException(String message, String scriptName) {
// this(message, null, scriptName);
// }
//
// public MigrationException(String message, Throwable cause) {
// this(message, cause, null, null);
// }
//
// public MigrationException(String message, Throwable cause, String scriptName) {
// this(message, cause, scriptName, null);
// }
//
// public MigrationException(String message, Throwable cause, String scriptName, String statement) {
// super(message, cause);
// this.scriptName = scriptName;
// this.statement = statement;
// }
//
// /**
// * The name of the script that was involved in the error. Usually
// * the script that contains a faulty statement. If the process did
// * not arrive yet at script execution this will be null.
// *
// * @return the name of the failing script or null if there was a different kind of error
// */
// public String getScriptName() {
// return scriptName;
// }
//
// /**
// * The statement that caused the migration to fail. This
// * is helpful in case there is more than one statement inside a script.
// *
// * @return the failing statement or null if the exception was not thrown
// * during statement execution
// */
// public String getStatement() {
// return statement;
// }
// }
| import org.cognitor.cassandra.migration.MigrationException;
import java.util.*;
import static java.lang.String.format; | package org.cognitor.cassandra.migration.collector;
/**
* This strategy throws a {@link MigrationException} when there are two different
* migration scripts with the same version inside the repository. It will fail immediately
* and the collector process is interrupted.
*
* This is the default script collection strategy as it is a common problem in
* projects with many developers or branches.
*
* @author Patrick Kranz
*/
public class FailOnDuplicatesCollector implements ScriptCollector {
private final List<ScriptFile> scripts = new ArrayList<>();
private final Set<Integer> versions = new HashSet<>();
/**
* {@inheritDoc}
*
* Checks for every <code>scriptFile</code> that was added if there was
* already a script with the same version added. Throws an exception of
* it is the case.
*
* @param scriptFile an object containing information about the script. Never null.
* @throws MigrationException if a two different scripts with the same version are added
*/
@Override
public void collect(ScriptFile scriptFile) {
if (!versions.contains(scriptFile.getVersion())) {
scripts.add(scriptFile);
versions.add(scriptFile.getVersion());
} else { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationException.java
// public class MigrationException extends RuntimeException {
// private final String scriptName;
// private final String statement;
//
// public MigrationException(String message, String scriptName) {
// this(message, null, scriptName);
// }
//
// public MigrationException(String message, Throwable cause) {
// this(message, cause, null, null);
// }
//
// public MigrationException(String message, Throwable cause, String scriptName) {
// this(message, cause, scriptName, null);
// }
//
// public MigrationException(String message, Throwable cause, String scriptName, String statement) {
// super(message, cause);
// this.scriptName = scriptName;
// this.statement = statement;
// }
//
// /**
// * The name of the script that was involved in the error. Usually
// * the script that contains a faulty statement. If the process did
// * not arrive yet at script execution this will be null.
// *
// * @return the name of the failing script or null if there was a different kind of error
// */
// public String getScriptName() {
// return scriptName;
// }
//
// /**
// * The statement that caused the migration to fail. This
// * is helpful in case there is more than one statement inside a script.
// *
// * @return the failing statement or null if the exception was not thrown
// * during statement execution
// */
// public String getStatement() {
// return statement;
// }
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/collector/FailOnDuplicatesCollector.java
import org.cognitor.cassandra.migration.MigrationException;
import java.util.*;
import static java.lang.String.format;
package org.cognitor.cassandra.migration.collector;
/**
* This strategy throws a {@link MigrationException} when there are two different
* migration scripts with the same version inside the repository. It will fail immediately
* and the collector process is interrupted.
*
* This is the default script collection strategy as it is a common problem in
* projects with many developers or branches.
*
* @author Patrick Kranz
*/
public class FailOnDuplicatesCollector implements ScriptCollector {
private final List<ScriptFile> scripts = new ArrayList<>();
private final Set<Integer> versions = new HashSet<>();
/**
* {@inheritDoc}
*
* Checks for every <code>scriptFile</code> that was added if there was
* already a script with the same version added. Throws an exception of
* it is the case.
*
* @param scriptFile an object containing information about the script. Never null.
* @throws MigrationException if a two different scripts with the same version are added
*/
@Override
public void collect(ScriptFile scriptFile) {
if (!versions.contains(scriptFile.getVersion())) {
scripts.add(scriptFile);
versions.add(scriptFile.getVersion());
} else { | throw new MigrationException( |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/Keyspace.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration.keyspace;
/**
* This represents the definition of a key space and is basically
* a builder for the CQL statement that is required to create a keyspace
* before any migration can be executed.
*
* @author Patrick Kranz
*/
public class Keyspace {
private final String keyspaceName;
private boolean durableWrites;
private ReplicationStrategy replicationStrategy;
/**
* This creates a new instance of a keyspace using the provided keyspace name. It by default
* uses a {@link SimpleStrategy} for replication and sets durable writes to <code>true</code>.
* These default values can be overwritten by the provided methods.
*
* @param keyspaceName the name of the keyspace to be used.
*/
public Keyspace(String keyspaceName) { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/Keyspace.java
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration.keyspace;
/**
* This represents the definition of a key space and is basically
* a builder for the CQL statement that is required to create a keyspace
* before any migration can be executed.
*
* @author Patrick Kranz
*/
public class Keyspace {
private final String keyspaceName;
private boolean durableWrites;
private ReplicationStrategy replicationStrategy;
/**
* This creates a new instance of a keyspace using the provided keyspace name. It by default
* uses a {@link SimpleStrategy} for replication and sets durable writes to <code>true</code>.
* These default values can be overwritten by the provided methods.
*
* @param keyspaceName the name of the keyspace to be used.
*/
public Keyspace(String keyspaceName) { | this.keyspaceName = notNullOrEmpty(keyspaceName, "keyspaceName"); |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/Keyspace.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration.keyspace;
/**
* This represents the definition of a key space and is basically
* a builder for the CQL statement that is required to create a keyspace
* before any migration can be executed.
*
* @author Patrick Kranz
*/
public class Keyspace {
private final String keyspaceName;
private boolean durableWrites;
private ReplicationStrategy replicationStrategy;
/**
* This creates a new instance of a keyspace using the provided keyspace name. It by default
* uses a {@link SimpleStrategy} for replication and sets durable writes to <code>true</code>.
* These default values can be overwritten by the provided methods.
*
* @param keyspaceName the name of the keyspace to be used.
*/
public Keyspace(String keyspaceName) {
this.keyspaceName = notNullOrEmpty(keyspaceName, "keyspaceName");
this.replicationStrategy = new SimpleStrategy();
this.durableWrites = true;
}
public String getKeyspaceName() {
return keyspaceName;
}
/**
* Sets durable writes to false and by this bypass
* the commit log for write operations in this keyspace.
* This behavior is not recommended and should not be done
* with SimpleStrategy replication.
*
* @return the current Keyspace instance
*/
public Keyspace withoutDurableWrites() {
this.durableWrites = false;
return this;
}
public Keyspace with(ReplicationStrategy replicationStrategy) { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/Keyspace.java
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration.keyspace;
/**
* This represents the definition of a key space and is basically
* a builder for the CQL statement that is required to create a keyspace
* before any migration can be executed.
*
* @author Patrick Kranz
*/
public class Keyspace {
private final String keyspaceName;
private boolean durableWrites;
private ReplicationStrategy replicationStrategy;
/**
* This creates a new instance of a keyspace using the provided keyspace name. It by default
* uses a {@link SimpleStrategy} for replication and sets durable writes to <code>true</code>.
* These default values can be overwritten by the provided methods.
*
* @param keyspaceName the name of the keyspace to be used.
*/
public Keyspace(String keyspaceName) {
this.keyspaceName = notNullOrEmpty(keyspaceName, "keyspaceName");
this.replicationStrategy = new SimpleStrategy();
this.durableWrites = true;
}
public String getKeyspaceName() {
return keyspaceName;
}
/**
* Sets durable writes to false and by this bypass
* the commit log for write operations in this keyspace.
* This behavior is not recommended and should not be done
* with SimpleStrategy replication.
*
* @return the current Keyspace instance
*/
public Keyspace withoutDurableWrites() {
this.durableWrites = false;
return this;
}
public Keyspace with(ReplicationStrategy replicationStrategy) { | this.replicationStrategy = notNull(replicationStrategy, "replicationStrategy"); |
patka/cassandra-migration | cassandra-migration/src/test/java/org/cognitor/cassandra/migration/collector/FailOnDuplicatesCollectorTest.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationException.java
// public class MigrationException extends RuntimeException {
// private final String scriptName;
// private final String statement;
//
// public MigrationException(String message, String scriptName) {
// this(message, null, scriptName);
// }
//
// public MigrationException(String message, Throwable cause) {
// this(message, cause, null, null);
// }
//
// public MigrationException(String message, Throwable cause, String scriptName) {
// this(message, cause, scriptName, null);
// }
//
// public MigrationException(String message, Throwable cause, String scriptName, String statement) {
// super(message, cause);
// this.scriptName = scriptName;
// this.statement = statement;
// }
//
// /**
// * The name of the script that was involved in the error. Usually
// * the script that contains a faulty statement. If the process did
// * not arrive yet at script execution this will be null.
// *
// * @return the name of the failing script or null if there was a different kind of error
// */
// public String getScriptName() {
// return scriptName;
// }
//
// /**
// * The statement that caused the migration to fail. This
// * is helpful in case there is more than one statement inside a script.
// *
// * @return the failing statement or null if the exception was not thrown
// * during statement execution
// */
// public String getStatement() {
// return statement;
// }
// }
| import org.cognitor.cassandra.migration.MigrationException;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.MatcherAssert.assertThat; | package org.cognitor.cassandra.migration.collector;
/**
* @author Patrick Kranz
*/
public class FailOnDuplicatesCollectorTest {
private ScriptCollector scriptCollector;
@Before
public void before() {
this.scriptCollector = new FailOnDuplicatesCollector();
}
@Test
public void shouldReturnAllScriptsWhenNoDuplicateScriptFileGiven() {
scriptCollector.collect(new ScriptFile(0, "/0_init.cql", "init.cql"));
scriptCollector.collect(new ScriptFile(1, "/1_add-table.cql", "add_table.cql"));
assertThat(scriptCollector.getScriptFiles().size(), is(equalTo(2)));
}
| // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationException.java
// public class MigrationException extends RuntimeException {
// private final String scriptName;
// private final String statement;
//
// public MigrationException(String message, String scriptName) {
// this(message, null, scriptName);
// }
//
// public MigrationException(String message, Throwable cause) {
// this(message, cause, null, null);
// }
//
// public MigrationException(String message, Throwable cause, String scriptName) {
// this(message, cause, scriptName, null);
// }
//
// public MigrationException(String message, Throwable cause, String scriptName, String statement) {
// super(message, cause);
// this.scriptName = scriptName;
// this.statement = statement;
// }
//
// /**
// * The name of the script that was involved in the error. Usually
// * the script that contains a faulty statement. If the process did
// * not arrive yet at script execution this will be null.
// *
// * @return the name of the failing script or null if there was a different kind of error
// */
// public String getScriptName() {
// return scriptName;
// }
//
// /**
// * The statement that caused the migration to fail. This
// * is helpful in case there is more than one statement inside a script.
// *
// * @return the failing statement or null if the exception was not thrown
// * during statement execution
// */
// public String getStatement() {
// return statement;
// }
// }
// Path: cassandra-migration/src/test/java/org/cognitor/cassandra/migration/collector/FailOnDuplicatesCollectorTest.java
import org.cognitor.cassandra.migration.MigrationException;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.MatcherAssert.assertThat;
package org.cognitor.cassandra.migration.collector;
/**
* @author Patrick Kranz
*/
public class FailOnDuplicatesCollectorTest {
private ScriptCollector scriptCollector;
@Before
public void before() {
this.scriptCollector = new FailOnDuplicatesCollector();
}
@Test
public void shouldReturnAllScriptsWhenNoDuplicateScriptFileGiven() {
scriptCollector.collect(new ScriptFile(0, "/0_init.cql", "init.cql"));
scriptCollector.collect(new ScriptFile(1, "/1_add-table.cql", "add_table.cql"));
assertThat(scriptCollector.getScriptFiles().size(), is(equalTo(2)));
}
| @Test(expected = MigrationException.class) |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/NetworkStrategy.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import java.util.HashMap;
import java.util.Map;
import static java.lang.String.join;
import static java.util.Collections.unmodifiableMap;
import static java.util.stream.Collectors.toSet;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration.keyspace;
/**
* @author Patrick Kranz
*/
public class NetworkStrategy implements ReplicationStrategy {
private final Map<String, Integer> dataCenters = new HashMap<>();
@Override
public String getName() {
return "NetworkTopologyStrategy";
}
@Override
public String createCqlStatement() {
if (getDataCenters().isEmpty()) {
throw new IllegalStateException("There has to be at least one datacenter in order to use NetworkTopologyStrategy.");
}
StringBuilder builder = new StringBuilder();
builder.append("{")
.append("'class':'").append(getName()).append("',");
builder.append(join(",",
dataCenters.keySet().stream().map(dc -> "'" + dc + "':" + dataCenters.get(dc))
.collect(toSet())));
builder.append("}");
return builder.toString();
}
public NetworkStrategy with(String datacenter, int replicationFactor) { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/NetworkStrategy.java
import java.util.HashMap;
import java.util.Map;
import static java.lang.String.join;
import static java.util.Collections.unmodifiableMap;
import static java.util.stream.Collectors.toSet;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration.keyspace;
/**
* @author Patrick Kranz
*/
public class NetworkStrategy implements ReplicationStrategy {
private final Map<String, Integer> dataCenters = new HashMap<>();
@Override
public String getName() {
return "NetworkTopologyStrategy";
}
@Override
public String createCqlStatement() {
if (getDataCenters().isEmpty()) {
throw new IllegalStateException("There has to be at least one datacenter in order to use NetworkTopologyStrategy.");
}
StringBuilder builder = new StringBuilder();
builder.append("{")
.append("'class':'").append(getName()).append("',");
builder.append(join(",",
dataCenters.keySet().stream().map(dc -> "'" + dc + "':" + dataCenters.get(dc))
.collect(toSet())));
builder.append("}");
return builder.toString();
}
public NetworkStrategy with(String datacenter, int replicationFactor) { | notNullOrEmpty(datacenter, "datacenter"); |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationConfiguration.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/Keyspace.java
// public class Keyspace {
// private final String keyspaceName;
// private boolean durableWrites;
// private ReplicationStrategy replicationStrategy;
//
// /**
// * This creates a new instance of a keyspace using the provided keyspace name. It by default
// * uses a {@link SimpleStrategy} for replication and sets durable writes to <code>true</code>.
// * These default values can be overwritten by the provided methods.
// *
// * @param keyspaceName the name of the keyspace to be used.
// */
// public Keyspace(String keyspaceName) {
// this.keyspaceName = notNullOrEmpty(keyspaceName, "keyspaceName");
// this.replicationStrategy = new SimpleStrategy();
// this.durableWrites = true;
// }
//
// public String getKeyspaceName() {
// return keyspaceName;
// }
//
// /**
// * Sets durable writes to false and by this bypass
// * the commit log for write operations in this keyspace.
// * This behavior is not recommended and should not be done
// * with SimpleStrategy replication.
// *
// * @return the current Keyspace instance
// */
// public Keyspace withoutDurableWrites() {
// this.durableWrites = false;
// return this;
// }
//
// public Keyspace with(ReplicationStrategy replicationStrategy) {
// this.replicationStrategy = notNull(replicationStrategy, "replicationStrategy");
// return this;
// }
//
// public boolean isDurableWrites() {
// return durableWrites;
// }
//
// public ReplicationStrategy getReplicationStrategy() {
// return replicationStrategy;
// }
//
// public String getCqlStatement() {
// StringBuilder builder = new StringBuilder(60);
// builder.append("CREATE KEYSPACE IF NOT EXISTS ")
// .append(getKeyspaceName())
// .append(" WITH REPLICATION = ")
// .append(getReplicationStrategy().createCqlStatement())
// .append(" AND DURABLE_WRITES = ")
// .append(Boolean.toString(isDurableWrites()));
// return builder.toString();
// }
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import org.cognitor.cassandra.migration.keyspace.Keyspace;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration;
/**
* MigrationConfiguration contains the required settings for the {@link Database} to be
* created and for later execution. It is the central place to modify the behavior of the
* migration execution.
*
* Currently, the only required parameter is the keyspace name. Alternatively the instance
* of the keyspace can be set as well as this contains the name. Only use one or the other
* as internally it will always result in an instance of {@link Keyspace} meaning, if you
* set an instance of {@link Keyspace} with a non default keyspace configuration and then
* call <code>setKeyspaceName</code> separately, your non default keyspace configuration
* will be lost.
*/
public class MigrationConfiguration {
public final String EMPTY_TABLE_PREFIX = "";
private String tablePrefix = EMPTY_TABLE_PREFIX; | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/Keyspace.java
// public class Keyspace {
// private final String keyspaceName;
// private boolean durableWrites;
// private ReplicationStrategy replicationStrategy;
//
// /**
// * This creates a new instance of a keyspace using the provided keyspace name. It by default
// * uses a {@link SimpleStrategy} for replication and sets durable writes to <code>true</code>.
// * These default values can be overwritten by the provided methods.
// *
// * @param keyspaceName the name of the keyspace to be used.
// */
// public Keyspace(String keyspaceName) {
// this.keyspaceName = notNullOrEmpty(keyspaceName, "keyspaceName");
// this.replicationStrategy = new SimpleStrategy();
// this.durableWrites = true;
// }
//
// public String getKeyspaceName() {
// return keyspaceName;
// }
//
// /**
// * Sets durable writes to false and by this bypass
// * the commit log for write operations in this keyspace.
// * This behavior is not recommended and should not be done
// * with SimpleStrategy replication.
// *
// * @return the current Keyspace instance
// */
// public Keyspace withoutDurableWrites() {
// this.durableWrites = false;
// return this;
// }
//
// public Keyspace with(ReplicationStrategy replicationStrategy) {
// this.replicationStrategy = notNull(replicationStrategy, "replicationStrategy");
// return this;
// }
//
// public boolean isDurableWrites() {
// return durableWrites;
// }
//
// public ReplicationStrategy getReplicationStrategy() {
// return replicationStrategy;
// }
//
// public String getCqlStatement() {
// StringBuilder builder = new StringBuilder(60);
// builder.append("CREATE KEYSPACE IF NOT EXISTS ")
// .append(getKeyspaceName())
// .append(" WITH REPLICATION = ")
// .append(getReplicationStrategy().createCqlStatement())
// .append(" AND DURABLE_WRITES = ")
// .append(Boolean.toString(isDurableWrites()));
// return builder.toString();
// }
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationConfiguration.java
import org.cognitor.cassandra.migration.keyspace.Keyspace;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration;
/**
* MigrationConfiguration contains the required settings for the {@link Database} to be
* created and for later execution. It is the central place to modify the behavior of the
* migration execution.
*
* Currently, the only required parameter is the keyspace name. Alternatively the instance
* of the keyspace can be set as well as this contains the name. Only use one or the other
* as internally it will always result in an instance of {@link Keyspace} meaning, if you
* set an instance of {@link Keyspace} with a non default keyspace configuration and then
* call <code>setKeyspaceName</code> separately, your non default keyspace configuration
* will be lost.
*/
public class MigrationConfiguration {
public final String EMPTY_TABLE_PREFIX = "";
private String tablePrefix = EMPTY_TABLE_PREFIX; | private Keyspace keyspace; |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationConfiguration.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/Keyspace.java
// public class Keyspace {
// private final String keyspaceName;
// private boolean durableWrites;
// private ReplicationStrategy replicationStrategy;
//
// /**
// * This creates a new instance of a keyspace using the provided keyspace name. It by default
// * uses a {@link SimpleStrategy} for replication and sets durable writes to <code>true</code>.
// * These default values can be overwritten by the provided methods.
// *
// * @param keyspaceName the name of the keyspace to be used.
// */
// public Keyspace(String keyspaceName) {
// this.keyspaceName = notNullOrEmpty(keyspaceName, "keyspaceName");
// this.replicationStrategy = new SimpleStrategy();
// this.durableWrites = true;
// }
//
// public String getKeyspaceName() {
// return keyspaceName;
// }
//
// /**
// * Sets durable writes to false and by this bypass
// * the commit log for write operations in this keyspace.
// * This behavior is not recommended and should not be done
// * with SimpleStrategy replication.
// *
// * @return the current Keyspace instance
// */
// public Keyspace withoutDurableWrites() {
// this.durableWrites = false;
// return this;
// }
//
// public Keyspace with(ReplicationStrategy replicationStrategy) {
// this.replicationStrategy = notNull(replicationStrategy, "replicationStrategy");
// return this;
// }
//
// public boolean isDurableWrites() {
// return durableWrites;
// }
//
// public ReplicationStrategy getReplicationStrategy() {
// return replicationStrategy;
// }
//
// public String getCqlStatement() {
// StringBuilder builder = new StringBuilder(60);
// builder.append("CREATE KEYSPACE IF NOT EXISTS ")
// .append(getKeyspaceName())
// .append(" WITH REPLICATION = ")
// .append(getReplicationStrategy().createCqlStatement())
// .append(" AND DURABLE_WRITES = ")
// .append(Boolean.toString(isDurableWrites()));
// return builder.toString();
// }
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import org.cognitor.cassandra.migration.keyspace.Keyspace;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration;
/**
* MigrationConfiguration contains the required settings for the {@link Database} to be
* created and for later execution. It is the central place to modify the behavior of the
* migration execution.
*
* Currently, the only required parameter is the keyspace name. Alternatively the instance
* of the keyspace can be set as well as this contains the name. Only use one or the other
* as internally it will always result in an instance of {@link Keyspace} meaning, if you
* set an instance of {@link Keyspace} with a non default keyspace configuration and then
* call <code>setKeyspaceName</code> separately, your non default keyspace configuration
* will be lost.
*/
public class MigrationConfiguration {
public final String EMPTY_TABLE_PREFIX = "";
private String tablePrefix = EMPTY_TABLE_PREFIX;
private Keyspace keyspace;
private String executionProfile;
/**
* Set the name of the keyspace to be used. This is just a shortcut for
* <code>setKeyspace(new Keyspace(keyspaceName))</code>.
*
* @param keyspaceName the name of the keyspace. Must not be null or empty.
* @return this instance of the <code>MigrationConfiguration</code>. Never null.
*/
public MigrationConfiguration withKeyspaceName(String keyspaceName) { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/Keyspace.java
// public class Keyspace {
// private final String keyspaceName;
// private boolean durableWrites;
// private ReplicationStrategy replicationStrategy;
//
// /**
// * This creates a new instance of a keyspace using the provided keyspace name. It by default
// * uses a {@link SimpleStrategy} for replication and sets durable writes to <code>true</code>.
// * These default values can be overwritten by the provided methods.
// *
// * @param keyspaceName the name of the keyspace to be used.
// */
// public Keyspace(String keyspaceName) {
// this.keyspaceName = notNullOrEmpty(keyspaceName, "keyspaceName");
// this.replicationStrategy = new SimpleStrategy();
// this.durableWrites = true;
// }
//
// public String getKeyspaceName() {
// return keyspaceName;
// }
//
// /**
// * Sets durable writes to false and by this bypass
// * the commit log for write operations in this keyspace.
// * This behavior is not recommended and should not be done
// * with SimpleStrategy replication.
// *
// * @return the current Keyspace instance
// */
// public Keyspace withoutDurableWrites() {
// this.durableWrites = false;
// return this;
// }
//
// public Keyspace with(ReplicationStrategy replicationStrategy) {
// this.replicationStrategy = notNull(replicationStrategy, "replicationStrategy");
// return this;
// }
//
// public boolean isDurableWrites() {
// return durableWrites;
// }
//
// public ReplicationStrategy getReplicationStrategy() {
// return replicationStrategy;
// }
//
// public String getCqlStatement() {
// StringBuilder builder = new StringBuilder(60);
// builder.append("CREATE KEYSPACE IF NOT EXISTS ")
// .append(getKeyspaceName())
// .append(" WITH REPLICATION = ")
// .append(getReplicationStrategy().createCqlStatement())
// .append(" AND DURABLE_WRITES = ")
// .append(Boolean.toString(isDurableWrites()));
// return builder.toString();
// }
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationConfiguration.java
import org.cognitor.cassandra.migration.keyspace.Keyspace;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration;
/**
* MigrationConfiguration contains the required settings for the {@link Database} to be
* created and for later execution. It is the central place to modify the behavior of the
* migration execution.
*
* Currently, the only required parameter is the keyspace name. Alternatively the instance
* of the keyspace can be set as well as this contains the name. Only use one or the other
* as internally it will always result in an instance of {@link Keyspace} meaning, if you
* set an instance of {@link Keyspace} with a non default keyspace configuration and then
* call <code>setKeyspaceName</code> separately, your non default keyspace configuration
* will be lost.
*/
public class MigrationConfiguration {
public final String EMPTY_TABLE_PREFIX = "";
private String tablePrefix = EMPTY_TABLE_PREFIX;
private Keyspace keyspace;
private String executionProfile;
/**
* Set the name of the keyspace to be used. This is just a shortcut for
* <code>setKeyspace(new Keyspace(keyspaceName))</code>.
*
* @param keyspaceName the name of the keyspace. Must not be null or empty.
* @return this instance of the <code>MigrationConfiguration</code>. Never null.
*/
public MigrationConfiguration withKeyspaceName(String keyspaceName) { | this.keyspace = new Keyspace(notNullOrEmpty(keyspaceName, "keyspaceName")); |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationConfiguration.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/Keyspace.java
// public class Keyspace {
// private final String keyspaceName;
// private boolean durableWrites;
// private ReplicationStrategy replicationStrategy;
//
// /**
// * This creates a new instance of a keyspace using the provided keyspace name. It by default
// * uses a {@link SimpleStrategy} for replication and sets durable writes to <code>true</code>.
// * These default values can be overwritten by the provided methods.
// *
// * @param keyspaceName the name of the keyspace to be used.
// */
// public Keyspace(String keyspaceName) {
// this.keyspaceName = notNullOrEmpty(keyspaceName, "keyspaceName");
// this.replicationStrategy = new SimpleStrategy();
// this.durableWrites = true;
// }
//
// public String getKeyspaceName() {
// return keyspaceName;
// }
//
// /**
// * Sets durable writes to false and by this bypass
// * the commit log for write operations in this keyspace.
// * This behavior is not recommended and should not be done
// * with SimpleStrategy replication.
// *
// * @return the current Keyspace instance
// */
// public Keyspace withoutDurableWrites() {
// this.durableWrites = false;
// return this;
// }
//
// public Keyspace with(ReplicationStrategy replicationStrategy) {
// this.replicationStrategy = notNull(replicationStrategy, "replicationStrategy");
// return this;
// }
//
// public boolean isDurableWrites() {
// return durableWrites;
// }
//
// public ReplicationStrategy getReplicationStrategy() {
// return replicationStrategy;
// }
//
// public String getCqlStatement() {
// StringBuilder builder = new StringBuilder(60);
// builder.append("CREATE KEYSPACE IF NOT EXISTS ")
// .append(getKeyspaceName())
// .append(" WITH REPLICATION = ")
// .append(getReplicationStrategy().createCqlStatement())
// .append(" AND DURABLE_WRITES = ")
// .append(Boolean.toString(isDurableWrites()));
// return builder.toString();
// }
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import org.cognitor.cassandra.migration.keyspace.Keyspace;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration;
/**
* MigrationConfiguration contains the required settings for the {@link Database} to be
* created and for later execution. It is the central place to modify the behavior of the
* migration execution.
*
* Currently, the only required parameter is the keyspace name. Alternatively the instance
* of the keyspace can be set as well as this contains the name. Only use one or the other
* as internally it will always result in an instance of {@link Keyspace} meaning, if you
* set an instance of {@link Keyspace} with a non default keyspace configuration and then
* call <code>setKeyspaceName</code> separately, your non default keyspace configuration
* will be lost.
*/
public class MigrationConfiguration {
public final String EMPTY_TABLE_PREFIX = "";
private String tablePrefix = EMPTY_TABLE_PREFIX;
private Keyspace keyspace;
private String executionProfile;
/**
* Set the name of the keyspace to be used. This is just a shortcut for
* <code>setKeyspace(new Keyspace(keyspaceName))</code>.
*
* @param keyspaceName the name of the keyspace. Must not be null or empty.
* @return this instance of the <code>MigrationConfiguration</code>. Never null.
*/
public MigrationConfiguration withKeyspaceName(String keyspaceName) {
this.keyspace = new Keyspace(notNullOrEmpty(keyspaceName, "keyspaceName"));
return this;
}
/**
* Sets the prefix that will be used whenever a table is created to manage migration scripts.
* The default is no prefix which is done by using <code>EMPTY_TABLE_PREFIX</code>.
*
* @param tablePrefix the prefix to be used for any management table to be created. Can be null
* in which case the <code>EMPTY_TABLE_PREFIX</code> will be used.
* @return this instance of the <code>MigrationConfiguration</code>. Never null.
*/
public MigrationConfiguration withTablePrefix(String tablePrefix) {
if (tablePrefix == null) {
this.tablePrefix = EMPTY_TABLE_PREFIX;
return this;
}
this.tablePrefix = tablePrefix;
return this;
}
/**
* Sets the keyspace instance to be used for schema migration.
*
* @param keyspace the keyspace to be used for schema migration. Must not be null.
* @return this instance of the <code>MigrationConfiguration</code>. Never null.
*/
public MigrationConfiguration withKeyspace(Keyspace keyspace) { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/keyspace/Keyspace.java
// public class Keyspace {
// private final String keyspaceName;
// private boolean durableWrites;
// private ReplicationStrategy replicationStrategy;
//
// /**
// * This creates a new instance of a keyspace using the provided keyspace name. It by default
// * uses a {@link SimpleStrategy} for replication and sets durable writes to <code>true</code>.
// * These default values can be overwritten by the provided methods.
// *
// * @param keyspaceName the name of the keyspace to be used.
// */
// public Keyspace(String keyspaceName) {
// this.keyspaceName = notNullOrEmpty(keyspaceName, "keyspaceName");
// this.replicationStrategy = new SimpleStrategy();
// this.durableWrites = true;
// }
//
// public String getKeyspaceName() {
// return keyspaceName;
// }
//
// /**
// * Sets durable writes to false and by this bypass
// * the commit log for write operations in this keyspace.
// * This behavior is not recommended and should not be done
// * with SimpleStrategy replication.
// *
// * @return the current Keyspace instance
// */
// public Keyspace withoutDurableWrites() {
// this.durableWrites = false;
// return this;
// }
//
// public Keyspace with(ReplicationStrategy replicationStrategy) {
// this.replicationStrategy = notNull(replicationStrategy, "replicationStrategy");
// return this;
// }
//
// public boolean isDurableWrites() {
// return durableWrites;
// }
//
// public ReplicationStrategy getReplicationStrategy() {
// return replicationStrategy;
// }
//
// public String getCqlStatement() {
// StringBuilder builder = new StringBuilder(60);
// builder.append("CREATE KEYSPACE IF NOT EXISTS ")
// .append(getKeyspaceName())
// .append(" WITH REPLICATION = ")
// .append(getReplicationStrategy().createCqlStatement())
// .append(" AND DURABLE_WRITES = ")
// .append(Boolean.toString(isDurableWrites()));
// return builder.toString();
// }
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/MigrationConfiguration.java
import org.cognitor.cassandra.migration.keyspace.Keyspace;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration;
/**
* MigrationConfiguration contains the required settings for the {@link Database} to be
* created and for later execution. It is the central place to modify the behavior of the
* migration execution.
*
* Currently, the only required parameter is the keyspace name. Alternatively the instance
* of the keyspace can be set as well as this contains the name. Only use one or the other
* as internally it will always result in an instance of {@link Keyspace} meaning, if you
* set an instance of {@link Keyspace} with a non default keyspace configuration and then
* call <code>setKeyspaceName</code> separately, your non default keyspace configuration
* will be lost.
*/
public class MigrationConfiguration {
public final String EMPTY_TABLE_PREFIX = "";
private String tablePrefix = EMPTY_TABLE_PREFIX;
private Keyspace keyspace;
private String executionProfile;
/**
* Set the name of the keyspace to be used. This is just a shortcut for
* <code>setKeyspace(new Keyspace(keyspaceName))</code>.
*
* @param keyspaceName the name of the keyspace. Must not be null or empty.
* @return this instance of the <code>MigrationConfiguration</code>. Never null.
*/
public MigrationConfiguration withKeyspaceName(String keyspaceName) {
this.keyspace = new Keyspace(notNullOrEmpty(keyspaceName, "keyspaceName"));
return this;
}
/**
* Sets the prefix that will be used whenever a table is created to manage migration scripts.
* The default is no prefix which is done by using <code>EMPTY_TABLE_PREFIX</code>.
*
* @param tablePrefix the prefix to be used for any management table to be created. Can be null
* in which case the <code>EMPTY_TABLE_PREFIX</code> will be used.
* @return this instance of the <code>MigrationConfiguration</code>. Never null.
*/
public MigrationConfiguration withTablePrefix(String tablePrefix) {
if (tablePrefix == null) {
this.tablePrefix = EMPTY_TABLE_PREFIX;
return this;
}
this.tablePrefix = tablePrefix;
return this;
}
/**
* Sets the keyspace instance to be used for schema migration.
*
* @param keyspace the keyspace to be used for schema migration. Must not be null.
* @return this instance of the <code>MigrationConfiguration</code>. Never null.
*/
public MigrationConfiguration withKeyspace(Keyspace keyspace) { | this.keyspace = notNull(keyspace, "keyspace"); |
patka/cassandra-migration | cassandra-migration/src/test/java/org/cognitor/cassandra/migration/util/EnsureTest.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import org.junit.Test;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.MatcherAssert.assertThat; | package org.cognitor.cassandra.migration.util;
/**
* @author Patrick Kranz
*/
public class EnsureTest {
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionWhenNullObjectGiven() { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/test/java/org/cognitor/cassandra/migration/util/EnsureTest.java
import org.junit.Test;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
package org.cognitor.cassandra.migration.util;
/**
* @author Patrick Kranz
*/
public class EnsureTest {
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionWhenNullObjectGiven() { | notNull(null, "testArgument"); |
patka/cassandra-migration | cassandra-migration/src/test/java/org/cognitor/cassandra/migration/util/EnsureTest.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import org.junit.Test;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.MatcherAssert.assertThat; | package org.cognitor.cassandra.migration.util;
/**
* @author Patrick Kranz
*/
public class EnsureTest {
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionWhenNullObjectGiven() {
notNull(null, "testArgument");
}
@Test
public void shouldReturnObjectWhenNotNullObjectGiven() {
Object testObject = new Object();
assertThat(notNull(testObject, "testObject"), is(equalTo(testObject)));
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionWhenNullStringGiven() { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/test/java/org/cognitor/cassandra/migration/util/EnsureTest.java
import org.junit.Test;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
package org.cognitor.cassandra.migration.util;
/**
* @author Patrick Kranz
*/
public class EnsureTest {
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionWhenNullObjectGiven() {
notNull(null, "testArgument");
}
@Test
public void shouldReturnObjectWhenNotNullObjectGiven() {
Object testObject = new Object();
assertThat(notNull(testObject, "testObject"), is(equalTo(testObject)));
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionWhenNullStringGiven() { | notNullOrEmpty(null, "testString"); |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/scanner/ScannerRegistry.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import java.util.HashMap;
import java.util.Map;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration.scanner;
/**
* The <code>ScannerRegistry</code> is used to provide a {@link LocationScanner}
* depending on the scheme that is provided. This default implementation
* knows two types:
* <ul>
* <li>Jar scanning</li>
* <li>Filesystem scanning</li>
* </ul>
* In case the provided scheme is "jar", the {@link JarLocationScanner} is returned. For
* the scheme "file" the {@link FileSystemLocationScanner} is returned. If you want to include
* you own scanner implementation you can register it here with the appropriate
* scheme. If you need to overwrite on existing one you can do this as well by providing
* the scheme you want to overwrite. You can use the constants of this class for convenience.
*
* The scheme names are considered case-insensitive, therefore "JAR" and "jar" will return
* the same entry.
*
* @author Patrick Kranz
*/
public class ScannerRegistry {
/**
* The scheme used to register scanners for jar files
*/
public static final String JAR_SCHEME = "jar";
/**
* The scheme used to register scanners for file locations
*/
public static final String FILE_SCHEME = "file";
private final Map<String, LocationScanner> scanners;
public ScannerRegistry() {
this.scanners = new HashMap<>();
this.scanners.put(JAR_SCHEME, new JarLocationScanner());
this.scanners.put(FILE_SCHEME, new FileSystemLocationScanner());
}
/**
* Returns the correct implementation of a {@link LocationScanner}
* depending on the scheme or null of no scanner for this scheme is
* registered.
*
* @param scheme the scheme that should be supported
* @return {@link JarLocationScanner} if scheme is "jar", {@link FileSystemLocationScanner}
* if the scheme is "file" or null if an unknown scheme is given
* @throws IllegalArgumentException in case scheme is null or empty
*/
public LocationScanner getScanner(String scheme) { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/scanner/ScannerRegistry.java
import java.util.HashMap;
import java.util.Map;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration.scanner;
/**
* The <code>ScannerRegistry</code> is used to provide a {@link LocationScanner}
* depending on the scheme that is provided. This default implementation
* knows two types:
* <ul>
* <li>Jar scanning</li>
* <li>Filesystem scanning</li>
* </ul>
* In case the provided scheme is "jar", the {@link JarLocationScanner} is returned. For
* the scheme "file" the {@link FileSystemLocationScanner} is returned. If you want to include
* you own scanner implementation you can register it here with the appropriate
* scheme. If you need to overwrite on existing one you can do this as well by providing
* the scheme you want to overwrite. You can use the constants of this class for convenience.
*
* The scheme names are considered case-insensitive, therefore "JAR" and "jar" will return
* the same entry.
*
* @author Patrick Kranz
*/
public class ScannerRegistry {
/**
* The scheme used to register scanners for jar files
*/
public static final String JAR_SCHEME = "jar";
/**
* The scheme used to register scanners for file locations
*/
public static final String FILE_SCHEME = "file";
private final Map<String, LocationScanner> scanners;
public ScannerRegistry() {
this.scanners = new HashMap<>();
this.scanners.put(JAR_SCHEME, new JarLocationScanner());
this.scanners.put(FILE_SCHEME, new FileSystemLocationScanner());
}
/**
* Returns the correct implementation of a {@link LocationScanner}
* depending on the scheme or null of no scanner for this scheme is
* registered.
*
* @param scheme the scheme that should be supported
* @return {@link JarLocationScanner} if scheme is "jar", {@link FileSystemLocationScanner}
* if the scheme is "file" or null if an unknown scheme is given
* @throws IllegalArgumentException in case scheme is null or empty
*/
public LocationScanner getScanner(String scheme) { | notNullOrEmpty(scheme, "scheme"); |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/scanner/ScannerRegistry.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import java.util.HashMap;
import java.util.Map;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration.scanner;
/**
* The <code>ScannerRegistry</code> is used to provide a {@link LocationScanner}
* depending on the scheme that is provided. This default implementation
* knows two types:
* <ul>
* <li>Jar scanning</li>
* <li>Filesystem scanning</li>
* </ul>
* In case the provided scheme is "jar", the {@link JarLocationScanner} is returned. For
* the scheme "file" the {@link FileSystemLocationScanner} is returned. If you want to include
* you own scanner implementation you can register it here with the appropriate
* scheme. If you need to overwrite on existing one you can do this as well by providing
* the scheme you want to overwrite. You can use the constants of this class for convenience.
*
* The scheme names are considered case-insensitive, therefore "JAR" and "jar" will return
* the same entry.
*
* @author Patrick Kranz
*/
public class ScannerRegistry {
/**
* The scheme used to register scanners for jar files
*/
public static final String JAR_SCHEME = "jar";
/**
* The scheme used to register scanners for file locations
*/
public static final String FILE_SCHEME = "file";
private final Map<String, LocationScanner> scanners;
public ScannerRegistry() {
this.scanners = new HashMap<>();
this.scanners.put(JAR_SCHEME, new JarLocationScanner());
this.scanners.put(FILE_SCHEME, new FileSystemLocationScanner());
}
/**
* Returns the correct implementation of a {@link LocationScanner}
* depending on the scheme or null of no scanner for this scheme is
* registered.
*
* @param scheme the scheme that should be supported
* @return {@link JarLocationScanner} if scheme is "jar", {@link FileSystemLocationScanner}
* if the scheme is "file" or null if an unknown scheme is given
* @throws IllegalArgumentException in case scheme is null or empty
*/
public LocationScanner getScanner(String scheme) {
notNullOrEmpty(scheme, "scheme");
return this.scanners.get(scheme.toLowerCase());
}
/**
* Indicates of there is s {@link LocationScanner} registered for
* the given scheme.
*
* @param scheme the scheme for which a {@link LocationScanner} is required
* @return true if a scanner is registered, false otherwise
* @throws IllegalArgumentException in case scheme is null or empty
*/
public boolean supports(String scheme) {
notNullOrEmpty(scheme, "scheme");
return this.scanners.containsKey(scheme.toLowerCase());
}
/**
* Registers a new {@link LocationScanner}. If there is already one registered
* for the provided scheme, the registration will be updated.
*
* @param scheme the scheme for which the scanner can handle
* @param scanner the scanner implementation
* @throws IllegalArgumentException if scheme is null or empty or scanner is null
*/
public void register(String scheme, LocationScanner scanner) {
notNullOrEmpty(scheme, "scheme"); | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/scanner/ScannerRegistry.java
import java.util.HashMap;
import java.util.Map;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration.scanner;
/**
* The <code>ScannerRegistry</code> is used to provide a {@link LocationScanner}
* depending on the scheme that is provided. This default implementation
* knows two types:
* <ul>
* <li>Jar scanning</li>
* <li>Filesystem scanning</li>
* </ul>
* In case the provided scheme is "jar", the {@link JarLocationScanner} is returned. For
* the scheme "file" the {@link FileSystemLocationScanner} is returned. If you want to include
* you own scanner implementation you can register it here with the appropriate
* scheme. If you need to overwrite on existing one you can do this as well by providing
* the scheme you want to overwrite. You can use the constants of this class for convenience.
*
* The scheme names are considered case-insensitive, therefore "JAR" and "jar" will return
* the same entry.
*
* @author Patrick Kranz
*/
public class ScannerRegistry {
/**
* The scheme used to register scanners for jar files
*/
public static final String JAR_SCHEME = "jar";
/**
* The scheme used to register scanners for file locations
*/
public static final String FILE_SCHEME = "file";
private final Map<String, LocationScanner> scanners;
public ScannerRegistry() {
this.scanners = new HashMap<>();
this.scanners.put(JAR_SCHEME, new JarLocationScanner());
this.scanners.put(FILE_SCHEME, new FileSystemLocationScanner());
}
/**
* Returns the correct implementation of a {@link LocationScanner}
* depending on the scheme or null of no scanner for this scheme is
* registered.
*
* @param scheme the scheme that should be supported
* @return {@link JarLocationScanner} if scheme is "jar", {@link FileSystemLocationScanner}
* if the scheme is "file" or null if an unknown scheme is given
* @throws IllegalArgumentException in case scheme is null or empty
*/
public LocationScanner getScanner(String scheme) {
notNullOrEmpty(scheme, "scheme");
return this.scanners.get(scheme.toLowerCase());
}
/**
* Indicates of there is s {@link LocationScanner} registered for
* the given scheme.
*
* @param scheme the scheme for which a {@link LocationScanner} is required
* @return true if a scanner is registered, false otherwise
* @throws IllegalArgumentException in case scheme is null or empty
*/
public boolean supports(String scheme) {
notNullOrEmpty(scheme, "scheme");
return this.scanners.containsKey(scheme.toLowerCase());
}
/**
* Registers a new {@link LocationScanner}. If there is already one registered
* for the provided scheme, the registration will be updated.
*
* @param scheme the scheme for which the scanner can handle
* @param scanner the scanner implementation
* @throws IllegalArgumentException if scheme is null or empty or scanner is null
*/
public void register(String scheme, LocationScanner scanner) {
notNullOrEmpty(scheme, "scheme"); | notNull(scanner, "scanner"); |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/DbMigration.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration;
/**
* An object representing a database migration. Every script corresponds to one object of this class.
*
* @author Patrick Kranz
*/
class DbMigration {
private final String migrationScript;
private final String scriptName;
private final int version;
/**
* Creates a new instance based on the given information.
*
* @param scriptName the name of the script without the version part. Must not be null.
* @param version the schema version this migration will result to.
* @param migrationScript the migration steps in cql. Must not be null.
*/
public DbMigration(String scriptName, int version, String migrationScript) { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/DbMigration.java
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration;
/**
* An object representing a database migration. Every script corresponds to one object of this class.
*
* @author Patrick Kranz
*/
class DbMigration {
private final String migrationScript;
private final String scriptName;
private final int version;
/**
* Creates a new instance based on the given information.
*
* @param scriptName the name of the script without the version part. Must not be null.
* @param version the schema version this migration will result to.
* @param migrationScript the migration steps in cql. Must not be null.
*/
public DbMigration(String scriptName, int version, String migrationScript) { | this.migrationScript = notNull(migrationScript, "migrationScript"); |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/DbMigration.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration;
/**
* An object representing a database migration. Every script corresponds to one object of this class.
*
* @author Patrick Kranz
*/
class DbMigration {
private final String migrationScript;
private final String scriptName;
private final int version;
/**
* Creates a new instance based on the given information.
*
* @param scriptName the name of the script without the version part. Must not be null.
* @param version the schema version this migration will result to.
* @param migrationScript the migration steps in cql. Must not be null.
*/
public DbMigration(String scriptName, int version, String migrationScript) {
this.migrationScript = notNull(migrationScript, "migrationScript"); | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/DbMigration.java
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration;
/**
* An object representing a database migration. Every script corresponds to one object of this class.
*
* @author Patrick Kranz
*/
class DbMigration {
private final String migrationScript;
private final String scriptName;
private final int version;
/**
* Creates a new instance based on the given information.
*
* @param scriptName the name of the script without the version part. Must not be null.
* @param version the schema version this migration will result to.
* @param migrationScript the migration steps in cql. Must not be null.
*/
public DbMigration(String scriptName, int version, String migrationScript) {
this.migrationScript = notNull(migrationScript, "migrationScript"); | this.scriptName = notNullOrEmpty(scriptName, "scriptName"); |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/scanner/JarLocationScanner.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.Set;
import static java.util.Collections.emptyMap;
import static java.util.stream.Collectors.toSet;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration.scanner;
/**
* Scans a path within a compiled jar for resources that are inside this path.
*
* @author Pavel Borsky
*/
public class JarLocationScanner implements LocationScanner {
private static final Logger LOGGER = LoggerFactory.getLogger(JarLocationScanner.class);
/**
* {@inheritDoc}
*/
@Override
public Set<String> findResourceNames(String location, URI locationUri) throws IOException { | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/scanner/JarLocationScanner.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.Set;
import static java.util.Collections.emptyMap;
import static java.util.stream.Collectors.toSet;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration.scanner;
/**
* Scans a path within a compiled jar for resources that are inside this path.
*
* @author Pavel Borsky
*/
public class JarLocationScanner implements LocationScanner {
private static final Logger LOGGER = LoggerFactory.getLogger(JarLocationScanner.class);
/**
* {@inheritDoc}
*/
@Override
public Set<String> findResourceNames(String location, URI locationUri) throws IOException { | notNullOrEmpty(location, "location"); |
patka/cassandra-migration | cassandra-migration/src/main/java/org/cognitor/cassandra/migration/scanner/JarLocationScanner.java | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.Set;
import static java.util.Collections.emptyMap;
import static java.util.stream.Collectors.toSet;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty; | package org.cognitor.cassandra.migration.scanner;
/**
* Scans a path within a compiled jar for resources that are inside this path.
*
* @author Pavel Borsky
*/
public class JarLocationScanner implements LocationScanner {
private static final Logger LOGGER = LoggerFactory.getLogger(JarLocationScanner.class);
/**
* {@inheritDoc}
*/
@Override
public Set<String> findResourceNames(String location, URI locationUri) throws IOException {
notNullOrEmpty(location, "location"); | // Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static <T> T notNull(T argument, String argumentName) {
// if (argument == null) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null.");
// }
// return argument;
// }
//
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/util/Ensure.java
// public static String notNullOrEmpty(String argument, String argumentName) {
// if (argument == null || argument.trim().isEmpty()) {
// throw new IllegalArgumentException("Argument " + argumentName + " must not be null or empty.");
// }
// return argument;
// }
// Path: cassandra-migration/src/main/java/org/cognitor/cassandra/migration/scanner/JarLocationScanner.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.Set;
import static java.util.Collections.emptyMap;
import static java.util.stream.Collectors.toSet;
import static org.cognitor.cassandra.migration.util.Ensure.notNull;
import static org.cognitor.cassandra.migration.util.Ensure.notNullOrEmpty;
package org.cognitor.cassandra.migration.scanner;
/**
* Scans a path within a compiled jar for resources that are inside this path.
*
* @author Pavel Borsky
*/
public class JarLocationScanner implements LocationScanner {
private static final Logger LOGGER = LoggerFactory.getLogger(JarLocationScanner.class);
/**
* {@inheritDoc}
*/
@Override
public Set<String> findResourceNames(String location, URI locationUri) throws IOException {
notNullOrEmpty(location, "location"); | notNull(locationUri, "locationUri"); |
Fueled/flowr | sample/src/main/java/com/fueled/flowr/sample/FirstFragment.java | // Path: flowr/src/main/java/com/fueled/flowr/NavigationIconType.java
// public enum NavigationIconType {
// HIDDEN,
// HAMBURGER,
// BACK,
// CUSTOM
// }
//
// Path: sample/src/main/java/com/fueled/flowr/sample/core/AbstractFragment.java
// public abstract class AbstractFragment extends AbstractFlowrFragment {
//
// private Disposable fragmentResultSubscription;
//
// private String title;
//
// public abstract @LayoutRes int getLayoutId();
//
// protected abstract void setupView(View view);
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// View view = inflater.inflate(getLayoutId(), container, false);
// view.setClickable(true);
// setupView(view);
// return view;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// listenToResults();
//
// title = getString(R.string.app_name);
// getFlowr().syncScreenState();
// }
//
// protected Flowr getFlowr() {
// if (getActivity() != null && getActivity() instanceof AbstractActivity) {
// return ((AbstractActivity) getActivity()).getFlowr();
// }
//
// return null;
// }
//
// private void listenToResults() {
// removeFragmentResultSubscription();
// fragmentResultSubscription = FragmentResultPublisherImpl.getInstance()
// .observeResultsForFragment(getFragmentId(), new Consumer<ResultResponse>() {
// @Override
// public void accept(ResultResponse resultResponse) throws Exception {
// onFragmentResults(resultResponse.requestCode, resultResponse.resultCode,
// resultResponse.data);
// }
// });
// }
//
// private void removeFragmentResultSubscription() {
// if (fragmentResultSubscription != null && !fragmentResultSubscription.isDisposed()) {
// fragmentResultSubscription.dispose();
// }
// }
//
// @Override
// public String getTitle() {
// return title;
// }
// }
| import android.view.View;
import com.fueled.flowr.NavigationIconType;
import com.fueled.flowr.annotations.DeepLink;
import com.fueled.flowr.sample.core.AbstractFragment; | package com.fueled.flowr.sample;
/**
* Created by [email protected] on 18/05/2017.
* Copyright (c) 2017 Fueled. All rights reserved.
*/
@DeepLink(value = "/first")
public class FirstFragment extends AbstractFragment implements View.OnClickListener {
@Override
public int getLayoutId() {
return R.layout.fragment_first;
}
@Override
protected void setupView(View view) {
view.findViewById(R.id.add_stack_button).setOnClickListener(this);
}
@Override
public String getTitle() {
return "First Fragment";
}
@Override | // Path: flowr/src/main/java/com/fueled/flowr/NavigationIconType.java
// public enum NavigationIconType {
// HIDDEN,
// HAMBURGER,
// BACK,
// CUSTOM
// }
//
// Path: sample/src/main/java/com/fueled/flowr/sample/core/AbstractFragment.java
// public abstract class AbstractFragment extends AbstractFlowrFragment {
//
// private Disposable fragmentResultSubscription;
//
// private String title;
//
// public abstract @LayoutRes int getLayoutId();
//
// protected abstract void setupView(View view);
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// View view = inflater.inflate(getLayoutId(), container, false);
// view.setClickable(true);
// setupView(view);
// return view;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// listenToResults();
//
// title = getString(R.string.app_name);
// getFlowr().syncScreenState();
// }
//
// protected Flowr getFlowr() {
// if (getActivity() != null && getActivity() instanceof AbstractActivity) {
// return ((AbstractActivity) getActivity()).getFlowr();
// }
//
// return null;
// }
//
// private void listenToResults() {
// removeFragmentResultSubscription();
// fragmentResultSubscription = FragmentResultPublisherImpl.getInstance()
// .observeResultsForFragment(getFragmentId(), new Consumer<ResultResponse>() {
// @Override
// public void accept(ResultResponse resultResponse) throws Exception {
// onFragmentResults(resultResponse.requestCode, resultResponse.resultCode,
// resultResponse.data);
// }
// });
// }
//
// private void removeFragmentResultSubscription() {
// if (fragmentResultSubscription != null && !fragmentResultSubscription.isDisposed()) {
// fragmentResultSubscription.dispose();
// }
// }
//
// @Override
// public String getTitle() {
// return title;
// }
// }
// Path: sample/src/main/java/com/fueled/flowr/sample/FirstFragment.java
import android.view.View;
import com.fueled.flowr.NavigationIconType;
import com.fueled.flowr.annotations.DeepLink;
import com.fueled.flowr.sample.core.AbstractFragment;
package com.fueled.flowr.sample;
/**
* Created by [email protected] on 18/05/2017.
* Copyright (c) 2017 Fueled. All rights reserved.
*/
@DeepLink(value = "/first")
public class FirstFragment extends AbstractFragment implements View.OnClickListener {
@Override
public int getLayoutId() {
return R.layout.fragment_first;
}
@Override
protected void setupView(View view) {
view.findViewById(R.id.add_stack_button).setOnClickListener(this);
}
@Override
public String getTitle() {
return "First Fragment";
}
@Override | public NavigationIconType getNavigationIconType() { |
Fueled/flowr | sample/src/main/java/com/fueled/flowr/sample/HomeFragment.java | // Path: flowr/src/main/java/com/fueled/flowr/NavigationIconType.java
// public enum NavigationIconType {
// HIDDEN,
// HAMBURGER,
// BACK,
// CUSTOM
// }
//
// Path: sample/src/main/java/com/fueled/flowr/sample/core/AbstractFragment.java
// public abstract class AbstractFragment extends AbstractFlowrFragment {
//
// private Disposable fragmentResultSubscription;
//
// private String title;
//
// public abstract @LayoutRes int getLayoutId();
//
// protected abstract void setupView(View view);
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// View view = inflater.inflate(getLayoutId(), container, false);
// view.setClickable(true);
// setupView(view);
// return view;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// listenToResults();
//
// title = getString(R.string.app_name);
// getFlowr().syncScreenState();
// }
//
// protected Flowr getFlowr() {
// if (getActivity() != null && getActivity() instanceof AbstractActivity) {
// return ((AbstractActivity) getActivity()).getFlowr();
// }
//
// return null;
// }
//
// private void listenToResults() {
// removeFragmentResultSubscription();
// fragmentResultSubscription = FragmentResultPublisherImpl.getInstance()
// .observeResultsForFragment(getFragmentId(), new Consumer<ResultResponse>() {
// @Override
// public void accept(ResultResponse resultResponse) throws Exception {
// onFragmentResults(resultResponse.requestCode, resultResponse.resultCode,
// resultResponse.data);
// }
// });
// }
//
// private void removeFragmentResultSubscription() {
// if (fragmentResultSubscription != null && !fragmentResultSubscription.isDisposed()) {
// fragmentResultSubscription.dispose();
// }
// }
//
// @Override
// public String getTitle() {
// return title;
// }
// }
| import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.fueled.flowr.NavigationIconType;
import com.fueled.flowr.sample.core.AbstractFragment;
import com.fueled.flowr.sample.databinding.FragmentHomeBinding; | package com.fueled.flowr.sample;
/**
* Created by [email protected] on 13/02/2017.
* Copyright (c) 2017 Fueled. All rights reserved.
*/
public class HomeFragment extends AbstractFragment implements View.OnClickListener {
public static final int RC_STACK = 101;
public static int backStackIdentifier;
public static String targetFragmentId;
private FragmentHomeBinding binding;
@Override
public int getLayoutId() {
return R.layout.fragment_home;
}
@Override
protected void setupView(View view) {
binding = DataBindingUtil.bind(view);
binding.homeOpenViewButton.setOnClickListener(this);
binding.homeOpenLinkButton.setOnClickListener(this);
binding.homeOpenFirstButton.setOnClickListener(this);
}
@Override
public boolean onNavigationIconClick() {
return true;
}
@Override | // Path: flowr/src/main/java/com/fueled/flowr/NavigationIconType.java
// public enum NavigationIconType {
// HIDDEN,
// HAMBURGER,
// BACK,
// CUSTOM
// }
//
// Path: sample/src/main/java/com/fueled/flowr/sample/core/AbstractFragment.java
// public abstract class AbstractFragment extends AbstractFlowrFragment {
//
// private Disposable fragmentResultSubscription;
//
// private String title;
//
// public abstract @LayoutRes int getLayoutId();
//
// protected abstract void setupView(View view);
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// View view = inflater.inflate(getLayoutId(), container, false);
// view.setClickable(true);
// setupView(view);
// return view;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// listenToResults();
//
// title = getString(R.string.app_name);
// getFlowr().syncScreenState();
// }
//
// protected Flowr getFlowr() {
// if (getActivity() != null && getActivity() instanceof AbstractActivity) {
// return ((AbstractActivity) getActivity()).getFlowr();
// }
//
// return null;
// }
//
// private void listenToResults() {
// removeFragmentResultSubscription();
// fragmentResultSubscription = FragmentResultPublisherImpl.getInstance()
// .observeResultsForFragment(getFragmentId(), new Consumer<ResultResponse>() {
// @Override
// public void accept(ResultResponse resultResponse) throws Exception {
// onFragmentResults(resultResponse.requestCode, resultResponse.resultCode,
// resultResponse.data);
// }
// });
// }
//
// private void removeFragmentResultSubscription() {
// if (fragmentResultSubscription != null && !fragmentResultSubscription.isDisposed()) {
// fragmentResultSubscription.dispose();
// }
// }
//
// @Override
// public String getTitle() {
// return title;
// }
// }
// Path: sample/src/main/java/com/fueled/flowr/sample/HomeFragment.java
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.fueled.flowr.NavigationIconType;
import com.fueled.flowr.sample.core.AbstractFragment;
import com.fueled.flowr.sample.databinding.FragmentHomeBinding;
package com.fueled.flowr.sample;
/**
* Created by [email protected] on 13/02/2017.
* Copyright (c) 2017 Fueled. All rights reserved.
*/
public class HomeFragment extends AbstractFragment implements View.OnClickListener {
public static final int RC_STACK = 101;
public static int backStackIdentifier;
public static String targetFragmentId;
private FragmentHomeBinding binding;
@Override
public int getLayoutId() {
return R.layout.fragment_home;
}
@Override
protected void setupView(View view) {
binding = DataBindingUtil.bind(view);
binding.homeOpenViewButton.setOnClickListener(this);
binding.homeOpenLinkButton.setOnClickListener(this);
binding.homeOpenFirstButton.setOnClickListener(this);
}
@Override
public boolean onNavigationIconClick() {
return true;
}
@Override | public NavigationIconType getNavigationIconType() { |
Fueled/flowr | flowr/src/main/java/com/fueled/flowr/Flowr.java | // Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkHandler.java
// public interface FlowrDeepLinkHandler {
//
// /**
// * Retrieve deep link info from an intent.
// *
// * @param intent the intent to retrieve the info from.
// * @return the deep link info if found for the specified intent, else null.
// */
// @Nullable
// FlowrDeepLinkInfo getDeepLinkInfoForIntent(@NonNull Intent intent);
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkInfo.java
// public class FlowrDeepLinkInfo<T extends Fragment & FlowrFragment> {
// public final Bundle data;
// public final Class<? extends T> fragment;
//
// public FlowrDeepLinkInfo(Bundle data, Class<? extends T> fragment) {
// this.data = data;
// this.fragment = fragment;
// }
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/TransactionData.java
// public final class TransactionData<T extends Fragment & FlowrFragment> {
//
// private Class<? extends T> fragmentClass;
// private Bundle args;
// private boolean skipBackStack = false;
// private boolean clearBackStack = false;
// private boolean replaceCurrentFragment = false;
// private int enterAnim;
// private int exitAnim;
// private int popEnterAnim;
// private int popExitAnim;
// private Intent deepLinkIntent;
//
// public TransactionData(Class<? extends T> fragmentClass) {
// this(fragmentClass, FragmentTransaction.TRANSIT_NONE, FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim) {
// this(fragmentClass, enterAnim, exitAnim, FragmentTransaction.TRANSIT_NONE,
// FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim,
// int popEnterAnim, int popExitAnim) {
// this.fragmentClass = fragmentClass;
// this.enterAnim = enterAnim;
// this.exitAnim = exitAnim;
// this.popEnterAnim = popEnterAnim;
// this.popExitAnim = popExitAnim;
// }
//
// public Intent getDeepLinkIntent() {
// return deepLinkIntent;
// }
//
// public void setDeepLinkIntent(Intent deepLinkIntent) {
// this.deepLinkIntent = deepLinkIntent;
// }
//
// public int getPopEnterAnim() {
// return popEnterAnim;
// }
//
// public void setPopEnterAnim(int popEnterAnim) {
// this.popEnterAnim = popEnterAnim;
// }
//
// public int getPopExitAnim() {
// return popExitAnim;
// }
//
// public void setPopExitAnim(int popExitAnim) {
// this.popExitAnim = popExitAnim;
// }
//
// public Class<? extends T> getFragmentClass() {
// return fragmentClass;
// }
//
// public void setFragmentClass(Class<? extends T> fragmentClass) {
// this.fragmentClass = fragmentClass;
// }
//
// public Bundle getArgs() {
// return args;
// }
//
// public void setArgs(Bundle args) {
// this.args = args;
// }
//
// public boolean isSkipBackStack() {
// return skipBackStack;
// }
//
// public void setSkipBackStack(boolean skipBackStack) {
// this.skipBackStack = skipBackStack;
// }
//
// public boolean isClearBackStack() {
// return clearBackStack;
// }
//
// public void setClearBackStack(boolean clearBackStack) {
// this.clearBackStack = clearBackStack;
// }
//
// public boolean isReplaceCurrentFragment() {
// return replaceCurrentFragment;
// }
//
// public void setReplaceCurrentFragment(boolean replaceCurrentFragment) {
// this.replaceCurrentFragment = replaceCurrentFragment;
// }
//
// public int getEnterAnim() {
// return enterAnim;
// }
//
// public void setEnterAnim(int enterAnim) {
// this.enterAnim = enterAnim;
// }
//
// public int getExitAnim() {
// return exitAnim;
// }
//
// public void setExitAnim(int exitAnim) {
// this.exitAnim = exitAnim;
// }
// }
| import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.AnimRes;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import com.fueled.flowr.internal.FlowrDeepLinkHandler;
import com.fueled.flowr.internal.FlowrDeepLinkInfo;
import com.fueled.flowr.internal.TransactionData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | package com.fueled.flowr;
/**
* Created by [email protected] on 31/05/2016.
* Copyright (c) 2016 Fueled. All rights reserved.
*/
@SuppressWarnings({"WeakerAccess", "UnusedDeclaration"}) // Public API.
public class Flowr implements FragmentManager.OnBackStackChangedListener,
View.OnClickListener {
/**
* To be used as Bundle key for deep links.
*/
public final static String DEEP_LINK_URL = "DEEP_LINK_URL";
private final static String KEY_REQUEST_BUNDLE = "KEY_REQUEST_BUNDLE";
private final static String KEY_FRAGMENT_ID = "KEY_FRAGMENT_ID";
private final static String KEY_REQUEST_CODE = "KEY_REQUEST_CODE";
private final static String TAG = Flowr.class.getSimpleName();
private final FragmentsResultPublisher resultPublisher;
private final int mainContainerId;
@Nullable private FlowrScreen screen;
@Nullable private ToolbarHandler toolbarHandler;
@Nullable private DrawerHandler drawerHandler;
@Nullable private Fragment currentFragment;
private boolean overrideBack;
private String tagPrefix;
| // Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkHandler.java
// public interface FlowrDeepLinkHandler {
//
// /**
// * Retrieve deep link info from an intent.
// *
// * @param intent the intent to retrieve the info from.
// * @return the deep link info if found for the specified intent, else null.
// */
// @Nullable
// FlowrDeepLinkInfo getDeepLinkInfoForIntent(@NonNull Intent intent);
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkInfo.java
// public class FlowrDeepLinkInfo<T extends Fragment & FlowrFragment> {
// public final Bundle data;
// public final Class<? extends T> fragment;
//
// public FlowrDeepLinkInfo(Bundle data, Class<? extends T> fragment) {
// this.data = data;
// this.fragment = fragment;
// }
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/TransactionData.java
// public final class TransactionData<T extends Fragment & FlowrFragment> {
//
// private Class<? extends T> fragmentClass;
// private Bundle args;
// private boolean skipBackStack = false;
// private boolean clearBackStack = false;
// private boolean replaceCurrentFragment = false;
// private int enterAnim;
// private int exitAnim;
// private int popEnterAnim;
// private int popExitAnim;
// private Intent deepLinkIntent;
//
// public TransactionData(Class<? extends T> fragmentClass) {
// this(fragmentClass, FragmentTransaction.TRANSIT_NONE, FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim) {
// this(fragmentClass, enterAnim, exitAnim, FragmentTransaction.TRANSIT_NONE,
// FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim,
// int popEnterAnim, int popExitAnim) {
// this.fragmentClass = fragmentClass;
// this.enterAnim = enterAnim;
// this.exitAnim = exitAnim;
// this.popEnterAnim = popEnterAnim;
// this.popExitAnim = popExitAnim;
// }
//
// public Intent getDeepLinkIntent() {
// return deepLinkIntent;
// }
//
// public void setDeepLinkIntent(Intent deepLinkIntent) {
// this.deepLinkIntent = deepLinkIntent;
// }
//
// public int getPopEnterAnim() {
// return popEnterAnim;
// }
//
// public void setPopEnterAnim(int popEnterAnim) {
// this.popEnterAnim = popEnterAnim;
// }
//
// public int getPopExitAnim() {
// return popExitAnim;
// }
//
// public void setPopExitAnim(int popExitAnim) {
// this.popExitAnim = popExitAnim;
// }
//
// public Class<? extends T> getFragmentClass() {
// return fragmentClass;
// }
//
// public void setFragmentClass(Class<? extends T> fragmentClass) {
// this.fragmentClass = fragmentClass;
// }
//
// public Bundle getArgs() {
// return args;
// }
//
// public void setArgs(Bundle args) {
// this.args = args;
// }
//
// public boolean isSkipBackStack() {
// return skipBackStack;
// }
//
// public void setSkipBackStack(boolean skipBackStack) {
// this.skipBackStack = skipBackStack;
// }
//
// public boolean isClearBackStack() {
// return clearBackStack;
// }
//
// public void setClearBackStack(boolean clearBackStack) {
// this.clearBackStack = clearBackStack;
// }
//
// public boolean isReplaceCurrentFragment() {
// return replaceCurrentFragment;
// }
//
// public void setReplaceCurrentFragment(boolean replaceCurrentFragment) {
// this.replaceCurrentFragment = replaceCurrentFragment;
// }
//
// public int getEnterAnim() {
// return enterAnim;
// }
//
// public void setEnterAnim(int enterAnim) {
// this.enterAnim = enterAnim;
// }
//
// public int getExitAnim() {
// return exitAnim;
// }
//
// public void setExitAnim(int exitAnim) {
// this.exitAnim = exitAnim;
// }
// }
// Path: flowr/src/main/java/com/fueled/flowr/Flowr.java
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.AnimRes;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import com.fueled.flowr.internal.FlowrDeepLinkHandler;
import com.fueled.flowr.internal.FlowrDeepLinkInfo;
import com.fueled.flowr.internal.TransactionData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
package com.fueled.flowr;
/**
* Created by [email protected] on 31/05/2016.
* Copyright (c) 2016 Fueled. All rights reserved.
*/
@SuppressWarnings({"WeakerAccess", "UnusedDeclaration"}) // Public API.
public class Flowr implements FragmentManager.OnBackStackChangedListener,
View.OnClickListener {
/**
* To be used as Bundle key for deep links.
*/
public final static String DEEP_LINK_URL = "DEEP_LINK_URL";
private final static String KEY_REQUEST_BUNDLE = "KEY_REQUEST_BUNDLE";
private final static String KEY_FRAGMENT_ID = "KEY_FRAGMENT_ID";
private final static String KEY_REQUEST_CODE = "KEY_REQUEST_CODE";
private final static String TAG = Flowr.class.getSimpleName();
private final FragmentsResultPublisher resultPublisher;
private final int mainContainerId;
@Nullable private FlowrScreen screen;
@Nullable private ToolbarHandler toolbarHandler;
@Nullable private DrawerHandler drawerHandler;
@Nullable private Fragment currentFragment;
private boolean overrideBack;
private String tagPrefix;
| private List<FlowrDeepLinkHandler> deepLinkHandlers; |
Fueled/flowr | flowr/src/main/java/com/fueled/flowr/Flowr.java | // Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkHandler.java
// public interface FlowrDeepLinkHandler {
//
// /**
// * Retrieve deep link info from an intent.
// *
// * @param intent the intent to retrieve the info from.
// * @return the deep link info if found for the specified intent, else null.
// */
// @Nullable
// FlowrDeepLinkInfo getDeepLinkInfoForIntent(@NonNull Intent intent);
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkInfo.java
// public class FlowrDeepLinkInfo<T extends Fragment & FlowrFragment> {
// public final Bundle data;
// public final Class<? extends T> fragment;
//
// public FlowrDeepLinkInfo(Bundle data, Class<? extends T> fragment) {
// this.data = data;
// this.fragment = fragment;
// }
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/TransactionData.java
// public final class TransactionData<T extends Fragment & FlowrFragment> {
//
// private Class<? extends T> fragmentClass;
// private Bundle args;
// private boolean skipBackStack = false;
// private boolean clearBackStack = false;
// private boolean replaceCurrentFragment = false;
// private int enterAnim;
// private int exitAnim;
// private int popEnterAnim;
// private int popExitAnim;
// private Intent deepLinkIntent;
//
// public TransactionData(Class<? extends T> fragmentClass) {
// this(fragmentClass, FragmentTransaction.TRANSIT_NONE, FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim) {
// this(fragmentClass, enterAnim, exitAnim, FragmentTransaction.TRANSIT_NONE,
// FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim,
// int popEnterAnim, int popExitAnim) {
// this.fragmentClass = fragmentClass;
// this.enterAnim = enterAnim;
// this.exitAnim = exitAnim;
// this.popEnterAnim = popEnterAnim;
// this.popExitAnim = popExitAnim;
// }
//
// public Intent getDeepLinkIntent() {
// return deepLinkIntent;
// }
//
// public void setDeepLinkIntent(Intent deepLinkIntent) {
// this.deepLinkIntent = deepLinkIntent;
// }
//
// public int getPopEnterAnim() {
// return popEnterAnim;
// }
//
// public void setPopEnterAnim(int popEnterAnim) {
// this.popEnterAnim = popEnterAnim;
// }
//
// public int getPopExitAnim() {
// return popExitAnim;
// }
//
// public void setPopExitAnim(int popExitAnim) {
// this.popExitAnim = popExitAnim;
// }
//
// public Class<? extends T> getFragmentClass() {
// return fragmentClass;
// }
//
// public void setFragmentClass(Class<? extends T> fragmentClass) {
// this.fragmentClass = fragmentClass;
// }
//
// public Bundle getArgs() {
// return args;
// }
//
// public void setArgs(Bundle args) {
// this.args = args;
// }
//
// public boolean isSkipBackStack() {
// return skipBackStack;
// }
//
// public void setSkipBackStack(boolean skipBackStack) {
// this.skipBackStack = skipBackStack;
// }
//
// public boolean isClearBackStack() {
// return clearBackStack;
// }
//
// public void setClearBackStack(boolean clearBackStack) {
// this.clearBackStack = clearBackStack;
// }
//
// public boolean isReplaceCurrentFragment() {
// return replaceCurrentFragment;
// }
//
// public void setReplaceCurrentFragment(boolean replaceCurrentFragment) {
// this.replaceCurrentFragment = replaceCurrentFragment;
// }
//
// public int getEnterAnim() {
// return enterAnim;
// }
//
// public void setEnterAnim(int enterAnim) {
// this.enterAnim = enterAnim;
// }
//
// public int getExitAnim() {
// return exitAnim;
// }
//
// public void setExitAnim(int exitAnim) {
// this.exitAnim = exitAnim;
// }
// }
| import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.AnimRes;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import com.fueled.flowr.internal.FlowrDeepLinkHandler;
import com.fueled.flowr.internal.FlowrDeepLinkInfo;
import com.fueled.flowr.internal.TransactionData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | /**
* Specify a collection of {@link FlowrDeepLinkHandler} to be used when routing deep link
* intents replacing all previously set handlers.
*
* @param handlers the collection of handlers to be used.
*/
public void setDeepLinkHandlers(FlowrDeepLinkHandler... handlers) {
this.deepLinkHandlers.clear();
if (handlers != null) {
Collections.addAll(deepLinkHandlers, handlers);
}
}
/**
* Returns the prefix used for the backstack fragments tag
*
* @return the prefix used for the backstack fragments tag
*/
@NonNull
protected final String getTagPrefix() {
return tagPrefix;
}
/**
*
* @param data TransactionData used to configure fragment transaction
* @param <T> type Fragment & FlowrFragment
* @return id Identifier of the committed transaction.
*/ | // Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkHandler.java
// public interface FlowrDeepLinkHandler {
//
// /**
// * Retrieve deep link info from an intent.
// *
// * @param intent the intent to retrieve the info from.
// * @return the deep link info if found for the specified intent, else null.
// */
// @Nullable
// FlowrDeepLinkInfo getDeepLinkInfoForIntent(@NonNull Intent intent);
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkInfo.java
// public class FlowrDeepLinkInfo<T extends Fragment & FlowrFragment> {
// public final Bundle data;
// public final Class<? extends T> fragment;
//
// public FlowrDeepLinkInfo(Bundle data, Class<? extends T> fragment) {
// this.data = data;
// this.fragment = fragment;
// }
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/TransactionData.java
// public final class TransactionData<T extends Fragment & FlowrFragment> {
//
// private Class<? extends T> fragmentClass;
// private Bundle args;
// private boolean skipBackStack = false;
// private boolean clearBackStack = false;
// private boolean replaceCurrentFragment = false;
// private int enterAnim;
// private int exitAnim;
// private int popEnterAnim;
// private int popExitAnim;
// private Intent deepLinkIntent;
//
// public TransactionData(Class<? extends T> fragmentClass) {
// this(fragmentClass, FragmentTransaction.TRANSIT_NONE, FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim) {
// this(fragmentClass, enterAnim, exitAnim, FragmentTransaction.TRANSIT_NONE,
// FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim,
// int popEnterAnim, int popExitAnim) {
// this.fragmentClass = fragmentClass;
// this.enterAnim = enterAnim;
// this.exitAnim = exitAnim;
// this.popEnterAnim = popEnterAnim;
// this.popExitAnim = popExitAnim;
// }
//
// public Intent getDeepLinkIntent() {
// return deepLinkIntent;
// }
//
// public void setDeepLinkIntent(Intent deepLinkIntent) {
// this.deepLinkIntent = deepLinkIntent;
// }
//
// public int getPopEnterAnim() {
// return popEnterAnim;
// }
//
// public void setPopEnterAnim(int popEnterAnim) {
// this.popEnterAnim = popEnterAnim;
// }
//
// public int getPopExitAnim() {
// return popExitAnim;
// }
//
// public void setPopExitAnim(int popExitAnim) {
// this.popExitAnim = popExitAnim;
// }
//
// public Class<? extends T> getFragmentClass() {
// return fragmentClass;
// }
//
// public void setFragmentClass(Class<? extends T> fragmentClass) {
// this.fragmentClass = fragmentClass;
// }
//
// public Bundle getArgs() {
// return args;
// }
//
// public void setArgs(Bundle args) {
// this.args = args;
// }
//
// public boolean isSkipBackStack() {
// return skipBackStack;
// }
//
// public void setSkipBackStack(boolean skipBackStack) {
// this.skipBackStack = skipBackStack;
// }
//
// public boolean isClearBackStack() {
// return clearBackStack;
// }
//
// public void setClearBackStack(boolean clearBackStack) {
// this.clearBackStack = clearBackStack;
// }
//
// public boolean isReplaceCurrentFragment() {
// return replaceCurrentFragment;
// }
//
// public void setReplaceCurrentFragment(boolean replaceCurrentFragment) {
// this.replaceCurrentFragment = replaceCurrentFragment;
// }
//
// public int getEnterAnim() {
// return enterAnim;
// }
//
// public void setEnterAnim(int enterAnim) {
// this.enterAnim = enterAnim;
// }
//
// public int getExitAnim() {
// return exitAnim;
// }
//
// public void setExitAnim(int exitAnim) {
// this.exitAnim = exitAnim;
// }
// }
// Path: flowr/src/main/java/com/fueled/flowr/Flowr.java
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.AnimRes;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import com.fueled.flowr.internal.FlowrDeepLinkHandler;
import com.fueled.flowr.internal.FlowrDeepLinkInfo;
import com.fueled.flowr.internal.TransactionData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Specify a collection of {@link FlowrDeepLinkHandler} to be used when routing deep link
* intents replacing all previously set handlers.
*
* @param handlers the collection of handlers to be used.
*/
public void setDeepLinkHandlers(FlowrDeepLinkHandler... handlers) {
this.deepLinkHandlers.clear();
if (handlers != null) {
Collections.addAll(deepLinkHandlers, handlers);
}
}
/**
* Returns the prefix used for the backstack fragments tag
*
* @return the prefix used for the backstack fragments tag
*/
@NonNull
protected final String getTagPrefix() {
return tagPrefix;
}
/**
*
* @param data TransactionData used to configure fragment transaction
* @param <T> type Fragment & FlowrFragment
* @return id Identifier of the committed transaction.
*/ | protected <T extends Fragment & FlowrFragment> int displayFragment(TransactionData<T> data) { |
Fueled/flowr | flowr/src/main/java/com/fueled/flowr/Flowr.java | // Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkHandler.java
// public interface FlowrDeepLinkHandler {
//
// /**
// * Retrieve deep link info from an intent.
// *
// * @param intent the intent to retrieve the info from.
// * @return the deep link info if found for the specified intent, else null.
// */
// @Nullable
// FlowrDeepLinkInfo getDeepLinkInfoForIntent(@NonNull Intent intent);
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkInfo.java
// public class FlowrDeepLinkInfo<T extends Fragment & FlowrFragment> {
// public final Bundle data;
// public final Class<? extends T> fragment;
//
// public FlowrDeepLinkInfo(Bundle data, Class<? extends T> fragment) {
// this.data = data;
// this.fragment = fragment;
// }
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/TransactionData.java
// public final class TransactionData<T extends Fragment & FlowrFragment> {
//
// private Class<? extends T> fragmentClass;
// private Bundle args;
// private boolean skipBackStack = false;
// private boolean clearBackStack = false;
// private boolean replaceCurrentFragment = false;
// private int enterAnim;
// private int exitAnim;
// private int popEnterAnim;
// private int popExitAnim;
// private Intent deepLinkIntent;
//
// public TransactionData(Class<? extends T> fragmentClass) {
// this(fragmentClass, FragmentTransaction.TRANSIT_NONE, FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim) {
// this(fragmentClass, enterAnim, exitAnim, FragmentTransaction.TRANSIT_NONE,
// FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim,
// int popEnterAnim, int popExitAnim) {
// this.fragmentClass = fragmentClass;
// this.enterAnim = enterAnim;
// this.exitAnim = exitAnim;
// this.popEnterAnim = popEnterAnim;
// this.popExitAnim = popExitAnim;
// }
//
// public Intent getDeepLinkIntent() {
// return deepLinkIntent;
// }
//
// public void setDeepLinkIntent(Intent deepLinkIntent) {
// this.deepLinkIntent = deepLinkIntent;
// }
//
// public int getPopEnterAnim() {
// return popEnterAnim;
// }
//
// public void setPopEnterAnim(int popEnterAnim) {
// this.popEnterAnim = popEnterAnim;
// }
//
// public int getPopExitAnim() {
// return popExitAnim;
// }
//
// public void setPopExitAnim(int popExitAnim) {
// this.popExitAnim = popExitAnim;
// }
//
// public Class<? extends T> getFragmentClass() {
// return fragmentClass;
// }
//
// public void setFragmentClass(Class<? extends T> fragmentClass) {
// this.fragmentClass = fragmentClass;
// }
//
// public Bundle getArgs() {
// return args;
// }
//
// public void setArgs(Bundle args) {
// this.args = args;
// }
//
// public boolean isSkipBackStack() {
// return skipBackStack;
// }
//
// public void setSkipBackStack(boolean skipBackStack) {
// this.skipBackStack = skipBackStack;
// }
//
// public boolean isClearBackStack() {
// return clearBackStack;
// }
//
// public void setClearBackStack(boolean clearBackStack) {
// this.clearBackStack = clearBackStack;
// }
//
// public boolean isReplaceCurrentFragment() {
// return replaceCurrentFragment;
// }
//
// public void setReplaceCurrentFragment(boolean replaceCurrentFragment) {
// this.replaceCurrentFragment = replaceCurrentFragment;
// }
//
// public int getEnterAnim() {
// return enterAnim;
// }
//
// public void setEnterAnim(int enterAnim) {
// this.enterAnim = enterAnim;
// }
//
// public int getExitAnim() {
// return exitAnim;
// }
//
// public void setExitAnim(int exitAnim) {
// this.exitAnim = exitAnim;
// }
// }
| import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.AnimRes;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import com.fueled.flowr.internal.FlowrDeepLinkHandler;
import com.fueled.flowr.internal.FlowrDeepLinkInfo;
import com.fueled.flowr.internal.TransactionData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | if (data.isReplaceCurrentFragment()) {
transaction.replace(mainContainerId, fragment);
} else {
transaction.add(mainContainerId, fragment);
}
identifier = transaction.commit();
if (data.isSkipBackStack()) {
setCurrentFragment(fragment);
}
} catch (Exception e) {
Log.e(TAG, "Error while displaying fragment.", e);
}
return identifier;
}
/**
* Parse the intent set by {@link TransactionData#deepLinkIntent} and if this intent contains
* Deep Link info, update the {@link #currentFragment} and the Transaction data.
*
* @param data The Transaction data to extend if Deep link info are found in
* the {@link TransactionData#deepLinkIntent}.
* @param <T> The generic type for a valid Fragment.
*/
@SuppressWarnings("unchecked")
private <T extends Fragment & FlowrFragment> void injectDeepLinkInfo(TransactionData<T> data) {
Intent deepLinkIntent = data.getDeepLinkIntent();
if (deepLinkIntent != null) {
for (FlowrDeepLinkHandler handler : deepLinkHandlers) { | // Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkHandler.java
// public interface FlowrDeepLinkHandler {
//
// /**
// * Retrieve deep link info from an intent.
// *
// * @param intent the intent to retrieve the info from.
// * @return the deep link info if found for the specified intent, else null.
// */
// @Nullable
// FlowrDeepLinkInfo getDeepLinkInfoForIntent(@NonNull Intent intent);
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/FlowrDeepLinkInfo.java
// public class FlowrDeepLinkInfo<T extends Fragment & FlowrFragment> {
// public final Bundle data;
// public final Class<? extends T> fragment;
//
// public FlowrDeepLinkInfo(Bundle data, Class<? extends T> fragment) {
// this.data = data;
// this.fragment = fragment;
// }
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/internal/TransactionData.java
// public final class TransactionData<T extends Fragment & FlowrFragment> {
//
// private Class<? extends T> fragmentClass;
// private Bundle args;
// private boolean skipBackStack = false;
// private boolean clearBackStack = false;
// private boolean replaceCurrentFragment = false;
// private int enterAnim;
// private int exitAnim;
// private int popEnterAnim;
// private int popExitAnim;
// private Intent deepLinkIntent;
//
// public TransactionData(Class<? extends T> fragmentClass) {
// this(fragmentClass, FragmentTransaction.TRANSIT_NONE, FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim) {
// this(fragmentClass, enterAnim, exitAnim, FragmentTransaction.TRANSIT_NONE,
// FragmentTransaction.TRANSIT_NONE);
// }
//
// public TransactionData(Class<? extends T> fragmentClass, int enterAnim, int exitAnim,
// int popEnterAnim, int popExitAnim) {
// this.fragmentClass = fragmentClass;
// this.enterAnim = enterAnim;
// this.exitAnim = exitAnim;
// this.popEnterAnim = popEnterAnim;
// this.popExitAnim = popExitAnim;
// }
//
// public Intent getDeepLinkIntent() {
// return deepLinkIntent;
// }
//
// public void setDeepLinkIntent(Intent deepLinkIntent) {
// this.deepLinkIntent = deepLinkIntent;
// }
//
// public int getPopEnterAnim() {
// return popEnterAnim;
// }
//
// public void setPopEnterAnim(int popEnterAnim) {
// this.popEnterAnim = popEnterAnim;
// }
//
// public int getPopExitAnim() {
// return popExitAnim;
// }
//
// public void setPopExitAnim(int popExitAnim) {
// this.popExitAnim = popExitAnim;
// }
//
// public Class<? extends T> getFragmentClass() {
// return fragmentClass;
// }
//
// public void setFragmentClass(Class<? extends T> fragmentClass) {
// this.fragmentClass = fragmentClass;
// }
//
// public Bundle getArgs() {
// return args;
// }
//
// public void setArgs(Bundle args) {
// this.args = args;
// }
//
// public boolean isSkipBackStack() {
// return skipBackStack;
// }
//
// public void setSkipBackStack(boolean skipBackStack) {
// this.skipBackStack = skipBackStack;
// }
//
// public boolean isClearBackStack() {
// return clearBackStack;
// }
//
// public void setClearBackStack(boolean clearBackStack) {
// this.clearBackStack = clearBackStack;
// }
//
// public boolean isReplaceCurrentFragment() {
// return replaceCurrentFragment;
// }
//
// public void setReplaceCurrentFragment(boolean replaceCurrentFragment) {
// this.replaceCurrentFragment = replaceCurrentFragment;
// }
//
// public int getEnterAnim() {
// return enterAnim;
// }
//
// public void setEnterAnim(int enterAnim) {
// this.enterAnim = enterAnim;
// }
//
// public int getExitAnim() {
// return exitAnim;
// }
//
// public void setExitAnim(int exitAnim) {
// this.exitAnim = exitAnim;
// }
// }
// Path: flowr/src/main/java/com/fueled/flowr/Flowr.java
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.AnimRes;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import com.fueled.flowr.internal.FlowrDeepLinkHandler;
import com.fueled.flowr.internal.FlowrDeepLinkInfo;
import com.fueled.flowr.internal.TransactionData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
if (data.isReplaceCurrentFragment()) {
transaction.replace(mainContainerId, fragment);
} else {
transaction.add(mainContainerId, fragment);
}
identifier = transaction.commit();
if (data.isSkipBackStack()) {
setCurrentFragment(fragment);
}
} catch (Exception e) {
Log.e(TAG, "Error while displaying fragment.", e);
}
return identifier;
}
/**
* Parse the intent set by {@link TransactionData#deepLinkIntent} and if this intent contains
* Deep Link info, update the {@link #currentFragment} and the Transaction data.
*
* @param data The Transaction data to extend if Deep link info are found in
* the {@link TransactionData#deepLinkIntent}.
* @param <T> The generic type for a valid Fragment.
*/
@SuppressWarnings("unchecked")
private <T extends Fragment & FlowrFragment> void injectDeepLinkInfo(TransactionData<T> data) {
Intent deepLinkIntent = data.getDeepLinkIntent();
if (deepLinkIntent != null) {
for (FlowrDeepLinkHandler handler : deepLinkHandlers) { | FlowrDeepLinkInfo info = handler.getDeepLinkInfoForIntent(deepLinkIntent); |
Fueled/flowr | sample/src/main/java/com/fueled/flowr/sample/core/FragmentResultPublisherImpl.java | // Path: flowr/src/main/java/com/fueled/flowr/FragmentsResultPublisher.java
// public interface FragmentsResultPublisher {
//
// void publishResult(ResultResponse resultResponse);
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/ResultResponse.java
// public class ResultResponse {
//
// public String fragmentId;
// public int requestCode;
// public int resultCode;
// public Bundle data;
// }
| import com.fueled.flowr.FragmentsResultPublisher;
import com.fueled.flowr.ResultResponse;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import io.reactivex.subjects.PublishSubject; | package com.fueled.flowr.sample.core;
/**
* Created by [email protected] on 13/02/2017.
* Copyright (c) 2017 Fueled. All rights reserved.
*/
public class FragmentResultPublisherImpl implements FragmentsResultPublisher {
private static FragmentResultPublisherImpl instance;
| // Path: flowr/src/main/java/com/fueled/flowr/FragmentsResultPublisher.java
// public interface FragmentsResultPublisher {
//
// void publishResult(ResultResponse resultResponse);
// }
//
// Path: flowr/src/main/java/com/fueled/flowr/ResultResponse.java
// public class ResultResponse {
//
// public String fragmentId;
// public int requestCode;
// public int resultCode;
// public Bundle data;
// }
// Path: sample/src/main/java/com/fueled/flowr/sample/core/FragmentResultPublisherImpl.java
import com.fueled.flowr.FragmentsResultPublisher;
import com.fueled.flowr.ResultResponse;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import io.reactivex.subjects.PublishSubject;
package com.fueled.flowr.sample.core;
/**
* Created by [email protected] on 13/02/2017.
* Copyright (c) 2017 Fueled. All rights reserved.
*/
public class FragmentResultPublisherImpl implements FragmentsResultPublisher {
private static FragmentResultPublisherImpl instance;
| private PublishSubject<ResultResponse> publishSubject; |
avrecko/weld-guiceconfig | test/weld/guiceconfig/basics/BasicTest.java | // Path: test/weld/guiceconfig/AbstractGuiceConfigTest.java
// public abstract class AbstractGuiceConfigTest extends TestCase {
//
// protected BeanManager manager;
//
// Weld weld;
//
// protected abstract Iterable<? extends Module> getModules();
//
// @Override
// public void setUp() {
// GuiceConfigTestModule.register(getModules());
// weld = new Weld();
// WeldContainer container = weld.initialize();
// manager = container.getBeanManager();
// }
//
// @Override
// public void tearDown() {
// weld.shutdown();
// }
//
// public <T> T getReference(Class<T> clazz, Annotation... bindings) {
// Set<Bean<?>> beans = manager.getBeans(clazz, bindings);
// if (beans.isEmpty()) {
// throw new RuntimeException("No bean found with class: " + clazz + " and bindings " + bindings.toString());
// } else if (beans.size() != 1) {
// StringBuilder bs = new StringBuilder("[");
// for (Annotation a : bindings) {
// bs.append(a.toString() + ",");
// }
// bs.append("]");
// throw new RuntimeException("More than one bean found with class: " + clazz + " and bindings " + bs);
// }
// Bean bean = beans.iterator().next();
// return (T) bean.create(manager.createCreationalContext(bean));
// }
//
// }
//
// Path: test/weld/guiceconfig/world/AsynchronousMailer.java
// public class AsynchronousMailer implements Mailer {
// @Override
// public void sendMail(String recipient, String subject, String content) {
//
// }
// }
//
// Path: test/weld/guiceconfig/world/Mailer.java
// @CustomQualifier
// public interface Mailer {
//
// void sendMail(String recipient, String subject, String content);
//
// }
| import com.google.inject.AbstractModule;
import com.google.inject.Module;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matchers;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import weld.guiceconfig.AbstractGuiceConfigTest;
import weld.guiceconfig.world.AsynchronousMailer;
import weld.guiceconfig.world.Mailer;
import javax.inject.Singleton;
import java.lang.reflect.Method;
import java.util.Arrays; | /*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.basics;
/**
* Tests basic linked binding and aop.
*
* @author Alen Vrecko
*/
public class BasicTest extends AbstractGuiceConfigTest {
private static final String AOPED = "AOPED";
@Override
protected Iterable<? extends Module> getModules() {
return Arrays.asList(new AbstractModule() {
@Override
protected void configure() { | // Path: test/weld/guiceconfig/AbstractGuiceConfigTest.java
// public abstract class AbstractGuiceConfigTest extends TestCase {
//
// protected BeanManager manager;
//
// Weld weld;
//
// protected abstract Iterable<? extends Module> getModules();
//
// @Override
// public void setUp() {
// GuiceConfigTestModule.register(getModules());
// weld = new Weld();
// WeldContainer container = weld.initialize();
// manager = container.getBeanManager();
// }
//
// @Override
// public void tearDown() {
// weld.shutdown();
// }
//
// public <T> T getReference(Class<T> clazz, Annotation... bindings) {
// Set<Bean<?>> beans = manager.getBeans(clazz, bindings);
// if (beans.isEmpty()) {
// throw new RuntimeException("No bean found with class: " + clazz + " and bindings " + bindings.toString());
// } else if (beans.size() != 1) {
// StringBuilder bs = new StringBuilder("[");
// for (Annotation a : bindings) {
// bs.append(a.toString() + ",");
// }
// bs.append("]");
// throw new RuntimeException("More than one bean found with class: " + clazz + " and bindings " + bs);
// }
// Bean bean = beans.iterator().next();
// return (T) bean.create(manager.createCreationalContext(bean));
// }
//
// }
//
// Path: test/weld/guiceconfig/world/AsynchronousMailer.java
// public class AsynchronousMailer implements Mailer {
// @Override
// public void sendMail(String recipient, String subject, String content) {
//
// }
// }
//
// Path: test/weld/guiceconfig/world/Mailer.java
// @CustomQualifier
// public interface Mailer {
//
// void sendMail(String recipient, String subject, String content);
//
// }
// Path: test/weld/guiceconfig/basics/BasicTest.java
import com.google.inject.AbstractModule;
import com.google.inject.Module;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matchers;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import weld.guiceconfig.AbstractGuiceConfigTest;
import weld.guiceconfig.world.AsynchronousMailer;
import weld.guiceconfig.world.Mailer;
import javax.inject.Singleton;
import java.lang.reflect.Method;
import java.util.Arrays;
/*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.basics;
/**
* Tests basic linked binding and aop.
*
* @author Alen Vrecko
*/
public class BasicTest extends AbstractGuiceConfigTest {
private static final String AOPED = "AOPED";
@Override
protected Iterable<? extends Module> getModules() {
return Arrays.asList(new AbstractModule() {
@Override
protected void configure() { | bind(Mailer.class).to(AsynchronousMailer.class).in(Singleton.class); |
avrecko/weld-guiceconfig | test/weld/guiceconfig/basics/BasicTest.java | // Path: test/weld/guiceconfig/AbstractGuiceConfigTest.java
// public abstract class AbstractGuiceConfigTest extends TestCase {
//
// protected BeanManager manager;
//
// Weld weld;
//
// protected abstract Iterable<? extends Module> getModules();
//
// @Override
// public void setUp() {
// GuiceConfigTestModule.register(getModules());
// weld = new Weld();
// WeldContainer container = weld.initialize();
// manager = container.getBeanManager();
// }
//
// @Override
// public void tearDown() {
// weld.shutdown();
// }
//
// public <T> T getReference(Class<T> clazz, Annotation... bindings) {
// Set<Bean<?>> beans = manager.getBeans(clazz, bindings);
// if (beans.isEmpty()) {
// throw new RuntimeException("No bean found with class: " + clazz + " and bindings " + bindings.toString());
// } else if (beans.size() != 1) {
// StringBuilder bs = new StringBuilder("[");
// for (Annotation a : bindings) {
// bs.append(a.toString() + ",");
// }
// bs.append("]");
// throw new RuntimeException("More than one bean found with class: " + clazz + " and bindings " + bs);
// }
// Bean bean = beans.iterator().next();
// return (T) bean.create(manager.createCreationalContext(bean));
// }
//
// }
//
// Path: test/weld/guiceconfig/world/AsynchronousMailer.java
// public class AsynchronousMailer implements Mailer {
// @Override
// public void sendMail(String recipient, String subject, String content) {
//
// }
// }
//
// Path: test/weld/guiceconfig/world/Mailer.java
// @CustomQualifier
// public interface Mailer {
//
// void sendMail(String recipient, String subject, String content);
//
// }
| import com.google.inject.AbstractModule;
import com.google.inject.Module;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matchers;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import weld.guiceconfig.AbstractGuiceConfigTest;
import weld.guiceconfig.world.AsynchronousMailer;
import weld.guiceconfig.world.Mailer;
import javax.inject.Singleton;
import java.lang.reflect.Method;
import java.util.Arrays; | /*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.basics;
/**
* Tests basic linked binding and aop.
*
* @author Alen Vrecko
*/
public class BasicTest extends AbstractGuiceConfigTest {
private static final String AOPED = "AOPED";
@Override
protected Iterable<? extends Module> getModules() {
return Arrays.asList(new AbstractModule() {
@Override
protected void configure() { | // Path: test/weld/guiceconfig/AbstractGuiceConfigTest.java
// public abstract class AbstractGuiceConfigTest extends TestCase {
//
// protected BeanManager manager;
//
// Weld weld;
//
// protected abstract Iterable<? extends Module> getModules();
//
// @Override
// public void setUp() {
// GuiceConfigTestModule.register(getModules());
// weld = new Weld();
// WeldContainer container = weld.initialize();
// manager = container.getBeanManager();
// }
//
// @Override
// public void tearDown() {
// weld.shutdown();
// }
//
// public <T> T getReference(Class<T> clazz, Annotation... bindings) {
// Set<Bean<?>> beans = manager.getBeans(clazz, bindings);
// if (beans.isEmpty()) {
// throw new RuntimeException("No bean found with class: " + clazz + " and bindings " + bindings.toString());
// } else if (beans.size() != 1) {
// StringBuilder bs = new StringBuilder("[");
// for (Annotation a : bindings) {
// bs.append(a.toString() + ",");
// }
// bs.append("]");
// throw new RuntimeException("More than one bean found with class: " + clazz + " and bindings " + bs);
// }
// Bean bean = beans.iterator().next();
// return (T) bean.create(manager.createCreationalContext(bean));
// }
//
// }
//
// Path: test/weld/guiceconfig/world/AsynchronousMailer.java
// public class AsynchronousMailer implements Mailer {
// @Override
// public void sendMail(String recipient, String subject, String content) {
//
// }
// }
//
// Path: test/weld/guiceconfig/world/Mailer.java
// @CustomQualifier
// public interface Mailer {
//
// void sendMail(String recipient, String subject, String content);
//
// }
// Path: test/weld/guiceconfig/basics/BasicTest.java
import com.google.inject.AbstractModule;
import com.google.inject.Module;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matchers;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import weld.guiceconfig.AbstractGuiceConfigTest;
import weld.guiceconfig.world.AsynchronousMailer;
import weld.guiceconfig.world.Mailer;
import javax.inject.Singleton;
import java.lang.reflect.Method;
import java.util.Arrays;
/*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.basics;
/**
* Tests basic linked binding and aop.
*
* @author Alen Vrecko
*/
public class BasicTest extends AbstractGuiceConfigTest {
private static final String AOPED = "AOPED";
@Override
protected Iterable<? extends Module> getModules() {
return Arrays.asList(new AbstractModule() {
@Override
protected void configure() { | bind(Mailer.class).to(AsynchronousMailer.class).in(Singleton.class); |
avrecko/weld-guiceconfig | src/weld/guiceconfig/attic/internal/RecordingBinder.java | // Path: src/weld/guiceconfig/attic/Binder.java
// public interface Binder {
//
// <E> AnnotatedBindingBuilder<E> bind(Class<E> clazz);
//
// void install(Module module);
// }
//
// Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/Module.java
// public interface Module {
//
// void configure(Binder binder);
// }
//
// Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
| import weld.guiceconfig.attic.Binder;
import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.Module;
import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder;
import java.util.Stack;
import static java.util.Arrays.asList; | /*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class RecordingBinder implements Binder {
final Stack<Binding> bindings = new Stack<Binding>();
| // Path: src/weld/guiceconfig/attic/Binder.java
// public interface Binder {
//
// <E> AnnotatedBindingBuilder<E> bind(Class<E> clazz);
//
// void install(Module module);
// }
//
// Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/Module.java
// public interface Module {
//
// void configure(Binder binder);
// }
//
// Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
// Path: src/weld/guiceconfig/attic/internal/RecordingBinder.java
import weld.guiceconfig.attic.Binder;
import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.Module;
import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder;
import java.util.Stack;
import static java.util.Arrays.asList;
/*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class RecordingBinder implements Binder {
final Stack<Binding> bindings = new Stack<Binding>();
| public <E> AnnotatedBindingBuilder<E> bind(Class<E> clazz) { |
avrecko/weld-guiceconfig | src/weld/guiceconfig/attic/internal/RecordingBinder.java | // Path: src/weld/guiceconfig/attic/Binder.java
// public interface Binder {
//
// <E> AnnotatedBindingBuilder<E> bind(Class<E> clazz);
//
// void install(Module module);
// }
//
// Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/Module.java
// public interface Module {
//
// void configure(Binder binder);
// }
//
// Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
| import weld.guiceconfig.attic.Binder;
import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.Module;
import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder;
import java.util.Stack;
import static java.util.Arrays.asList; | /*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class RecordingBinder implements Binder {
final Stack<Binding> bindings = new Stack<Binding>();
public <E> AnnotatedBindingBuilder<E> bind(Class<E> clazz) {
bindings.push(new DefaultBinding(clazz));
return new RecordersBindingBuilder<E>(this);
}
| // Path: src/weld/guiceconfig/attic/Binder.java
// public interface Binder {
//
// <E> AnnotatedBindingBuilder<E> bind(Class<E> clazz);
//
// void install(Module module);
// }
//
// Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/Module.java
// public interface Module {
//
// void configure(Binder binder);
// }
//
// Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
// Path: src/weld/guiceconfig/attic/internal/RecordingBinder.java
import weld.guiceconfig.attic.Binder;
import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.Module;
import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder;
import java.util.Stack;
import static java.util.Arrays.asList;
/*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class RecordingBinder implements Binder {
final Stack<Binding> bindings = new Stack<Binding>();
public <E> AnnotatedBindingBuilder<E> bind(Class<E> clazz) {
bindings.push(new DefaultBinding(clazz));
return new RecordersBindingBuilder<E>(this);
}
| public void install(Module module) { |
avrecko/weld-guiceconfig | src/weld/guiceconfig/attic/internal/RecordersBindingBuilder.java | // Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/LinkedBindingBuilder.java
// public interface LinkedBindingBuilder<E> extends ScopedBindingBuilder {
//
// ScopedBindingBuilder to(Class<? extends E> linkedTo);
//
// }
//
// Path: src/weld/guiceconfig/attic/binder/ScopedBindingBuilder.java
// public interface ScopedBindingBuilder {
//
// void in(Class<? extends Annotation> annotationType);
//
// }
| import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder;
import weld.guiceconfig.attic.binder.LinkedBindingBuilder;
import weld.guiceconfig.attic.binder.ScopedBindingBuilder;
import java.lang.annotation.Annotation; | /*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class RecordersBindingBuilder<E> implements AnnotatedBindingBuilder<E> {
private final RecordingBinder recorder;
public RecordersBindingBuilder(RecordingBinder recorder) {
this.recorder = recorder;
}
| // Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/LinkedBindingBuilder.java
// public interface LinkedBindingBuilder<E> extends ScopedBindingBuilder {
//
// ScopedBindingBuilder to(Class<? extends E> linkedTo);
//
// }
//
// Path: src/weld/guiceconfig/attic/binder/ScopedBindingBuilder.java
// public interface ScopedBindingBuilder {
//
// void in(Class<? extends Annotation> annotationType);
//
// }
// Path: src/weld/guiceconfig/attic/internal/RecordersBindingBuilder.java
import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder;
import weld.guiceconfig.attic.binder.LinkedBindingBuilder;
import weld.guiceconfig.attic.binder.ScopedBindingBuilder;
import java.lang.annotation.Annotation;
/*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class RecordersBindingBuilder<E> implements AnnotatedBindingBuilder<E> {
private final RecordingBinder recorder;
public RecordersBindingBuilder(RecordingBinder recorder) {
this.recorder = recorder;
}
| public ScopedBindingBuilder to(Class moreConcreteType) { |
avrecko/weld-guiceconfig | src/weld/guiceconfig/attic/internal/RecordersBindingBuilder.java | // Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/LinkedBindingBuilder.java
// public interface LinkedBindingBuilder<E> extends ScopedBindingBuilder {
//
// ScopedBindingBuilder to(Class<? extends E> linkedTo);
//
// }
//
// Path: src/weld/guiceconfig/attic/binder/ScopedBindingBuilder.java
// public interface ScopedBindingBuilder {
//
// void in(Class<? extends Annotation> annotationType);
//
// }
| import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder;
import weld.guiceconfig.attic.binder.LinkedBindingBuilder;
import weld.guiceconfig.attic.binder.ScopedBindingBuilder;
import java.lang.annotation.Annotation; | /*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class RecordersBindingBuilder<E> implements AnnotatedBindingBuilder<E> {
private final RecordingBinder recorder;
public RecordersBindingBuilder(RecordingBinder recorder) {
this.recorder = recorder;
}
public ScopedBindingBuilder to(Class moreConcreteType) { | // Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/LinkedBindingBuilder.java
// public interface LinkedBindingBuilder<E> extends ScopedBindingBuilder {
//
// ScopedBindingBuilder to(Class<? extends E> linkedTo);
//
// }
//
// Path: src/weld/guiceconfig/attic/binder/ScopedBindingBuilder.java
// public interface ScopedBindingBuilder {
//
// void in(Class<? extends Annotation> annotationType);
//
// }
// Path: src/weld/guiceconfig/attic/internal/RecordersBindingBuilder.java
import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder;
import weld.guiceconfig.attic.binder.LinkedBindingBuilder;
import weld.guiceconfig.attic.binder.ScopedBindingBuilder;
import java.lang.annotation.Annotation;
/*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class RecordersBindingBuilder<E> implements AnnotatedBindingBuilder<E> {
private final RecordingBinder recorder;
public RecordersBindingBuilder(RecordingBinder recorder) {
this.recorder = recorder;
}
public ScopedBindingBuilder to(Class moreConcreteType) { | Binding poped = recorder.bindings.pop(); |
avrecko/weld-guiceconfig | src/weld/guiceconfig/attic/internal/RecordersBindingBuilder.java | // Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/LinkedBindingBuilder.java
// public interface LinkedBindingBuilder<E> extends ScopedBindingBuilder {
//
// ScopedBindingBuilder to(Class<? extends E> linkedTo);
//
// }
//
// Path: src/weld/guiceconfig/attic/binder/ScopedBindingBuilder.java
// public interface ScopedBindingBuilder {
//
// void in(Class<? extends Annotation> annotationType);
//
// }
| import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder;
import weld.guiceconfig.attic.binder.LinkedBindingBuilder;
import weld.guiceconfig.attic.binder.ScopedBindingBuilder;
import java.lang.annotation.Annotation; | /*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class RecordersBindingBuilder<E> implements AnnotatedBindingBuilder<E> {
private final RecordingBinder recorder;
public RecordersBindingBuilder(RecordingBinder recorder) {
this.recorder = recorder;
}
public ScopedBindingBuilder to(Class moreConcreteType) {
Binding poped = recorder.bindings.pop();
recorder.bindings.push(new LinkedKeyBinding(poped.getKey(), moreConcreteType));
return this;
}
public void in(Class<? extends Annotation> annotationType) {
Binding poped = recorder.bindings.pop();
recorder.bindings.push(poped.withScoping(annotationType));
}
| // Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/binder/LinkedBindingBuilder.java
// public interface LinkedBindingBuilder<E> extends ScopedBindingBuilder {
//
// ScopedBindingBuilder to(Class<? extends E> linkedTo);
//
// }
//
// Path: src/weld/guiceconfig/attic/binder/ScopedBindingBuilder.java
// public interface ScopedBindingBuilder {
//
// void in(Class<? extends Annotation> annotationType);
//
// }
// Path: src/weld/guiceconfig/attic/internal/RecordersBindingBuilder.java
import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder;
import weld.guiceconfig.attic.binder.LinkedBindingBuilder;
import weld.guiceconfig.attic.binder.ScopedBindingBuilder;
import java.lang.annotation.Annotation;
/*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class RecordersBindingBuilder<E> implements AnnotatedBindingBuilder<E> {
private final RecordingBinder recorder;
public RecordersBindingBuilder(RecordingBinder recorder) {
this.recorder = recorder;
}
public ScopedBindingBuilder to(Class moreConcreteType) {
Binding poped = recorder.bindings.pop();
recorder.bindings.push(new LinkedKeyBinding(poped.getKey(), moreConcreteType));
return this;
}
public void in(Class<? extends Annotation> annotationType) {
Binding poped = recorder.bindings.pop();
recorder.bindings.push(poped.withScoping(annotationType));
}
| public LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier) { |
avrecko/weld-guiceconfig | src/weld/guiceconfig/attic/internal/LinkedKeyBinding.java | // Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/Key.java
// public class Key {
//
// public final Class<?> clazz;
// public final Class<? extends Annotation> qualifier;
// private static final AtomicInteger count = new AtomicInteger();
//
// public Key(Class<?> clazz, Class<? extends Annotation> qualifier) {
// this.clazz = clazz;
// this.qualifier = qualifier;
// }
//
// public Key(Class<?> target) {
// this.clazz = target;
// this.qualifier = HardDefault.class;
// }
//
// public static <T, A extends Annotation> Key newKey(Class<T> clazz, Class<A> qualifier) {
// return new Key(clazz, qualifier);
// }
//
//
// @Override
// public String toString() {
// return "Key{" +
// "clazz=" + clazz +
// ", qualifier=" + qualifier +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (qualifier != null ? !qualifier.equals(key.qualifier) : key.qualifier != null) return false;
// if (clazz != null ? !clazz.equals(key.clazz) : key.clazz != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = clazz != null ? clazz.hashCode() : 0;
// result = 31 * result + (qualifier != null ? qualifier.hashCode() : 0);
// return result;
// }
//
// public static Key newKey(Class<?> target) {
// return new Key(target);
// }
// }
| import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.Key;
import java.lang.annotation.Annotation; | /*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class LinkedKeyBinding extends DefaultBinding {
private final Key target;
public LinkedKeyBinding(Key key, Class<?> target) {
super(key);
this.target = Key.newKey(target);
}
public LinkedKeyBinding(Key base, Key target, Class<? extends Annotation> scoping) {
super(base, scoping);
this.target = target;
}
public Key getTarget() {
return target;
}
@Override | // Path: src/weld/guiceconfig/attic/Binding.java
// public interface Binding {
//
// Key getKey();
//
// Class<? extends Annotation> getScoping();
//
// Binding withScoping(Class<? extends Annotation> annotationType);
//
// Binding withAnnotation(Class<? extends Annotation> qualifier);
// }
//
// Path: src/weld/guiceconfig/attic/Key.java
// public class Key {
//
// public final Class<?> clazz;
// public final Class<? extends Annotation> qualifier;
// private static final AtomicInteger count = new AtomicInteger();
//
// public Key(Class<?> clazz, Class<? extends Annotation> qualifier) {
// this.clazz = clazz;
// this.qualifier = qualifier;
// }
//
// public Key(Class<?> target) {
// this.clazz = target;
// this.qualifier = HardDefault.class;
// }
//
// public static <T, A extends Annotation> Key newKey(Class<T> clazz, Class<A> qualifier) {
// return new Key(clazz, qualifier);
// }
//
//
// @Override
// public String toString() {
// return "Key{" +
// "clazz=" + clazz +
// ", qualifier=" + qualifier +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (qualifier != null ? !qualifier.equals(key.qualifier) : key.qualifier != null) return false;
// if (clazz != null ? !clazz.equals(key.clazz) : key.clazz != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = clazz != null ? clazz.hashCode() : 0;
// result = 31 * result + (qualifier != null ? qualifier.hashCode() : 0);
// return result;
// }
//
// public static Key newKey(Class<?> target) {
// return new Key(target);
// }
// }
// Path: src/weld/guiceconfig/attic/internal/LinkedKeyBinding.java
import weld.guiceconfig.attic.Binding;
import weld.guiceconfig.attic.Key;
import java.lang.annotation.Annotation;
/*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic.internal;
/**
* Part of Fluent API configuration option.
*
* @author Alen Vrecko
*/
public class LinkedKeyBinding extends DefaultBinding {
private final Key target;
public LinkedKeyBinding(Key key, Class<?> target) {
super(key);
this.target = Key.newKey(target);
}
public LinkedKeyBinding(Key base, Key target, Class<? extends Annotation> scoping) {
super(base, scoping);
this.target = target;
}
public Key getTarget() {
return target;
}
@Override | public Binding withScoping(Class<? extends Annotation> scoping) { |
avrecko/weld-guiceconfig | src/weld/guiceconfig/attic/AbstractModule.java | // Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
| import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder; | /*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic;
/**
* Conveniance API.
*
* @author Alen Vrecko
*/
public abstract class AbstractModule implements Module {
private Binder binder;
public void configure(Binder binder) {
this.binder = binder;
configure();
}
public abstract void configure();
| // Path: src/weld/guiceconfig/attic/binder/AnnotatedBindingBuilder.java
// public interface AnnotatedBindingBuilder<E> extends LinkedBindingBuilder<E> {
//
// LinkedBindingBuilder<E> annotatedWith(Class<? extends Annotation> qualifier);
// }
// Path: src/weld/guiceconfig/attic/AbstractModule.java
import weld.guiceconfig.attic.binder.AnnotatedBindingBuilder;
/*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig.attic;
/**
* Conveniance API.
*
* @author Alen Vrecko
*/
public abstract class AbstractModule implements Module {
private Binder binder;
public void configure(Binder binder) {
this.binder = binder;
configure();
}
public abstract void configure();
| protected <E> AnnotatedBindingBuilder<E> bind(Class<E> clazz) { |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
| import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter; | package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
// Path: src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java
import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter;
package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override | public ExchangeFilterFunction build(List<RequestProcessor> requestProcessors, List<ResponseProcessor> responseProcessors, Logger logger, LogLevel logLevel) { |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
| import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter; | package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
// Path: src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java
import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter;
package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override | public ExchangeFilterFunction build(List<RequestProcessor> requestProcessors, List<ResponseProcessor> responseProcessors, Logger logger, LogLevel logLevel) { |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
| import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter; | package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
// Path: src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java
import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter;
package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override | public ExchangeFilterFunction build(List<RequestProcessor> requestProcessors, List<ResponseProcessor> responseProcessors, Logger logger, LogLevel logLevel) { |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
| import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter; | package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
// Path: src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java
import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter;
package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override | public ExchangeFilterFunction build(List<RequestProcessor> requestProcessors, List<ResponseProcessor> responseProcessors, Logger logger, LogLevel logLevel) { |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
| import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter; | package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override
public ExchangeFilterFunction build(List<RequestProcessor> requestProcessors, List<ResponseProcessor> responseProcessors, Logger logger, LogLevel logLevel) {
ExchangeFilterFunction exchangeFilterFunction = null;
if (!requestProcessors.isEmpty()) {
RequestProcessor requestProcessor = requestProcessors.stream()
.reduce(RequestProcessor::andThen)
.orElseGet(() -> clientRequest -> clientRequest);
| // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
// Path: src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java
import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter;
package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override
public ExchangeFilterFunction build(List<RequestProcessor> requestProcessors, List<ResponseProcessor> responseProcessors, Logger logger, LogLevel logLevel) {
ExchangeFilterFunction exchangeFilterFunction = null;
if (!requestProcessors.isEmpty()) {
RequestProcessor requestProcessor = requestProcessors.stream()
.reduce(RequestProcessor::andThen)
.orElseGet(() -> clientRequest -> clientRequest);
| exchangeFilterFunction = requestProcessorFilter(requestProcessor); |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
| import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter; | package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override
public ExchangeFilterFunction build(List<RequestProcessor> requestProcessors, List<ResponseProcessor> responseProcessors, Logger logger, LogLevel logLevel) {
ExchangeFilterFunction exchangeFilterFunction = null;
if (!requestProcessors.isEmpty()) {
RequestProcessor requestProcessor = requestProcessors.stream()
.reduce(RequestProcessor::andThen)
.orElseGet(() -> clientRequest -> clientRequest);
exchangeFilterFunction = requestProcessorFilter(requestProcessor);
}
if (logger != null && logLevel != null) {
ExchangeFilterFunction loggingExchangeFilterFunction = ExchangeFilterFunctions.loggingFilter(logger, logLevel);
exchangeFilterFunction = exchangeFilterFunction == null?
loggingExchangeFilterFunction :
exchangeFilterFunction.andThen(loggingExchangeFilterFunction);
}
if (!responseProcessors.isEmpty()) {
ResponseProcessor responseProcessor = responseProcessors.stream()
.reduce(ResponseProcessor::andThen)
.orElseGet(() -> clientResponse -> clientResponse);
| // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction requestProcessorFilter(RequestProcessor requestProcessor) {
// return ofRequestProcessor(clientRequest -> Mono.just(requestProcessor.process(clientRequest)));
// }
//
// Path: src/main/java/com/webfluxclient/client/ExchangeFilterFunctions.java
// static ExchangeFilterFunction responseInterceptorFilter(ResponseProcessor responseProcessor) {
// return ofResponseProcessor(clientResponse -> Mono.just(responseProcessor.process(clientResponse)));
// }
// Path: src/main/java/com/webfluxclient/client/DefaultExchangeFilterFunctionFactory.java
import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import java.util.List;
import static com.webfluxclient.client.ExchangeFilterFunctions.requestProcessorFilter;
import static com.webfluxclient.client.ExchangeFilterFunctions.responseInterceptorFilter;
package com.webfluxclient.client;
public class DefaultExchangeFilterFunctionFactory implements ExchangeFilterFunctionFactory {
@Override
public ExchangeFilterFunction build(List<RequestProcessor> requestProcessors, List<ResponseProcessor> responseProcessors, Logger logger, LogLevel logLevel) {
ExchangeFilterFunction exchangeFilterFunction = null;
if (!requestProcessors.isEmpty()) {
RequestProcessor requestProcessor = requestProcessors.stream()
.reduce(RequestProcessor::andThen)
.orElseGet(() -> clientRequest -> clientRequest);
exchangeFilterFunction = requestProcessorFilter(requestProcessor);
}
if (logger != null && logLevel != null) {
ExchangeFilterFunction loggingExchangeFilterFunction = ExchangeFilterFunctions.loggingFilter(logger, logLevel);
exchangeFilterFunction = exchangeFilterFunction == null?
loggingExchangeFilterFunction :
exchangeFilterFunction.andThen(loggingExchangeFilterFunction);
}
if (!responseProcessors.isEmpty()) {
ResponseProcessor responseProcessor = responseProcessors.stream()
.reduce(ResponseProcessor::andThen)
.orElseGet(() -> clientResponse -> clientResponse);
| ExchangeFilterFunction responseInterceptorFilter = responseInterceptorFilter(responseProcessor); |
jbrixhe/spring-webflux-client | src/test/java/com/webfluxclient/client/DefaultRequestExecutorTest.java | // Path: src/main/java/com/webfluxclient/metadata/request/Request.java
// public interface Request {
//
// HttpMethod httpMethod();
//
// HttpHeaders headers();
//
// Map<String, Object> variables();
//
// BodyInserter<?, ? super ClientHttpRequest> bodyInserter();
//
// URI expand();
// }
| import com.webfluxclient.metadata.request.Request;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ExchangeFunction;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.net.URI;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*; | package com.webfluxclient.client;
@RunWith(MockitoJUnitRunner.class)
public class DefaultRequestExecutorTest {
@Mock
private ExchangeFunction exchangeFunction;
@Captor
private ArgumentCaptor<ClientRequest> captor;
private DefaultRequestExecutor requestExecutor;
@Before
public void setup() throws Exception {
requestExecutor = create();
when(this.exchangeFunction.exchange(captor.capture())).thenReturn(Mono.empty());
}
@Test
public void execute() { | // Path: src/main/java/com/webfluxclient/metadata/request/Request.java
// public interface Request {
//
// HttpMethod httpMethod();
//
// HttpHeaders headers();
//
// Map<String, Object> variables();
//
// BodyInserter<?, ? super ClientHttpRequest> bodyInserter();
//
// URI expand();
// }
// Path: src/test/java/com/webfluxclient/client/DefaultRequestExecutorTest.java
import com.webfluxclient.metadata.request.Request;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ExchangeFunction;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.net.URI;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
package com.webfluxclient.client;
@RunWith(MockitoJUnitRunner.class)
public class DefaultRequestExecutorTest {
@Mock
private ExchangeFunction exchangeFunction;
@Captor
private ArgumentCaptor<ClientRequest> captor;
private DefaultRequestExecutor requestExecutor;
@Before
public void setup() throws Exception {
requestExecutor = create();
when(this.exchangeFunction.exchange(captor.capture())).thenReturn(Mono.empty());
}
@Test
public void execute() { | Request request = new MockRequest("http://example.ca", HttpMethod.GET); |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/codec/HttpClientErrorDecoder.java | // Path: src/main/java/com/webfluxclient/utils/DataBuffers.java
// public class DataBuffers {
//
// public static String readToString(DataBuffer dataBuffer) {
// try {
// return FileCopyUtils.copyToString(new InputStreamReader(dataBuffer.asInputStream()));
// }
// catch (IOException e) {
// return e.getMessage();
// }
// }
// }
| import com.webfluxclient.utils.DataBuffers;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus; | package com.webfluxclient.codec;
public class HttpClientErrorDecoder implements ErrorDecoder<HttpClientException> {
@Override
public boolean canDecode(HttpStatus httpStatus) {
return httpStatus.is4xxClientError();
}
@Override
public HttpClientException decode(HttpStatus httpStatus, DataBuffer inputMessage) { | // Path: src/main/java/com/webfluxclient/utils/DataBuffers.java
// public class DataBuffers {
//
// public static String readToString(DataBuffer dataBuffer) {
// try {
// return FileCopyUtils.copyToString(new InputStreamReader(dataBuffer.asInputStream()));
// }
// catch (IOException e) {
// return e.getMessage();
// }
// }
// }
// Path: src/main/java/com/webfluxclient/codec/HttpClientErrorDecoder.java
import com.webfluxclient.utils.DataBuffers;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
package com.webfluxclient.codec;
public class HttpClientErrorDecoder implements ErrorDecoder<HttpClientException> {
@Override
public boolean canDecode(HttpStatus httpStatus) {
return httpStatus.is4xxClientError();
}
@Override
public HttpClientException decode(HttpStatus httpStatus, DataBuffer inputMessage) { | return new HttpClientException(httpStatus, DataBuffers.readToString(inputMessage)); |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/client/DefaultRequestExecutor.java | // Path: src/main/java/com/webfluxclient/metadata/request/Request.java
// public interface Request {
//
// HttpMethod httpMethod();
//
// HttpHeaders headers();
//
// Map<String, Object> variables();
//
// BodyInserter<?, ? super ClientHttpRequest> bodyInserter();
//
// URI expand();
// }
| import com.webfluxclient.metadata.request.Request;
import lombok.AllArgsConstructor;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono; | package com.webfluxclient.client;
@AllArgsConstructor
public class DefaultRequestExecutor implements RequestExecutor {
private WebClient webClient;
@Override | // Path: src/main/java/com/webfluxclient/metadata/request/Request.java
// public interface Request {
//
// HttpMethod httpMethod();
//
// HttpHeaders headers();
//
// Map<String, Object> variables();
//
// BodyInserter<?, ? super ClientHttpRequest> bodyInserter();
//
// URI expand();
// }
// Path: src/main/java/com/webfluxclient/client/DefaultRequestExecutor.java
import com.webfluxclient.metadata.request.Request;
import lombok.AllArgsConstructor;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
package com.webfluxclient.client;
@AllArgsConstructor
public class DefaultRequestExecutor implements RequestExecutor {
private WebClient webClient;
@Override | public Mono<ClientResponse> execute(Request request) { |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/metadata/annotation/RequestHeaderParameterProcessor.java | // Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
| import com.webfluxclient.metadata.MethodMetadata;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type; | /*
* Copyright 2013-2015 the original author or authors.
*
* 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.webfluxclient.metadata.annotation;
public class RequestHeaderParameterProcessor implements AnnotatedParameterProcessor {
@Override
public Class<? extends Annotation> getAnnotationType() {
return RequestHeader.class;
}
@Override | // Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
// Path: src/main/java/com/webfluxclient/metadata/annotation/RequestHeaderParameterProcessor.java
import com.webfluxclient.metadata.MethodMetadata;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/*
* Copyright 2013-2015 the original author or authors.
*
* 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.webfluxclient.metadata.annotation;
public class RequestHeaderParameterProcessor implements AnnotatedParameterProcessor {
@Override
public Class<? extends Annotation> getAnnotationType() {
return RequestHeader.class;
}
@Override | public void processAnnotation(MethodMetadata.Builder requestTemplateBuilder, Annotation annotation, Integer integer, Type parameterType) { |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/handler/ReactiveInvocationHandlerFactory.java | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/codec/ExtendedClientCodecConfigurer.java
// public interface ExtendedClientCodecConfigurer extends ClientCodecConfigurer {
//
// List<HttpErrorReader> getErrorReaders();
//
// ExtendedCustomCodecs customCodecs();
//
// ExtendedClientDefaultCodecs defaultCodecs();
//
// static ExtendedClientCodecConfigurer create(){
// return new DefaultExtendedClientCodecConfigurer();
// }
//
// interface ExtendedClientDefaultCodecs extends ClientDefaultCodecs {
// void httpClientErrorDecoder(HttpClientErrorDecoder clientErrorDecoder);
// void httpServerErrorDecoder(HttpServerErrorDecoder serverErrorDecoder);
// }
//
// interface ExtendedCustomCodecs extends CustomCodecs{
// void errorReader(HttpErrorReader errorReader);
// void errorDecoder(ErrorDecoder errorDecoder);
// }
// }
| import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import com.webfluxclient.codec.ExtendedClientCodecConfigurer;
import java.lang.reflect.InvocationHandler;
import java.net.URI;
import java.util.List; | package com.webfluxclient.handler;
public interface ReactiveInvocationHandlerFactory {
InvocationHandler build( | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/codec/ExtendedClientCodecConfigurer.java
// public interface ExtendedClientCodecConfigurer extends ClientCodecConfigurer {
//
// List<HttpErrorReader> getErrorReaders();
//
// ExtendedCustomCodecs customCodecs();
//
// ExtendedClientDefaultCodecs defaultCodecs();
//
// static ExtendedClientCodecConfigurer create(){
// return new DefaultExtendedClientCodecConfigurer();
// }
//
// interface ExtendedClientDefaultCodecs extends ClientDefaultCodecs {
// void httpClientErrorDecoder(HttpClientErrorDecoder clientErrorDecoder);
// void httpServerErrorDecoder(HttpServerErrorDecoder serverErrorDecoder);
// }
//
// interface ExtendedCustomCodecs extends CustomCodecs{
// void errorReader(HttpErrorReader errorReader);
// void errorDecoder(ErrorDecoder errorDecoder);
// }
// }
// Path: src/main/java/com/webfluxclient/handler/ReactiveInvocationHandlerFactory.java
import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import com.webfluxclient.codec.ExtendedClientCodecConfigurer;
import java.lang.reflect.InvocationHandler;
import java.net.URI;
import java.util.List;
package com.webfluxclient.handler;
public interface ReactiveInvocationHandlerFactory {
InvocationHandler build( | ExtendedClientCodecConfigurer codecConfigurer, |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/handler/ReactiveInvocationHandlerFactory.java | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/codec/ExtendedClientCodecConfigurer.java
// public interface ExtendedClientCodecConfigurer extends ClientCodecConfigurer {
//
// List<HttpErrorReader> getErrorReaders();
//
// ExtendedCustomCodecs customCodecs();
//
// ExtendedClientDefaultCodecs defaultCodecs();
//
// static ExtendedClientCodecConfigurer create(){
// return new DefaultExtendedClientCodecConfigurer();
// }
//
// interface ExtendedClientDefaultCodecs extends ClientDefaultCodecs {
// void httpClientErrorDecoder(HttpClientErrorDecoder clientErrorDecoder);
// void httpServerErrorDecoder(HttpServerErrorDecoder serverErrorDecoder);
// }
//
// interface ExtendedCustomCodecs extends CustomCodecs{
// void errorReader(HttpErrorReader errorReader);
// void errorDecoder(ErrorDecoder errorDecoder);
// }
// }
| import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import com.webfluxclient.codec.ExtendedClientCodecConfigurer;
import java.lang.reflect.InvocationHandler;
import java.net.URI;
import java.util.List; | package com.webfluxclient.handler;
public interface ReactiveInvocationHandlerFactory {
InvocationHandler build(
ExtendedClientCodecConfigurer codecConfigurer, | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/codec/ExtendedClientCodecConfigurer.java
// public interface ExtendedClientCodecConfigurer extends ClientCodecConfigurer {
//
// List<HttpErrorReader> getErrorReaders();
//
// ExtendedCustomCodecs customCodecs();
//
// ExtendedClientDefaultCodecs defaultCodecs();
//
// static ExtendedClientCodecConfigurer create(){
// return new DefaultExtendedClientCodecConfigurer();
// }
//
// interface ExtendedClientDefaultCodecs extends ClientDefaultCodecs {
// void httpClientErrorDecoder(HttpClientErrorDecoder clientErrorDecoder);
// void httpServerErrorDecoder(HttpServerErrorDecoder serverErrorDecoder);
// }
//
// interface ExtendedCustomCodecs extends CustomCodecs{
// void errorReader(HttpErrorReader errorReader);
// void errorDecoder(ErrorDecoder errorDecoder);
// }
// }
// Path: src/main/java/com/webfluxclient/handler/ReactiveInvocationHandlerFactory.java
import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import com.webfluxclient.codec.ExtendedClientCodecConfigurer;
import java.lang.reflect.InvocationHandler;
import java.net.URI;
import java.util.List;
package com.webfluxclient.handler;
public interface ReactiveInvocationHandlerFactory {
InvocationHandler build(
ExtendedClientCodecConfigurer codecConfigurer, | List<RequestProcessor> requestProcessors, |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/handler/ReactiveInvocationHandlerFactory.java | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/codec/ExtendedClientCodecConfigurer.java
// public interface ExtendedClientCodecConfigurer extends ClientCodecConfigurer {
//
// List<HttpErrorReader> getErrorReaders();
//
// ExtendedCustomCodecs customCodecs();
//
// ExtendedClientDefaultCodecs defaultCodecs();
//
// static ExtendedClientCodecConfigurer create(){
// return new DefaultExtendedClientCodecConfigurer();
// }
//
// interface ExtendedClientDefaultCodecs extends ClientDefaultCodecs {
// void httpClientErrorDecoder(HttpClientErrorDecoder clientErrorDecoder);
// void httpServerErrorDecoder(HttpServerErrorDecoder serverErrorDecoder);
// }
//
// interface ExtendedCustomCodecs extends CustomCodecs{
// void errorReader(HttpErrorReader errorReader);
// void errorDecoder(ErrorDecoder errorDecoder);
// }
// }
| import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import com.webfluxclient.codec.ExtendedClientCodecConfigurer;
import java.lang.reflect.InvocationHandler;
import java.net.URI;
import java.util.List; | package com.webfluxclient.handler;
public interface ReactiveInvocationHandlerFactory {
InvocationHandler build(
ExtendedClientCodecConfigurer codecConfigurer,
List<RequestProcessor> requestProcessors, | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/codec/ExtendedClientCodecConfigurer.java
// public interface ExtendedClientCodecConfigurer extends ClientCodecConfigurer {
//
// List<HttpErrorReader> getErrorReaders();
//
// ExtendedCustomCodecs customCodecs();
//
// ExtendedClientDefaultCodecs defaultCodecs();
//
// static ExtendedClientCodecConfigurer create(){
// return new DefaultExtendedClientCodecConfigurer();
// }
//
// interface ExtendedClientDefaultCodecs extends ClientDefaultCodecs {
// void httpClientErrorDecoder(HttpClientErrorDecoder clientErrorDecoder);
// void httpServerErrorDecoder(HttpServerErrorDecoder serverErrorDecoder);
// }
//
// interface ExtendedCustomCodecs extends CustomCodecs{
// void errorReader(HttpErrorReader errorReader);
// void errorDecoder(ErrorDecoder errorDecoder);
// }
// }
// Path: src/main/java/com/webfluxclient/handler/ReactiveInvocationHandlerFactory.java
import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import com.webfluxclient.codec.ExtendedClientCodecConfigurer;
import java.lang.reflect.InvocationHandler;
import java.net.URI;
import java.util.List;
package com.webfluxclient.handler;
public interface ReactiveInvocationHandlerFactory {
InvocationHandler build(
ExtendedClientCodecConfigurer codecConfigurer,
List<RequestProcessor> requestProcessors, | List<ResponseProcessor> responseProcessors, |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/handler/ReactiveInvocationHandlerFactory.java | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/codec/ExtendedClientCodecConfigurer.java
// public interface ExtendedClientCodecConfigurer extends ClientCodecConfigurer {
//
// List<HttpErrorReader> getErrorReaders();
//
// ExtendedCustomCodecs customCodecs();
//
// ExtendedClientDefaultCodecs defaultCodecs();
//
// static ExtendedClientCodecConfigurer create(){
// return new DefaultExtendedClientCodecConfigurer();
// }
//
// interface ExtendedClientDefaultCodecs extends ClientDefaultCodecs {
// void httpClientErrorDecoder(HttpClientErrorDecoder clientErrorDecoder);
// void httpServerErrorDecoder(HttpServerErrorDecoder serverErrorDecoder);
// }
//
// interface ExtendedCustomCodecs extends CustomCodecs{
// void errorReader(HttpErrorReader errorReader);
// void errorDecoder(ErrorDecoder errorDecoder);
// }
// }
| import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import com.webfluxclient.codec.ExtendedClientCodecConfigurer;
import java.lang.reflect.InvocationHandler;
import java.net.URI;
import java.util.List; | package com.webfluxclient.handler;
public interface ReactiveInvocationHandlerFactory {
InvocationHandler build(
ExtendedClientCodecConfigurer codecConfigurer,
List<RequestProcessor> requestProcessors,
List<ResponseProcessor> responseProcessors, | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/codec/ExtendedClientCodecConfigurer.java
// public interface ExtendedClientCodecConfigurer extends ClientCodecConfigurer {
//
// List<HttpErrorReader> getErrorReaders();
//
// ExtendedCustomCodecs customCodecs();
//
// ExtendedClientDefaultCodecs defaultCodecs();
//
// static ExtendedClientCodecConfigurer create(){
// return new DefaultExtendedClientCodecConfigurer();
// }
//
// interface ExtendedClientDefaultCodecs extends ClientDefaultCodecs {
// void httpClientErrorDecoder(HttpClientErrorDecoder clientErrorDecoder);
// void httpServerErrorDecoder(HttpServerErrorDecoder serverErrorDecoder);
// }
//
// interface ExtendedCustomCodecs extends CustomCodecs{
// void errorReader(HttpErrorReader errorReader);
// void errorDecoder(ErrorDecoder errorDecoder);
// }
// }
// Path: src/main/java/com/webfluxclient/handler/ReactiveInvocationHandlerFactory.java
import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import com.webfluxclient.codec.ExtendedClientCodecConfigurer;
import java.lang.reflect.InvocationHandler;
import java.net.URI;
import java.util.List;
package com.webfluxclient.handler;
public interface ReactiveInvocationHandlerFactory {
InvocationHandler build(
ExtendedClientCodecConfigurer codecConfigurer,
List<RequestProcessor> requestProcessors,
List<ResponseProcessor> responseProcessors, | Logger logger, |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/handler/ReactiveInvocationHandlerFactory.java | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/codec/ExtendedClientCodecConfigurer.java
// public interface ExtendedClientCodecConfigurer extends ClientCodecConfigurer {
//
// List<HttpErrorReader> getErrorReaders();
//
// ExtendedCustomCodecs customCodecs();
//
// ExtendedClientDefaultCodecs defaultCodecs();
//
// static ExtendedClientCodecConfigurer create(){
// return new DefaultExtendedClientCodecConfigurer();
// }
//
// interface ExtendedClientDefaultCodecs extends ClientDefaultCodecs {
// void httpClientErrorDecoder(HttpClientErrorDecoder clientErrorDecoder);
// void httpServerErrorDecoder(HttpServerErrorDecoder serverErrorDecoder);
// }
//
// interface ExtendedCustomCodecs extends CustomCodecs{
// void errorReader(HttpErrorReader errorReader);
// void errorDecoder(ErrorDecoder errorDecoder);
// }
// }
| import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import com.webfluxclient.codec.ExtendedClientCodecConfigurer;
import java.lang.reflect.InvocationHandler;
import java.net.URI;
import java.util.List; | package com.webfluxclient.handler;
public interface ReactiveInvocationHandlerFactory {
InvocationHandler build(
ExtendedClientCodecConfigurer codecConfigurer,
List<RequestProcessor> requestProcessors,
List<ResponseProcessor> responseProcessors,
Logger logger, | // Path: src/main/java/com/webfluxclient/LogLevel.java
// public enum LogLevel {
// /** No logs. */
// NONE,
//
// /**
// * Logs request and response lines.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: application/json
// *
// * <-- 200 OK POST /hello (22ms)
// * }</pre>
// */
// BASIC,
//
// /**
// * Logs request and response lines and their respective headers.
// *
// * <p>Example:
// * <pre>{@code
// * --> POST /hello
// * Content-Type: plain/text
// * Headers:
// * - Accept-Language: en
// * - Accept-Charset: UTF-8
// * --> END POST
// *
// * <-- 200 OK POST /hello (22ms)
// * Headers:
// * - Content-Type: plain/text
// * <-- END HTTP
// * }</pre>
// */
// HEADERS
// }
//
// Path: src/main/java/com/webfluxclient/Logger.java
// public interface Logger {
// void log(Supplier<String> messageSupplier);
// void log(String message);
// }
//
// Path: src/main/java/com/webfluxclient/RequestProcessor.java
// @FunctionalInterface
// public interface RequestProcessor {
//
// ClientRequest process(ClientRequest request);
//
// default RequestProcessor andThen(RequestProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/ResponseProcessor.java
// @FunctionalInterface
// public interface ResponseProcessor {
//
// ClientResponse process(ClientResponse clientResponse);
//
// default ResponseProcessor andThen(ResponseProcessor after) {
// Assert.notNull(after, "");
// return request -> after.process(process(request));
// }
// }
//
// Path: src/main/java/com/webfluxclient/codec/ExtendedClientCodecConfigurer.java
// public interface ExtendedClientCodecConfigurer extends ClientCodecConfigurer {
//
// List<HttpErrorReader> getErrorReaders();
//
// ExtendedCustomCodecs customCodecs();
//
// ExtendedClientDefaultCodecs defaultCodecs();
//
// static ExtendedClientCodecConfigurer create(){
// return new DefaultExtendedClientCodecConfigurer();
// }
//
// interface ExtendedClientDefaultCodecs extends ClientDefaultCodecs {
// void httpClientErrorDecoder(HttpClientErrorDecoder clientErrorDecoder);
// void httpServerErrorDecoder(HttpServerErrorDecoder serverErrorDecoder);
// }
//
// interface ExtendedCustomCodecs extends CustomCodecs{
// void errorReader(HttpErrorReader errorReader);
// void errorDecoder(ErrorDecoder errorDecoder);
// }
// }
// Path: src/main/java/com/webfluxclient/handler/ReactiveInvocationHandlerFactory.java
import com.webfluxclient.LogLevel;
import com.webfluxclient.Logger;
import com.webfluxclient.RequestProcessor;
import com.webfluxclient.ResponseProcessor;
import com.webfluxclient.codec.ExtendedClientCodecConfigurer;
import java.lang.reflect.InvocationHandler;
import java.net.URI;
import java.util.List;
package com.webfluxclient.handler;
public interface ReactiveInvocationHandlerFactory {
InvocationHandler build(
ExtendedClientCodecConfigurer codecConfigurer,
List<RequestProcessor> requestProcessors,
List<ResponseProcessor> responseProcessors,
Logger logger, | LogLevel logLevel, |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/handler/DefaultClientMethodHandler.java | // Path: src/main/java/com/webfluxclient/client/RequestExecutor.java
// public interface RequestExecutor {
// Mono<ClientResponse> execute(Request request);
// }
//
// Path: src/main/java/com/webfluxclient/client/ResponseBodyProcessor.java
// public interface ResponseBodyProcessor {
// Object process(Mono<ClientResponse> monoResponse, ResolvableType bodyType);
// }
//
// Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
//
// Path: src/main/java/com/webfluxclient/metadata/request/Request.java
// public interface Request {
//
// HttpMethod httpMethod();
//
// HttpHeaders headers();
//
// Map<String, Object> variables();
//
// BodyInserter<?, ? super ClientHttpRequest> bodyInserter();
//
// URI expand();
// }
| import com.webfluxclient.client.RequestExecutor;
import com.webfluxclient.client.ResponseBodyProcessor;
import com.webfluxclient.metadata.MethodMetadata;
import com.webfluxclient.metadata.request.Request;
import org.springframework.web.reactive.function.client.ClientResponse;
import reactor.core.publisher.Mono; | package com.webfluxclient.handler;
public class DefaultClientMethodHandler implements ClientMethodHandler {
private MethodMetadata methodMetadata; | // Path: src/main/java/com/webfluxclient/client/RequestExecutor.java
// public interface RequestExecutor {
// Mono<ClientResponse> execute(Request request);
// }
//
// Path: src/main/java/com/webfluxclient/client/ResponseBodyProcessor.java
// public interface ResponseBodyProcessor {
// Object process(Mono<ClientResponse> monoResponse, ResolvableType bodyType);
// }
//
// Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
//
// Path: src/main/java/com/webfluxclient/metadata/request/Request.java
// public interface Request {
//
// HttpMethod httpMethod();
//
// HttpHeaders headers();
//
// Map<String, Object> variables();
//
// BodyInserter<?, ? super ClientHttpRequest> bodyInserter();
//
// URI expand();
// }
// Path: src/main/java/com/webfluxclient/handler/DefaultClientMethodHandler.java
import com.webfluxclient.client.RequestExecutor;
import com.webfluxclient.client.ResponseBodyProcessor;
import com.webfluxclient.metadata.MethodMetadata;
import com.webfluxclient.metadata.request.Request;
import org.springframework.web.reactive.function.client.ClientResponse;
import reactor.core.publisher.Mono;
package com.webfluxclient.handler;
public class DefaultClientMethodHandler implements ClientMethodHandler {
private MethodMetadata methodMetadata; | private RequestExecutor requestExecutor; |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/handler/DefaultClientMethodHandler.java | // Path: src/main/java/com/webfluxclient/client/RequestExecutor.java
// public interface RequestExecutor {
// Mono<ClientResponse> execute(Request request);
// }
//
// Path: src/main/java/com/webfluxclient/client/ResponseBodyProcessor.java
// public interface ResponseBodyProcessor {
// Object process(Mono<ClientResponse> monoResponse, ResolvableType bodyType);
// }
//
// Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
//
// Path: src/main/java/com/webfluxclient/metadata/request/Request.java
// public interface Request {
//
// HttpMethod httpMethod();
//
// HttpHeaders headers();
//
// Map<String, Object> variables();
//
// BodyInserter<?, ? super ClientHttpRequest> bodyInserter();
//
// URI expand();
// }
| import com.webfluxclient.client.RequestExecutor;
import com.webfluxclient.client.ResponseBodyProcessor;
import com.webfluxclient.metadata.MethodMetadata;
import com.webfluxclient.metadata.request.Request;
import org.springframework.web.reactive.function.client.ClientResponse;
import reactor.core.publisher.Mono; | package com.webfluxclient.handler;
public class DefaultClientMethodHandler implements ClientMethodHandler {
private MethodMetadata methodMetadata;
private RequestExecutor requestExecutor; | // Path: src/main/java/com/webfluxclient/client/RequestExecutor.java
// public interface RequestExecutor {
// Mono<ClientResponse> execute(Request request);
// }
//
// Path: src/main/java/com/webfluxclient/client/ResponseBodyProcessor.java
// public interface ResponseBodyProcessor {
// Object process(Mono<ClientResponse> monoResponse, ResolvableType bodyType);
// }
//
// Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
//
// Path: src/main/java/com/webfluxclient/metadata/request/Request.java
// public interface Request {
//
// HttpMethod httpMethod();
//
// HttpHeaders headers();
//
// Map<String, Object> variables();
//
// BodyInserter<?, ? super ClientHttpRequest> bodyInserter();
//
// URI expand();
// }
// Path: src/main/java/com/webfluxclient/handler/DefaultClientMethodHandler.java
import com.webfluxclient.client.RequestExecutor;
import com.webfluxclient.client.ResponseBodyProcessor;
import com.webfluxclient.metadata.MethodMetadata;
import com.webfluxclient.metadata.request.Request;
import org.springframework.web.reactive.function.client.ClientResponse;
import reactor.core.publisher.Mono;
package com.webfluxclient.handler;
public class DefaultClientMethodHandler implements ClientMethodHandler {
private MethodMetadata methodMetadata;
private RequestExecutor requestExecutor; | private ResponseBodyProcessor responseBodyProcessor; |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/handler/DefaultClientMethodHandler.java | // Path: src/main/java/com/webfluxclient/client/RequestExecutor.java
// public interface RequestExecutor {
// Mono<ClientResponse> execute(Request request);
// }
//
// Path: src/main/java/com/webfluxclient/client/ResponseBodyProcessor.java
// public interface ResponseBodyProcessor {
// Object process(Mono<ClientResponse> monoResponse, ResolvableType bodyType);
// }
//
// Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
//
// Path: src/main/java/com/webfluxclient/metadata/request/Request.java
// public interface Request {
//
// HttpMethod httpMethod();
//
// HttpHeaders headers();
//
// Map<String, Object> variables();
//
// BodyInserter<?, ? super ClientHttpRequest> bodyInserter();
//
// URI expand();
// }
| import com.webfluxclient.client.RequestExecutor;
import com.webfluxclient.client.ResponseBodyProcessor;
import com.webfluxclient.metadata.MethodMetadata;
import com.webfluxclient.metadata.request.Request;
import org.springframework.web.reactive.function.client.ClientResponse;
import reactor.core.publisher.Mono; | package com.webfluxclient.handler;
public class DefaultClientMethodHandler implements ClientMethodHandler {
private MethodMetadata methodMetadata;
private RequestExecutor requestExecutor;
private ResponseBodyProcessor responseBodyProcessor;
DefaultClientMethodHandler(MethodMetadata methodMetadata,
RequestExecutor requestExecutor,
ResponseBodyProcessor responseBodyProcessor) {
this.methodMetadata = methodMetadata;
this.requestExecutor = requestExecutor;
this.responseBodyProcessor = responseBodyProcessor;
}
@Override
public Object invoke(Object[] args) { | // Path: src/main/java/com/webfluxclient/client/RequestExecutor.java
// public interface RequestExecutor {
// Mono<ClientResponse> execute(Request request);
// }
//
// Path: src/main/java/com/webfluxclient/client/ResponseBodyProcessor.java
// public interface ResponseBodyProcessor {
// Object process(Mono<ClientResponse> monoResponse, ResolvableType bodyType);
// }
//
// Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
//
// Path: src/main/java/com/webfluxclient/metadata/request/Request.java
// public interface Request {
//
// HttpMethod httpMethod();
//
// HttpHeaders headers();
//
// Map<String, Object> variables();
//
// BodyInserter<?, ? super ClientHttpRequest> bodyInserter();
//
// URI expand();
// }
// Path: src/main/java/com/webfluxclient/handler/DefaultClientMethodHandler.java
import com.webfluxclient.client.RequestExecutor;
import com.webfluxclient.client.ResponseBodyProcessor;
import com.webfluxclient.metadata.MethodMetadata;
import com.webfluxclient.metadata.request.Request;
import org.springframework.web.reactive.function.client.ClientResponse;
import reactor.core.publisher.Mono;
package com.webfluxclient.handler;
public class DefaultClientMethodHandler implements ClientMethodHandler {
private MethodMetadata methodMetadata;
private RequestExecutor requestExecutor;
private ResponseBodyProcessor responseBodyProcessor;
DefaultClientMethodHandler(MethodMetadata methodMetadata,
RequestExecutor requestExecutor,
ResponseBodyProcessor responseBodyProcessor) {
this.methodMetadata = methodMetadata;
this.requestExecutor = requestExecutor;
this.responseBodyProcessor = responseBodyProcessor;
}
@Override
public Object invoke(Object[] args) { | Request request = methodMetadata.getRequestTemplate().apply(args); |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/metadata/annotation/RequestParamParameterProcessor.java | // Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
| import com.webfluxclient.metadata.MethodMetadata;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type; | /*
* Copyright 2013-2015 the original author or authors.
*
* 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.webfluxclient.metadata.annotation;
public class RequestParamParameterProcessor implements AnnotatedParameterProcessor {
@Override
public Class<? extends Annotation> getAnnotationType() {
return RequestParam.class;
}
@Override | // Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
// Path: src/main/java/com/webfluxclient/metadata/annotation/RequestParamParameterProcessor.java
import com.webfluxclient.metadata.MethodMetadata;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/*
* Copyright 2013-2015 the original author or authors.
*
* 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.webfluxclient.metadata.annotation;
public class RequestParamParameterProcessor implements AnnotatedParameterProcessor {
@Override
public Class<? extends Annotation> getAnnotationType() {
return RequestParam.class;
}
@Override | public void processAnnotation(MethodMetadata.Builder requestTemplateBuilder, Annotation annotation, Integer integer, Type parameterType) { |
jbrixhe/spring-webflux-client | src/test/java/com/webfluxclient/metadata/MethodMetadataBuilderTest.java | // Path: src/main/java/com/webfluxclient/metadata/request/RequestTemplate.java
// @Getter
// @AllArgsConstructor
// public class RequestTemplate {
// private UriBuilder uriBuilder;
// private HttpMethod httpMethod;
// private RequestHeaders requestHeaders;
// private Integer bodyIndex;
// private ResolvableType requestBodyType;
// private MultiValueMap<Integer, String> variableIndexToName;
//
// public Request apply(Object[] args) {
// return new DefaultRequest(uriBuilder,
// httpMethod,
// requestHeaders.encode(args),
// nameToVariable(args),
// buildBody(args));
// }
//
// private BodyInserter<?, ? super ClientHttpRequest> buildBody(Object[] args) {
// if (bodyIndex == null) {
// return BodyInserters.empty();
// }
//
// Object body = args[bodyIndex];
// if (isDataBufferPublisher(requestBodyType)) {
// return BodyInserters.fromDataBuffers((Publisher<DataBuffer>) body);
// } else if (isPublisher(requestBodyType)) {
// return BodyInserters.fromPublisher((Publisher) body, requestBodyType.getGeneric(0).getRawClass());
// } else if (isResource(requestBodyType)) {
// return BodyInserters.fromResource((Resource) body);
// } else if (isFormData(requestBodyType)) {
// return BodyInserters.fromFormData((MultiValueMap<String, String>) body);
// } else {
// return BodyInserters.fromObject(body);
// }
// }
//
// private Map<String, Object> nameToVariable(Object[] args) {
// Map<String, Object> nameToVariable = new HashMap<>();
// variableIndexToName.forEach((variableIndex, variableNames) -> {
// variableNames
// .forEach(variableName -> nameToVariable.put(variableName, args[variableIndex]));
// });
// return nameToVariable;
// }
// }
| import com.webfluxclient.metadata.request.RequestTemplate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import java.net.URI;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat; | package com.webfluxclient.metadata;
@RunWith(MockitoJUnitRunner.class)
public class MethodMetadataBuilderTest {
@Test
public void addPath() { | // Path: src/main/java/com/webfluxclient/metadata/request/RequestTemplate.java
// @Getter
// @AllArgsConstructor
// public class RequestTemplate {
// private UriBuilder uriBuilder;
// private HttpMethod httpMethod;
// private RequestHeaders requestHeaders;
// private Integer bodyIndex;
// private ResolvableType requestBodyType;
// private MultiValueMap<Integer, String> variableIndexToName;
//
// public Request apply(Object[] args) {
// return new DefaultRequest(uriBuilder,
// httpMethod,
// requestHeaders.encode(args),
// nameToVariable(args),
// buildBody(args));
// }
//
// private BodyInserter<?, ? super ClientHttpRequest> buildBody(Object[] args) {
// if (bodyIndex == null) {
// return BodyInserters.empty();
// }
//
// Object body = args[bodyIndex];
// if (isDataBufferPublisher(requestBodyType)) {
// return BodyInserters.fromDataBuffers((Publisher<DataBuffer>) body);
// } else if (isPublisher(requestBodyType)) {
// return BodyInserters.fromPublisher((Publisher) body, requestBodyType.getGeneric(0).getRawClass());
// } else if (isResource(requestBodyType)) {
// return BodyInserters.fromResource((Resource) body);
// } else if (isFormData(requestBodyType)) {
// return BodyInserters.fromFormData((MultiValueMap<String, String>) body);
// } else {
// return BodyInserters.fromObject(body);
// }
// }
//
// private Map<String, Object> nameToVariable(Object[] args) {
// Map<String, Object> nameToVariable = new HashMap<>();
// variableIndexToName.forEach((variableIndex, variableNames) -> {
// variableNames
// .forEach(variableName -> nameToVariable.put(variableName, args[variableIndex]));
// });
// return nameToVariable;
// }
// }
// Path: src/test/java/com/webfluxclient/metadata/MethodMetadataBuilderTest.java
import com.webfluxclient.metadata.request.RequestTemplate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import java.net.URI;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
package com.webfluxclient.metadata;
@RunWith(MockitoJUnitRunner.class)
public class MethodMetadataBuilderTest {
@Test
public void addPath() { | RequestTemplate requestTemplate = MethodMetadata.newBuilder(URI.create("http://localhost:8080")) |
jbrixhe/spring-webflux-client | src/main/java/com/webfluxclient/metadata/annotation/RequestBodyParameterProcessor.java | // Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
| import com.webfluxclient.metadata.MethodMetadata;
import org.springframework.web.bind.annotation.RequestBody;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type; | /*
* Copyright 2013-2015 the original author or authors.
*
* 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.webfluxclient.metadata.annotation;
public class RequestBodyParameterProcessor implements AnnotatedParameterProcessor {
@Override
public Class<? extends Annotation> getAnnotationType() {
return RequestBody.class;
}
@Override | // Path: src/main/java/com/webfluxclient/metadata/MethodMetadata.java
// @Getter
// public class MethodMetadata {
// private Method targetMethod;
// private ResolvableType responseBodyType;
// private RequestTemplate requestTemplate;
//
// private MethodMetadata(Builder builder) {
// targetMethod = builder.targetMethod;
// responseBodyType = builder.returnType;
// requestTemplate = new RequestTemplate(
// builder.uriBuilder,
// builder.httpMethod,
// new RequestHeaders(builder.headers, builder.headerIndexToName),
// builder.bodyIndex,
// builder.bodyType,
// builder.variableIndexToName);
// }
//
// public static Builder newBuilder(URI baseUri) {
// return new Builder(baseUri.getScheme(), baseUri.getAuthority());
// }
//
// public static Builder newBuilder(MethodMetadata other) {
// return new Builder(other);
// }
//
// public static class Builder {
// private UriBuilder uriBuilder;
// private MultiValueMap<Integer, String> variableIndexToName;
// private Map<String, RequestHeader> headers;
// private Map<Integer, String> headerIndexToName;
// private HttpMethod httpMethod;
// private Method targetMethod;
// private Integer bodyIndex;
// private ResolvableType returnType;
// private ResolvableType bodyType;
//
// private Builder() {
// variableIndexToName = new LinkedMultiValueMap<>();
// headers = new HashMap<>();
// headerIndexToName = new HashMap<>();
// }
//
// public Builder(String scheme, String authority) {
// this();
// if (scheme != null && authority != null) {
// uriBuilder = new DefaultUriBuilderFactory(scheme + "://" + authority).builder();
// }
// else {
// uriBuilder = new DefaultUriBuilderFactory().builder();
// }
// }
//
// public Builder(MethodMetadata other) {
// this();
// uriBuilder = new DefaultUriBuilderFactory(other.getRequestTemplate().getUriBuilder().build().toString()).builder();
// variableIndexToName.putAll(other.getRequestTemplate().getVariableIndexToName());
// headers.putAll(other.getRequestTemplate().getRequestHeaders().getHeaders());
// headerIndexToName.putAll(other.getRequestTemplate().getRequestHeaders().getIndexToName());
// httpMethod = other.getRequestTemplate().getHttpMethod();
// targetMethod = other.getTargetMethod();
// }
//
// public Builder addPath(String path) {
// uriBuilder.path(path);
// return this;
// }
//
// public Builder addPathIndex(Integer index, String pathVariable) {
// this.variableIndexToName.add(index, pathVariable);
// return this;
// }
//
// public Builder addHeader(String name, String value) {
// headers.put(name, new RequestHeader.BasicRequestHeader(name, value));
// return this;
// }
//
// public Builder addHeader(Integer index, String name) {
// headers.put(name, new RequestHeader.DynamicRequestHeader(name));
// headerIndexToName.put(index, name);
// return this;
// }
//
// public Builder addParameter(Integer index, String name) {
// variableIndexToName.add(index, name);
// uriBuilder.query(name + "={" + name + "}");
// return this;
// }
//
// public Builder httpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// return this;
// }
//
// public Builder body(Integer bodyIndex, Type bodyType) {
// if (this.bodyType != null && this.bodyIndex != null) {
// throw new IllegalArgumentException();
// }
//
// this.bodyIndex = bodyIndex;
// this.bodyType = ResolvableType.forType(bodyType);
// return this;
// }
//
// public Builder targetMethod(Method targetMethod) {
// this.targetMethod = targetMethod;
// this.returnType = ResolvableType.forMethodReturnType(targetMethod);
// return this;
// }
//
// public MethodMetadata build() {
// return new MethodMetadata(this);
// }
// }
// }
// Path: src/main/java/com/webfluxclient/metadata/annotation/RequestBodyParameterProcessor.java
import com.webfluxclient.metadata.MethodMetadata;
import org.springframework.web.bind.annotation.RequestBody;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/*
* Copyright 2013-2015 the original author or authors.
*
* 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.webfluxclient.metadata.annotation;
public class RequestBodyParameterProcessor implements AnnotatedParameterProcessor {
@Override
public Class<? extends Annotation> getAnnotationType() {
return RequestBody.class;
}
@Override | public void processAnnotation(MethodMetadata.Builder requestTemplateBuilder, Annotation annotation, Integer index, Type parameterType) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.