index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc/support/BeanPropertyRowMapper.java | package ai.yue.library.data.jdbc.support;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
/**
* 增强 {@linkplain org.springframework.jdbc.core.BeanPropertyRowMapper},支持 {@linkplain FieldName} 注解
*
* @author ylyue
* @since 2020年2月24日
*/
public class BeanPropertyRowMapper<T> implements RowMapper<T> {
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
/** The class we are mapping to. */
@Nullable
private Class<T> mappedClass;
/** Whether we're strictly validating. */
private boolean checkFullyPopulated = false;
/** Whether we're defaulting primitives when mapping a null value. */
private boolean primitivesDefaultedForNullValue = false;
/** ConversionService for binding JDBC values to bean properties. */
@Nullable
private ConversionService conversionService = DefaultConversionService.getSharedInstance();
/** Map of the fields we provide mapping for. */
@Nullable
private Map<String, PropertyDescriptor> mappedFields;
/** Set of bean properties we provide mapping for. */
@Nullable
private Set<String> mappedProperties;
/**
* Create a new {@code BeanPropertyRowMapper} for bean-style configuration.
* @see #setMappedClass
* @see #setCheckFullyPopulated
*/
public BeanPropertyRowMapper() {
}
/**
* Create a new {@code BeanPropertyRowMapper}, accepting unpopulated
* properties in the target bean.
* <p>Consider using the {@link #newInstance} factory method instead,
* which allows for specifying the mapped type once only.
* @param mappedClass the class that each row should be mapped to
*/
public BeanPropertyRowMapper(Class<T> mappedClass) {
initialize(mappedClass);
}
/**
* Create a new {@code BeanPropertyRowMapper}.
* @param mappedClass the class that each row should be mapped to
* @param checkFullyPopulated whether we're strictly validating that
* all bean properties have been mapped from corresponding database fields
*/
public BeanPropertyRowMapper(Class<T> mappedClass, boolean checkFullyPopulated) {
initialize(mappedClass);
this.checkFullyPopulated = checkFullyPopulated;
}
/**
* Set the class that each row should be mapped to.
*/
public void setMappedClass(Class<T> mappedClass) {
if (this.mappedClass == null) {
initialize(mappedClass);
}
else {
if (this.mappedClass != mappedClass) {
throw new InvalidDataAccessApiUsageException("The mapped class can not be reassigned to map to " +
mappedClass + " since it is already providing mapping for " + this.mappedClass);
}
}
}
/**
* Get the class that we are mapping to.
*/
@Nullable
public final Class<T> getMappedClass() {
return this.mappedClass;
}
/**
* Set whether we're strictly validating that all bean properties have been mapped
* from corresponding database fields.
* <p>Default is {@code false}, accepting unpopulated properties in the target bean.
*/
public void setCheckFullyPopulated(boolean checkFullyPopulated) {
this.checkFullyPopulated = checkFullyPopulated;
}
/**
* Return whether we're strictly validating that all bean properties have been
* mapped from corresponding database fields.
*/
public boolean isCheckFullyPopulated() {
return this.checkFullyPopulated;
}
/**
* Set whether we're defaulting Java primitives in the case of mapping a null value
* from corresponding database fields.
* <p>Default is {@code false}, throwing an exception when nulls are mapped to Java primitives.
*/
public void setPrimitivesDefaultedForNullValue(boolean primitivesDefaultedForNullValue) {
this.primitivesDefaultedForNullValue = primitivesDefaultedForNullValue;
}
/**
* Return whether we're defaulting Java primitives in the case of mapping a null value
* from corresponding database fields.
*/
public boolean isPrimitivesDefaultedForNullValue() {
return this.primitivesDefaultedForNullValue;
}
/**
* Set a {@link ConversionService} for binding JDBC values to bean properties,
* or {@code null} for none.
* <p>Default is a {@link DefaultConversionService}, as of Spring 4.3. This
* provides support for {@code java.time} conversion and other special types.
* @since 4.3
* @see #initBeanWrapper(BeanWrapper)
*/
public void setConversionService(@Nullable ConversionService conversionService) {
this.conversionService = conversionService;
}
/**
* Return a {@link ConversionService} for binding JDBC values to bean properties,
* or {@code null} if none.
* @since 4.3
*/
@Nullable
public ConversionService getConversionService() {
return this.conversionService;
}
/**
* Initialize the mapping meta-data for the given class.
* @param mappedClass the mapped class
*/
protected void initialize(Class<T> mappedClass) {
this.mappedClass = mappedClass;
this.mappedFields = new HashMap<>();
this.mappedProperties = new HashSet<>();
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null) {
String databaseFieldName = AnnotationUtil.getAnnotationValue(ReflectUtil.getField(mappedClass, pd.getName()), FieldName.class);
if (StrUtil.isNotEmpty(databaseFieldName)) {
this.mappedFields.put(databaseFieldName, pd);
} else {
this.mappedFields.put(lowerCaseName(pd.getName()), pd);
String underscoredName = underscoreName(pd.getName());
if (!lowerCaseName(pd.getName()).equals(underscoredName)) {
this.mappedFields.put(underscoredName, pd);
}
}
this.mappedProperties.add(pd.getName());
}
}
}
/**
* Convert a name in camelCase to an underscored name in lower case.
* Any upper case letters are converted to lower case with a preceding underscore.
* @param name the original name
* @return the converted name
* @since 4.2
* @see #lowerCaseName
*/
protected String underscoreName(String name) {
if (!StringUtils.hasLength(name)) {
return "";
}
StringBuilder result = new StringBuilder();
result.append(lowerCaseName(name.substring(0, 1)));
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i + 1);
String slc = lowerCaseName(s);
if (!s.equals(slc)) {
result.append("_").append(slc);
}
else {
result.append(s);
}
}
return result.toString();
}
/**
* Convert the given name to lower case.
* By default, conversions will happen within the US locale.
* @param name the original name
* @return the converted name
* @since 4.2
*/
protected String lowerCaseName(String name) {
return name.toLowerCase(Locale.US);
}
/**
* Extract the values for all columns in the current row.
* <p>Utilizes public setters and result set meta-data.
* @see java.sql.ResultSetMetaData
*/
@Override
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
Assert.state(this.mappedClass != null, "Mapped class was not specified");
T mappedObject = BeanUtils.instantiateClass(this.mappedClass);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
initBeanWrapper(bw);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<>() : null);
for (int index = 1; index <= columnCount; index++) {
String column = JdbcUtils.lookupColumnName(rsmd, index);
String field = lowerCaseName(StringUtils.delete(column, " "));
PropertyDescriptor pd = (this.mappedFields != null ? this.mappedFields.get(field) : null);
if (pd != null) {
try {
Object value = getColumnValue(rs, index, pd);
if (rowNumber == 0 && logger.isDebugEnabled()) {
logger.debug("Mapping column '" + column + "' to property '" + pd.getName() +
"' of type '" + ClassUtils.getQualifiedName(pd.getPropertyType()) + "'");
}
try {
bw.setPropertyValue(pd.getName(), value);
}
catch (TypeMismatchException ex) {
if (value == null && this.primitivesDefaultedForNullValue) {
if (logger.isDebugEnabled()) {
logger.debug("Intercepted TypeMismatchException for row " + rowNumber +
" and column '" + column + "' with null value when setting property '" +
pd.getName() + "' of type '" +
ClassUtils.getQualifiedName(pd.getPropertyType()) +
"' on object: " + mappedObject, ex);
}
}
else {
throw ex;
}
}
if (populatedProperties != null) {
populatedProperties.add(pd.getName());
}
}
catch (NotWritablePropertyException ex) {
throw new DataRetrievalFailureException(
"Unable to map column '" + column + "' to property '" + pd.getName() + "'", ex);
}
}
else {
// No PropertyDescriptor found
if (rowNumber == 0 && logger.isDebugEnabled()) {
logger.debug("No property found for column '" + column + "' mapped to field '" + field + "'");
}
}
}
if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " +
"necessary to populate object of class [" + this.mappedClass.getName() + "]: " +
this.mappedProperties);
}
return mappedObject;
}
/**
* Initialize the given BeanWrapper to be used for row mapping.
* To be called for each row.
* <p>The default implementation applies the configured {@link ConversionService},
* if any. Can be overridden in subclasses.
* @param bw the BeanWrapper to initialize
* @see #getConversionService()
* @see BeanWrapper#setConversionService
*/
protected void initBeanWrapper(BeanWrapper bw) {
ConversionService cs = getConversionService();
if (cs != null) {
bw.setConversionService(cs);
}
}
/**
* Retrieve a JDBC object value for the specified column.
* <p>The default implementation calls
* {@link JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)}.
* Subclasses may override this to check specific value types upfront,
* or to post-process values return from {@code getResultSetValue}.
* @param rs is the ResultSet holding the data
* @param index is the column index
* @param pd the bean property that each result object is expected to match
* @return the Object value
* @throws SQLException in case of extraction failure
* @see org.springframework.jdbc.support.JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)
*/
@Nullable
protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {
return JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
}
/**
* Static factory method to create a new {@code BeanPropertyRowMapper}
* (with the mapped class specified only once).
* @param mappedClass the class that each row should be mapped to
*/
public static <T> BeanPropertyRowMapper<T> newInstance(Class<T> mappedClass) {
return new BeanPropertyRowMapper<>(mappedClass);
}
}
|
0 | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc/support/FieldName.java | package ai.yue.library.data.jdbc.support;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 数据库字段名
*
* @author ylyue
* @since 2020年2月24日
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD })
public @interface FieldName {
/**
* <b>数据库字段名,用于绑定关系映射</b>
* <p>成员变量名称:deleted
* <p>数据库字段名称:is_deleted
* <p>示例代码如下:
* <p><code>
* @FieldName("is_deleted")<br>
private boolean deleted;
* </code>
*/
String value() default "";
}
|
0 | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc/vo/PageBeforeAndAfterVO.java | package ai.yue.library.data.jdbc.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 分页上下条数据VO
*
* @author ylyue
* @since 2018年10月10日
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PageBeforeAndAfterVO {
/** 上一条数据ID */
Long beforeId;
/** 下一条数据ID */
Long afterId;
}
|
0 | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc/vo/PageTVO.java | package ai.yue.library.data.jdbc.vo;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import ai.yue.library.base.view.Result;
import ai.yue.library.base.view.ResultInfo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 分页查询结果
*
* @author ylyue
* @since 2018年7月18日
*/
@Data
@Builder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
public class PageTVO<T> {
/** 总数 */
Long count;
/** 分页列表数据 */
List<T> data;
public JSONObject toJSONObject() {
JSONObject json = new JSONObject();
json.put("count", count);
json.put("data", data);
return json;
}
/**
* 将分页结果转换成最外层响应对象
*
* @return HTTP请求,最外层响应对象
*/
public Result<List<T>> toResult() {
return ResultInfo.success(count, data);
}
}
|
0 | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc/vo/PageVO.java | package ai.yue.library.data.jdbc.vo;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import ai.yue.library.base.view.Result;
import ai.yue.library.base.view.ResultInfo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 分页查询结果
*
* @author ylyue
* @since 2018年7月18日
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PageVO {
/** 总数 */
Long count;
/** 分页列表数据 */
List<JSONObject> data;
public JSONObject toJSONObject() {
JSONObject json = new JSONObject();
json.put("count", count);
json.put("data", data);
return json;
}
/**
* 将分页结果转换成最外层响应对象
*
* @return HTTP请求,最外层响应对象
*/
public Result<List<JSONObject>> toResult() {
return ResultInfo.success(count, data);
}
}
|
0 | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc | java-sources/ai/ylyue/yue-library-data-jdbc/2.1.0/ai/yue/library/data/jdbc/vo/package-info.java | /**
* VO定义
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.data.jdbc.vo; |
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/package-info.java | /**
* data-mybatis库基于MyBatis-Plus进行二次封装,拥有着强大性能的同时又不失简单、灵活
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.data.mybatis; |
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/constant/DbConstant.java | package ai.yue.library.data.mybatis.constant;
/**
* Db常量定义
*
* @author ylyue
* @since 2018年7月18日
*/
public class DbConstant {
// ====================== 类字段名定义 ======================
/** 系统租户:一级租户(dict_tenant_sys) */
public static final String CLASS_FIELD_DEFINITION_TENANT_SYS = "tenantSys";
/** 企业租户:二级租户 */
public static final String CLASS_FIELD_DEFINITION_TENANT_CO = "tenantCo";
/** 删除时间:逻辑删除 */
public static final String CLASS_FIELD_DEFINITION_DELETE_TIME = "deleteTime";
// ====================== 数据库字段名定义 ======================
/** 系统租户:一级租户(dict_tenant_sys) */
public static final String DB_FIELD_DEFINITION_TENANT_SYS = "tenant_sys";
/** 企业租户:二级租户 */
public static final String DB_FIELD_DEFINITION_TENANT_CO = "tenant_co";
/** 删除时间:逻辑删除 */
public static final String DB_FIELD_DEFINITION_DELETE_TIME = "delete_time";
}
|
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/constant/DbCrudEnum.java | package ai.yue.library.data.mybatis.constant;
/**
* 增删改查动作定义
*
* @author ylyue
* @since 2021/7/27
*/
public enum DbCrudEnum {
/**
* 原译:创建;
* 释义:新增;
*/
C,
/**
* 原译:读取;
* 释义:查询;
*/
R,
/**
* 更新
*/
U,
/**
* 删除
*/
D
}
|
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/constant/DbExpectedEnum.java | package ai.yue.library.data.mybatis.constant;
import ai.yue.library.base.constant.CompareEnum;
/**
* 预期类型
* <p>遵守 {@linkplain CompareEnum} 标准
*
* @author ylyue
* @since 2018年9月18日
*/
public enum DbExpectedEnum {
/** 等于(equal to) */
EQ,
/** 大于等于(greater than or equal to) */
GE;
}
|
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/constant/DbUpdateEnum.java | package ai.yue.library.data.mybatis.constant;
/**
* 更新类型
*
* @author ylyue
* @since 2018年8月29日
*/
public enum DbUpdateEnum {
/** 正常 */
NORMAL,
/** 递增 */
INCREMENT,
/** 递减 */
DECR,
/** 递减_无符号 */
DECR_UNSIGNED;
}
|
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/constant/package-info.java | /**
* 常量定义
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.data.mybatis.constant; |
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/entity/BaseEntity.java | package ai.yue.library.data.mybatis.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <h2>RESTful驼峰命名法基础实体</h2><br>
*
* <b><code style="color:red">注意子类使用Lombok重写toString()与equals()和hashCode()方法时,callSuper属性需为true,如下:</code></b>
* <blockquote>
* <p>@ToString(callSuper = true)
* <p>@EqualsAndHashCode(callSuper = true)
* </blockquote><br>
*
* <b><code style="color:red">注意子类使用Lombok生成builder()方法时,需使用@SuperBuilder注解,而非@Builder注解,如下:</code></b>
* <blockquote>
* <p>@NoArgsConstructor
* <p>@AllArgsConstructor
* <p>@SuperBuilder(toBuilder = true)
* </blockquote><br>
*
* <a href="https://ylyue.cn/#/data/jdbc/DO基类">👉点击查看关于DO基类的详细使用介绍</a>
*
* @author ylyue
* @since 2018年7月26日
*/
@Data
@NoArgsConstructor
@SuperBuilder(toBuilder = true)
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = 2241197545628586478L;
/**
* 有序主键:单表时数据库自增、分布式时雪花自增
*/
@TableId
protected Long id;
/**
* 排序索引
*/
protected Integer sortIdx;
/**
* 创建人:用户名、昵称、人名
*/
@TableField(fill = FieldFill.INSERT)
protected String createUser;
/**
* 创建人:用户id
*/
@TableField(fill = FieldFill.INSERT)
protected String createUserId;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
protected LocalDateTime createTime;
/**
* 更新人:用户名、昵称、人名
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
protected String updateUser;
/**
* 更新人:用户id
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
protected String updateUserId;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
protected LocalDateTime updateTime;
/**
* 删除时间:默认0(未删除)
* <p>一般不作查询展示
*/
@TableLogic(delval = "now()")
protected Long deleteTime;
}
|
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/entity/package-info.java | /**
* RESTful基础实体
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.data.mybatis.entity; |
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/interceptor/LogicDeleteInnerInterceptor.java | package ai.yue.library.data.mybatis.interceptor;
import ai.yue.library.data.mybatis.constant.DbConstant;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.statement.insert.Insert;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.sql.Connection;
import java.sql.SQLException;
/**
* 逻辑删除拦截器
*
* @author yl-yue
* @since 2023/2/20
*/
public class LogicDeleteInnerInterceptor extends TenantLineInnerInterceptor {
public LogicDeleteInnerInterceptor(String... ignoreTables) {
TenantLineHandler tenantLineHandler = new TenantLineHandler() {
@Override
public String getTenantIdColumn() {
return DbConstant.DB_FIELD_DEFINITION_DELETE_TIME;
}
@Override
public Expression getTenantId() {
return new LongValue(0L);
}
@Override
public boolean ignoreTable(String tableName) {
for (String ignoreTable : ignoreTables) {
if (tableName.equalsIgnoreCase(ignoreTable)) {
return true;
}
}
return false;
}
};
super.setTenantLineHandler(tenantLineHandler);
}
@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
if (StrUtil.containsAny(boundSql.getSql(), "delete_time=0", "delete_time = 0")) {
return;
}
super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
}
@Override
public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
if (StrUtil.containsAny(sh.getBoundSql().getSql(), "delete_time=0", "delete_time = 0")) {
return;
}
super.beforePrepare(sh, connection, transactionTimeout);
}
@Override
protected void processInsert(Insert insert, int index, String sql, Object obj) {
}
}
|
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/provider/AuditUserProvider.java | package ai.yue.library.data.mybatis.provider;
/**
* 审计用户信息提供
* <p>实现此接口,配置为Bean即可</p>
*
* @author ylyue
* @since 2021/7/27
*/
public interface AuditUserProvider {
/**
* 审计:用户名、昵称、人名
*
* @return 用户名、昵称、人名
*/
String getUser();
/**
* 审计:用户id
*
* @return 用户id
*/
String getUserId();
}
|
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/provider/DataAuditProvider.java | package ai.yue.library.data.mybatis.provider;
import ai.yue.library.base.util.SpringUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import java.time.LocalDateTime;
/**
* 数据审计提供者
*
* @author ylyue
* @since 2022/12/29
*/
@Slf4j
@Configuration
@ConditionalOnMissingBean(MetaObjectHandler.class)
@ConditionalOnProperty(prefix = "yue.data.mybatis", name = "enableDataAudit", havingValue = "true")
public class DataAuditProvider implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
// 1. 获得用户
String user = null;
String userId = null;
try {
user = SpringUtils.getBean(AuditUserProvider.class).getUser();
userId = SpringUtils.getBean(AuditUserProvider.class).getUserId();
} catch (Exception e) {
log.error("【数据审计】未找到合适的Bean:{}", AuditUserProvider.class);
throw e;
}
// 2. 新增填充(支持i18n)
this.strictInsertFill(metaObject, "createUser", String.class, user);
this.strictInsertFill(metaObject, "createUserId", String.class, userId);
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now(LocaleContextHolder.getTimeZone().toZoneId()));
this.strictInsertFill(metaObject, "updateUser", String.class, user);
this.strictInsertFill(metaObject, "updateUserId", String.class, userId);
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now(LocaleContextHolder.getTimeZone().toZoneId()));
}
@Override
public void updateFill(MetaObject metaObject) {
// 1. 获得用户
String user = null;
String userId = null;
try {
user = SpringUtils.getBean(AuditUserProvider.class).getUser();
userId = SpringUtils.getBean(AuditUserProvider.class).getUserId();
} catch (Exception e) {
log.error("【数据审计】未找到合适的Bean:{}", AuditUserProvider.class);
throw e;
}
// 2. 更新填充(支持i18n)
this.strictUpdateFill(metaObject, "updateUser", String.class, user);
this.strictUpdateFill(metaObject, "updateUserId", String.class, userId);
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now(LocaleContextHolder.getTimeZone().toZoneId()));
}
}
|
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/provider/package-info.java | /**
* 数据提供者定义(数据审计、数据填充)
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.data.mybatis.provider; |
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/service/BaseService.java | package ai.yue.library.data.mybatis.service;
import ai.yue.library.base.convert.Convert;
import ai.yue.library.base.view.R;
import ai.yue.library.base.view.Result;
import ai.yue.library.data.mybatis.entity.BaseEntity;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* <b>基础Service</b>
* <p>继承后即可获得符合RESTful风格的内置CRUD实现</p>
*
* @param <M> mapper 对象
* @param <T> 实体
*
* @author yl-yue
* @since 2022/12/29
*/
@Slf4j
@Getter
public abstract class BaseService<M extends BaseMapper<T>, T extends BaseEntity> {
@Autowired
protected M baseMapper;
private ServiceImpl<M, T> serviceImpl = new ServiceImpl<>();
@SuppressWarnings("unchecked")
protected Class<T> entityClass = (Class<T>) ClassUtil.getTypeArgument(getClass(), 1);
@PostConstruct
private void init() {
ReflectUtil.setFieldValue(serviceImpl, "baseMapper", baseMapper);
ReflectUtil.setFieldValue(serviceImpl, "entityClass", entityClass);
ReflectUtil.setFieldValue(serviceImpl, "mapperClass", (Class<T>) ClassUtil.getTypeArgument(getClass(), 0));
}
/**
* 插入数据
*
* @param entity 实体参数,支持实体对象、map、json
* @return 填充后的实体
*/
public Result<T> insert(Object entity) {
T entityObject = Convert.toJavaBean(entity, entityClass);
serviceImpl.save(entityObject);
return R.success(entityObject);
}
/**
* 插入数据-批量
*
* @param entityList 实体集合
* @return 是否成功
*/
public Result<Boolean> insertBatch(Collection<?> entityList) {
ArrayList<T> entityObjectList = new ArrayList<>(entityList.size());
for (Object entity : entityList) {
T entityObject = Convert.toJavaBean(entity, entityClass);
entityObjectList.add(entityObject);
}
boolean success = serviceImpl.saveBatch(entityObjectList);
return R.success(success);
}
/**
* 插入或更新数据
* <p><code>@TableId</code> 注解存在,则更新,否则插入</p>
*
* @param entity 实体参数,支持实体对象、map、json
* @return 填充后的实体
*/
@Transactional(rollbackFor = Exception.class)
public Result<T> insertOrUpdate(Object entity) {
T entityObject = Convert.toJavaBean(entity, entityClass);
serviceImpl.saveOrUpdate(entityObject);
return R.success(entityObject);
}
/**
* 插入或更新数据-批量
* <p><code>@TableId</code> 注解存在,则更新,否则插入</p>
*
* @param entityList 实体集合
*/
@Transactional(rollbackFor = Exception.class)
public Result<Boolean> insertOrUpdateBatch(Collection<?> entityList) {
ArrayList<T> entityObjectList = new ArrayList<>(entityList.size());
for (Object entity : entityList) {
T entityObject = Convert.toJavaBean(entity, entityClass);
entityObjectList.add(entityObject);
}
boolean success = serviceImpl.saveOrUpdateBatch(entityObjectList);
return R.success(success);
}
/**
* 删除-ById
*
* @param id 主键id
* @return 是否成功
*/
public Result<Boolean> deleteById(Long id) {
boolean success = serviceImpl.removeById(id);
return R.success(success);
}
/**
* 批量删除-ById
*
* @param list 主键ID或实体列表
*/
@Transactional(rollbackFor = Exception.class)
public Result<Boolean> deleteByIds(Collection<?> list) {
boolean success = serviceImpl.removeByIds(list);
return R.success(success);
}
/**
* 更新-ById
*
* @param entity 实体参数,支持实体对象、map、json
* @return 是否成功
*/
public Result<Boolean> updateById(Object entity) {
T entityObject = Convert.toJavaBean(entity, entityClass);
boolean success = serviceImpl.updateById(entityObject);
return R.success(success);
}
/**
* 批量更新-ById
*
* @param entityList 实体集合
*/
@Transactional(rollbackFor = Exception.class)
public Result<Boolean> updateBatchById(Collection<?> entityList) {
ArrayList<T> entityObjectList = new ArrayList<>(entityList.size());
for (Object entity : entityList) {
T entityObject = Convert.toJavaBean(entity, entityClass);
entityObjectList.add(entityObject);
}
boolean success = serviceImpl.updateBatchById(entityObjectList);
return R.success(success);
}
/**
* 单个-ById
*
* @param id 主键id
* @return 实体
*/
public Result<T> getById(Long id) {
T entity = serviceImpl.getById(id);
return R.success(entity);
}
/**
* 列表-全部
*
* @return 实体集合
*/
public Result<List<T>> listAll() {
return R.success(serviceImpl.list());
}
/**
* 分页
* <p>分页能力只在HttpServletRequest环境下生效,webflux、grpc等web项目,请自行调用PageHelper.startPage()方法,开启分页</p>
*
* @param entity 实体参数,支持实体对象、map、json
* @return 分页实体集合
*/
public Result<PageInfo<T>> page(@Nullable Object entity) {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
Object request = ReflectUtil.invoke(requestAttributes, "getRequest");
PageHelper.startPage(request);
} else if (PageHelper.getLocalPage() == null) {
log.error("BaseService.page()方法,分页能力只在HttpServletRequest下生效,如仍需使用,请自行调用PageHelper.startPage()方法,开启分页。");
}
T entityObject = Convert.toJavaBean(entity, entityClass);
QueryWrapper<T> queryWrapper = new QueryWrapper<>(entityObject);
List<T> list = serviceImpl.list(queryWrapper);
return R.success(PageInfo.of(list));
}
}
|
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/vo/PageBeforeAndAfterVO.java | package ai.yue.library.data.mybatis.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 分页上下条数据VO
*
* @author ylyue
* @since 2018年10月10日
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PageBeforeAndAfterVO {
/** 上一条数据ID */
Long beforeId;
/** 下一条数据ID */
Long afterId;
}
|
0 | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis | java-sources/ai/ylyue/yue-library-data-mybatis/j11.2.6.2/ai/yue/library/data/mybatis/vo/package-info.java | /**
* VO定义
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.data.mybatis.vo; |
0 | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis/package-info.java | /**
* data-redis库基于SpringRedis进行二次封装,更简单灵活,提供全局token与登录等特性
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.data.redis; |
0 | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis/client/Redis.java | package ai.yue.library.data.redis.client;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import ai.yue.library.base.convert.Convert;
import ai.yue.library.base.util.StringUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* <h2>简单Redis</h2>
* 命令详细说明请参照 Redis <a href="http://www.redis.net.cn/order">官方文档</a> 进行查阅
*
* @author ylyue
* @since 2018年3月27日
*/
@Slf4j
@AllArgsConstructor
public class Redis {
RedisTemplate<String, Object> redisTemplate;
StringRedisTemplate stringRedisTemplate;
// Redis分布式锁
/**
* Redis分布式锁-加锁
* <p>可用于实现接口幂等性、秒杀业务等场景需求
*
* @param lockKey 分布式锁的key(唯一性)
* @param lockTimeout 当前时间戳 + 超时毫秒
* @return 是否成功拿到锁
*/
public boolean lock(String lockKey, Long lockTimeout) {
String value = lockTimeout.toString();
// 1. 设置锁
if (stringRedisTemplate.opsForValue().setIfAbsent(lockKey, value)) {
return true;
}
// 2. 锁设置失败,拿到当前锁
String currentValue = stringRedisTemplate.opsForValue().get(lockKey);
// 3. 判断当前锁是否过期
if (!StringUtils.isEmpty(currentValue) && Long.parseLong(currentValue) < System.currentTimeMillis()) {
// 4. 锁已过期 ,设置新锁同时得到上一个锁
String oldValue = stringRedisTemplate.opsForValue().getAndSet(lockKey, value);
// 5. 确认新锁是否设置成功(判断当前锁与上一个锁是否相等)
if (!StringUtils.isEmpty(oldValue) && oldValue.equals(currentValue)) {
// 此处只会有一个线程拿到锁
return true;
}
}
return false;
}
/**
* Redis分布式锁-解锁
*
* @param lockKey 分布式锁的key(唯一性)
* @param lockTimeout 加锁时使用的超时时间戳
*/
public void unlock(String lockKey, Long lockTimeout) {
String value = lockTimeout.toString();
try {
String currentValue = stringRedisTemplate.opsForValue().get(lockKey);
if (StringUtils.isNotEmpty(currentValue) && currentValue.equals(value)) {
stringRedisTemplate.opsForValue().getOperations().delete(lockKey);
}
} catch (Exception e) {
log.error("【redis分布式锁】解锁异常,{}", e);
}
}
// Key(键),简单的key-value操作
/**
* 实现命令:TTL key,以秒为单位,返回给定 key的剩余生存时间(TTL, time to live)。
*
* @param key key
* @return key的剩余生存时间(单位:秒)
*/
public long ttl(String key) {
return stringRedisTemplate.getExpire(key);
}
/**
* 实现命令:expire 设置过期时间,单位秒
*
* @param key key
* @param timeout 过期时间(单位:秒)
*/
public void expire(String key, long timeout) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
/**
* 实现命令:INCR key,将 key 中储存的数字值按增量递增。
*
* @param key 不能为空
* @param delta 增量数字
* @return 递增后的值
*/
public long incr(String key, long delta) {
return stringRedisTemplate.opsForValue().increment(key, delta);
}
/**
* 实现命令:KEYS pattern,查找所有符合给定模式 pattern的 key
*
* @param pattern 不能为空
* @return keys
*/
public Set<String> keys(String pattern) {
return stringRedisTemplate.keys(pattern);
}
/**
* 实现命令:DEL key,删除一个key
*
* @param key 不能为空
*/
public void del(String key) {
stringRedisTemplate.delete(key);
}
// get set ...
/**
* 实现命令:SET key value,设置一个key-value(将字符串对象 value 关联到 key)
*
* @param key 不能为空
* @param value 字符串对象
*/
public void set(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
/**
* 实现命令:SET key value,设置一个key-value(将可序列化对象 value 关联到 key)
*
* @param key 不能为空
* @param value 可序列化对象
*/
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 实现命令:SET key value EX seconds,设置key-value和超时时间(秒)
*
* @param key 不能为空
* @param value 可序列化对象
* @param timeout 超时时间(单位:秒)
*/
public void set(String key, Object value, long timeout) {
redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
/**
* 实现命令:SET key value EX seconds,设置key-value和超时时间(秒)
*
* @param key 不能为空
* @param value 字符串对象
* @param timeout 超时时间(单位:秒)
*/
public void set(String key, String value, long timeout) {
stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
/**
* 实现命令:GET key,返回 key所关联的字符串值。
*
* @param key 不能为空
* @return value
*/
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
/**
* 实现命令:GET key,返回 key 所关联的对象。
*
* @param key 不能为空
* @return 对象
*/
public Object getObject(String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 实现命令:GET key,返回 key 所关联的反序列化对象。
*
* @param <T> 反序列化对象类型
* @param key 不能为空
* @param clazz 反序列化对象类
* @return 反序列化对象
*/
public <T> T get(String key, Class<T> clazz) {
return Convert.convert(redisTemplate.opsForValue().get(key), clazz);
}
// Hash(哈希表)
/**
* 实现命令:HSET key field value,将哈希表 key中的域 field的值设为 value
* <p>设置hashKey的值
*
* @param key 不能为空
* @param hashKey 不能为空
* @param value 设置的值
*/
public void hset(String key, String hashKey, Object value) {
stringRedisTemplate.opsForHash().put(key, hashKey, value);
}
/**
* 实现命令:HGET key field,返回哈希表 key中给定域 field的值
* <p>从hashKey获取值
*
* @param key 不能为空
* @param hashKey 不能为空
* @return hashKey的值
*/
public Object hget(String key, String hashKey) {
return stringRedisTemplate.opsForHash().get(key, hashKey);
}
/**
* 实现命令:HGET key field,返回哈希表 key中给定域 field的值
* <p>从hashKey获取值
*
* @param <T> 反序列化对象类型
* @param key 不能为空
* @param hashKey 不能为空
* @param clazz 反序列化对象类
* @return hashKey的反序列化对象
*/
public <T> T hget(String key, String hashKey, Class<T> clazz) {
return Convert.convert(stringRedisTemplate.opsForHash().get(key, hashKey), clazz);
}
/**
* 实现命令:HDEL key field [field ...],删除哈希表 key 中的一个或多个指定域,不存在的域将被忽略。
* <p>删除给定的hashKeys
*
* @param key 不能为空
* @param hashKeys 不能为空
*/
public void hdel(String key, Object... hashKeys) {
stringRedisTemplate.opsForHash().delete(key, hashKeys);
}
/**
* 实现命令:HGETALL key,返回哈希表 key中,所有的域和值。
* <p>获取存储在键上的整个散列
*
* @param key 不能为空
* @return map
*/
public Map<Object, Object> hgetall(String key) {
return stringRedisTemplate.opsForHash().entries(key);
}
// List(列表)
/**
* 实现命令:LPUSH key value,将一个值 value插入到列表 key的表头
*
* @param key 不能为空
* @param value 插入的值
* @return 执行 LPUSH命令后,列表的长度。
*/
public long lpush(String key, String value) {
return stringRedisTemplate.opsForList().leftPush(key, value);
}
/**
* 实现命令:RPUSH key value,将一个值 value插入到列表 key的表尾(最右边)。
*
* @param key 不能为空
* @param value 插入的值
* @return 执行 LPUSH命令后,列表的长度。
*/
public long rpush(String key, String value) {
return stringRedisTemplate.opsForList().rightPush(key, value);
}
/**
* 实现命令:LPOP key,移除并返回列表 key的头元素。
*
* @param key 不能为空
* @return 列表key的头元素。
*/
public String lpop(String key) {
return stringRedisTemplate.opsForList().leftPop(key);
}
}
|
0 | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis/client/package-info.java | /**
* redis客户端
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.data.redis.client; |
0 | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis/config/RedisAutoConfig.java | package ai.yue.library.data.redis.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import ai.yue.library.base.util.ClassUtils;
import ai.yue.library.data.redis.client.Redis;
import ai.yue.library.data.redis.config.properties.RedisProperties;
import ai.yue.library.data.redis.constant.RedisSerializerEnum;
import lombok.extern.slf4j.Slf4j;
/**
* redis自动配置
*
* @author ylyue
* @since 2018年6月11日
*/
@Slf4j
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
@EnableConfigurationProperties({ RedisProperties.class })
public class RedisAutoConfig {
@Autowired
RedisProperties redisProperties;
/**
* <p>支持FastJson进行Redis存储对象序列/反序列化
* <p>https://github.com/alibaba/fastjson/wiki/%E5%9C%A8-Spring-%E4%B8%AD%E9%9B%86%E6%88%90-Fastjson
*/
@Bean
public RedisTemplate<String, Object> yueRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 支持FastJson进行Redis存储对象序列/反序列化
if (redisProperties.getRedisSerializerEnum() != RedisSerializerEnum.JDK) {
redisTemplate.setDefaultSerializer(redisProperties.getRedisSerializerEnum().getRedisSerializer());
}
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
return redisTemplate;
}
@Bean
@Primary
@ConditionalOnBean({ RedisTemplate.class, StringRedisTemplate.class })
public Redis redis(@Qualifier("yueRedisTemplate") RedisTemplate<String, Object> redisTemplate, StringRedisTemplate stringRedisTemplate) {
log.info("【初始化配置-Redis客户端】配置项:{},默认使用 {} 进行Redis存储对象序列/反序列化。Bean:Redis ... 已初始化完毕。",
RedisProperties.PREFIX,
ClassUtils.getClassName(RedisSerializerEnum.class, false).concat(".JDK"));
return new Redis(redisTemplate, stringRedisTemplate);
}
}
|
0 | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis/config/package-info.java | /**
* redis自动配置
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.data.redis.config; |
0 | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis/config | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis/config/properties/RedisProperties.java | package ai.yue.library.data.redis.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import ai.yue.library.data.redis.constant.RedisSerializerEnum;
import lombok.Data;
/**
* redis可配置属性
*
* @author ylyue
* @since 2018年11月6日
*/
@Data
@ConfigurationProperties(RedisProperties.PREFIX)
public class RedisProperties {
/**
* Prefix of {@link RedisProperties}.
*/
public static final String PREFIX = "yue.redis";
/**
* <p>Redis存储对象序列/反序列化器
* <p>默认:{@linkplain RedisSerializerEnum#JDK}
*/
private RedisSerializerEnum redisSerializerEnum = RedisSerializerEnum.JDK;
/**
* IP前缀(自定义值,请保留“<code style="color:red">_%s</code>”部分)
* <p>默认:ip_%s
*/
private String ipPrefix = "ip_%s";
}
|
0 | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis/config | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis/config/properties/package-info.java | /**
* redis自动配置属性
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.data.redis.config.properties; |
0 | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis | java-sources/ai/ylyue/yue-library-data-redis/2.1.0/ai/yue/library/data/redis/constant/RedisSerializerEnum.java | package ai.yue.library.data.redis.constant;
import java.io.Serializable;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
/**
* Redis 存储对象序列/反序列化
*
* @author ylyue
* @since 2020年4月15日
*/
public enum RedisSerializerEnum {
/**
* 序列化任何 {@link Serializable} 对象
*/
JDK {
@Override
public RedisSerializer<Object> getRedisSerializer() {
return new JdkSerializationRedisSerializer();
}
},
FASTJSON {
@Override
public RedisSerializer<Object> getRedisSerializer() {
return new GenericFastJsonRedisSerializer();
}
},
JACKSON {
@Override
public RedisSerializer<Object> getRedisSerializer() {
return new GenericJackson2JsonRedisSerializer();
}
};
public abstract RedisSerializer<Object> getRedisSerializer();
}
|
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/package-info.java | /**
* pay库基于pay-java-parent进行二次封装,让你真正做到一行代码实现支付聚合,让你可以不用理解支付怎么对接,只需要专注你的业务
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.pay; |
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/client/Pay.java | package ai.yue.library.pay.client;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.imageio.ImageIO;
import com.egzosn.pay.common.api.PayMessageInterceptor;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.MethodType;
import com.egzosn.pay.common.bean.RefundOrder;
import com.egzosn.pay.common.bean.TransactionType;
import com.egzosn.pay.common.bean.TransferOrder;
import ai.yue.library.pay.ipo.PayOrderIPO;
import ai.yue.library.pay.ipo.QueryOrderIPO;
import lombok.AllArgsConstructor;
/**
* 支付客户端,封装支付接口统一实现,只需一行代码实现支付聚合
*
* @author ylyue
* @since 2019年8月22日
*/
@AllArgsConstructor
public class Pay {
@SuppressWarnings("rawtypes")
private Map<Integer, PayService> payServiceMap;
private PayService<?> getPayService(Integer listId) {
PayService<?> payService = payServiceMap.get(listId);
if (payService == null) {
throw new IllegalArgumentException(String.format("未找到对应listId=[%s]的配置,请核实!", listId));
}
return payService;
}
/**
* 跳到支付页面
* 针对实时支付,即时付款
*
* @param payOrderIPO 商户支付订单信息
* @return 跳到支付页面
*/
public String toPay(PayOrderIPO payOrderIPO) {
PayService<?> payService = getPayService(payOrderIPO.getListId());
Map<String, Object> orderInfo = payService.orderInfo(payOrderIPO);
return payService.buildRequest(orderInfo, MethodType.POST);
}
/**
* 获取支付预订单信息
*
* @param payOrderIPO 商户支付订单信息
* @return 支付预订单信息
*/
public Map<String, Object> getOrderInfo(PayOrderIPO payOrderIPO) {
return getPayService(payOrderIPO.getListId()).orderInfo(payOrderIPO);
}
/**
* 刷卡付,pos主动扫码付款(条码付)
*
* @param payOrderIPO 商户支付订单信息
* @return 支付结果
*/
public Map<String, Object> microPay(PayOrderIPO payOrderIPO) {
PayService<?> payService = getPayService(payOrderIPO.getListId());
//支付结果
return payService.microPay(payOrderIPO);
}
/**
* 获取二维码图像
* 二维码支付
*
* @param payOrderIPO 商户支付订单信息
* @return 二维码图像
* @throws IOException IOException
*/
public byte[] toQrPay(PayOrderIPO payOrderIPO) throws IOException {
// 获取对应的支付账户操作工具(可根据账户id)
PayService<?> payService = getPayService(payOrderIPO.getListId());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(payService.genQrPay(payOrderIPO), "JPEG", baos);
return baos.toByteArray();
}
/**
* 获取二维码信息
* 二维码支付
*
* @param payOrderIPO 商户支付订单信息
* @return 二维码信息
*/
public String getQrPay(PayOrderIPO payOrderIPO) {
return getPayService(payOrderIPO.getListId()).getQrPay(payOrderIPO);
}
/**
* 支付回调地址
* 方式二
*
* @param listId 列表id
* @param parameterMap 请求参数
* @param is 请求流
* @return 支付是否成功
* @throws IOException IOException
* 拦截器相关增加, 详情查看{@link com.egzosn.pay.common.api.PayService#addPayMessageInterceptor(PayMessageInterceptor)}
* <p>
* 业务处理在对应的PayMessageHandler里面处理,在哪里设置PayMessageHandler,详情查看{@link com.egzosn.pay.common.api.PayService#setPayMessageHandler(com.egzosn.pay.common.api.PayMessageHandler)}
* </p>
* 如果未设置 {@link com.egzosn.pay.common.api.PayMessageHandler} 那么会使用默认的 {@link com.egzosn.pay.common.api.DefaultPayMessageHandler}
*/
public String payBack(Integer listId, Map<String, String[]> parameterMap, InputStream is) throws IOException {
// 业务处理在对应的PayMessageHandler里面处理,在哪里设置PayMessageHandler,详情查看com.egzosn.pay.common.api.PayService.setPayMessageHandler()
return getPayService(listId).payBack(parameterMap, is).toMessage();
}
/**
* 查询
*
* @param queryOrderIPO 订单的请求体
* @return 返回查询回来的结果集,支付方原值返回
*/
public Map<String, Object> query(QueryOrderIPO queryOrderIPO) {
return getPayService(queryOrderIPO.getListId()).query(queryOrderIPO.getTradeNo(), queryOrderIPO.getOutTradeNo());
}
/**
* 交易关闭接口
*
* @param queryOrderIPO 订单的请求体
* @return 返回支付方交易关闭后的结果
*/
public Map<String, Object> close(QueryOrderIPO queryOrderIPO) {
return getPayService(queryOrderIPO.getListId()).close(queryOrderIPO.getTradeNo(), queryOrderIPO.getOutTradeNo());
}
/**
* 申请退款接口
*
* @param listId 列表id
* @param order 订单的请求体
* @return 返回支付方申请退款后的结果
*/
public Map<String, Object> refund(Integer listId, RefundOrder order) {
return getPayService(listId).refund(order);
}
/**
* 查询退款
*
* @param listId 列表id
* @param refundOrder 订单的请求体
* @return 返回支付方查询退款后的结果
*/
public Map<String, Object> refundquery(Integer listId, RefundOrder refundOrder) {
return getPayService(listId).refundquery(refundOrder);
}
/**
* 下载对账单
*
* @param queryOrderIPO 订单的请求体
* @return 返回支付方下载对账单的结果
*/
public Object downloadbill(QueryOrderIPO queryOrderIPO) {
return getPayService(queryOrderIPO.getListId()).downloadbill(queryOrderIPO.getBillDate(), queryOrderIPO.getBillType());
}
/**
* 通用查询接口,根据 TransactionType 类型进行实现,此接口不包括退款
*
* @param queryOrderIPO 订单的请求体
* @param transactionType 交易类型
* @return 返回支付方对应接口的结果
*/
public Map<String, Object> secondaryInterface(QueryOrderIPO queryOrderIPO, TransactionType transactionType) {
return getPayService(queryOrderIPO.getListId()).secondaryInterface(queryOrderIPO.getTradeNoOrBillDate(), queryOrderIPO.getOutTradeNoBillType(), transactionType);
}
/**
* 转账
*
* @param listId 列表id
* @param transferOrder 转账订单
* @return 对应的转账结果
*/
public Map<String, Object> transfer(Integer listId, TransferOrder transferOrder) {
return getPayService(listId).transfer(transferOrder);
}
/**
* 转账查询
*
* @param listId 列表id
* @param outNo 商户转账订单号
* @param tradeNo 支付平台转账订单号
* @return 对应的转账订单
*/
public Map<String, Object> transferQuery(Integer listId, String outNo, String tradeNo) {
return getPayService(listId).transferQuery(outNo, tradeNo);
}
}
|
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/client/package-info.java | /**
* pay客户端
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.pay.client; |
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/config/PayAutoConfig.java | package ai.yue.library.pay.config;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.egzosn.pay.ali.api.AliPayConfigStorage;
import com.egzosn.pay.ali.api.AliPayService;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.http.HttpConfigStorage;
import com.egzosn.pay.wx.api.WxPayConfigStorage;
import com.egzosn.pay.wx.api.WxPayService;
import ai.yue.library.base.util.ListUtils;
import ai.yue.library.base.util.MapUtils;
import ai.yue.library.base.util.ObjectUtils;
import ai.yue.library.pay.client.Pay;
import ai.yue.library.pay.config.properties.AliPayProperties;
import ai.yue.library.pay.config.properties.AliPayProperties.AliPayConfig;
import ai.yue.library.pay.config.properties.WxPayProperties;
import ai.yue.library.pay.config.properties.WxPayProperties.WxPayConfig;
import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
/**
* 支付自动配置
*
* @author ylyue
* @since 2019年8月22日
*/
@Slf4j
@Configuration
@EnableConfigurationProperties({ AliPayProperties.class, WxPayProperties.class })
public class PayAutoConfig {
@Autowired
WxPayProperties wxPayProperties;
@Autowired
AliPayProperties aliPayProperties;
@SuppressWarnings("rawtypes")
Map<Integer, PayService> payServiceMap = MapUtils.newHashMap();
@Bean
@Primary
public Pay pay() {
// 微信
if (wxPayProperties.isEnabled()) {
if (!ClassLoaderUtil.isPresent("com.egzosn.pay.wx.api.WxPayService")) {
log.error("【支付配置】未引入依赖模块:pay-java-wx");
}
wxPay();
}
// 支付宝
if (aliPayProperties.isEnabled()) {
if (!ClassLoaderUtil.isPresent("com.egzosn.pay.ali.api.AliPayService")) {
log.error("【支付配置】未引入依赖模块:pay-java-ali");
}
aliPay();
}
// Bean
return new Pay(payServiceMap);
}
private void wxPay() {
// 1. 获得配置列表
List<WxPayConfig> configList = wxPayProperties.getConfigList();
if (ListUtils.isEmpty(configList)) {
throw new RuntimeException("【支付配置】无效的微信支付配置...");
}
configList.forEach(config -> {
// 2. 支付配置
WxPayConfigStorage wxPayConfigStorage = new WxPayConfigStorage();
wxPayConfigStorage.setMchId(config.getMchId());
wxPayConfigStorage.setAppid(config.getAppId());
wxPayConfigStorage.setKeyPublic(config.getKeyPublic());// 转账公钥,转账时必填
wxPayConfigStorage.setSecretKey(config.getSecretKey());
wxPayConfigStorage.setNotifyUrl(config.getNotifyUrl());
wxPayConfigStorage.setSignType(config.getSignType().name());
wxPayConfigStorage.setInputCharset("utf-8");
// 3. 网络请求配置
HttpConfigStorage httpConfigStorage = new HttpConfigStorage();
// // ssl 退款证书相关 不使用可注释
// if(!"ssl 退款证书".equals(KEYSTORE)){
// httpConfigStorage.setKeystore(KEYSTORE);
// httpConfigStorage.setStorePassword(STORE_PASSWORD);
// httpConfigStorage.setPath(true);
// }
// 请求连接池配置
// 最大连接数
httpConfigStorage.setMaxTotal(20);
// 默认的每个路由的最大连接数
httpConfigStorage.setDefaultMaxPerRoute(10);
// 4. 配置支付服务
WxPayService wxPayService = new WxPayService(wxPayConfigStorage, httpConfigStorage);
Integer listId = config.getListId();
if (ObjectUtils.isNotNull(payServiceMap.get(listId))) {
throw new RuntimeException(StrUtil.format("【支付配置】出现非全局唯一 listId:{}", listId));
}
payServiceMap.put(listId, wxPayService);
});
}
private void aliPay() {
// 1. 获得配置列表
List<AliPayConfig> configList = aliPayProperties.getConfigList();
if (ListUtils.isEmpty(configList)) {
throw new RuntimeException("【支付配置】无效的支付宝支付配置...");
}
configList.forEach(config -> {
// 2. 支付配置
AliPayConfigStorage aliPayConfigStorage = new AliPayConfigStorage();
aliPayConfigStorage.setPid(config.getPid());
aliPayConfigStorage.setAppid(config.getAppId());
aliPayConfigStorage.setKeyPublic(config.getKeyPublic());
aliPayConfigStorage.setKeyPrivate(config.getKeyPrivate());
aliPayConfigStorage.setNotifyUrl(config.getNotifyUrl());
aliPayConfigStorage.setSignType(config.getSignType().name());
aliPayConfigStorage.setSeller(config.getSeller());
aliPayConfigStorage.setInputCharset(config.getInputCharset());
// 是否为测试账号,沙箱环境
aliPayConfigStorage.setTest(config.getTest());
// 3. 网络请求配置
HttpConfigStorage httpConfigStorage = new HttpConfigStorage();
// 请求连接池配置
// 最大连接数
httpConfigStorage.setMaxTotal(20);
// 默认的每个路由的最大连接数
httpConfigStorage.setDefaultMaxPerRoute(10);
// 4. 配置支付服务
AliPayService aliPayService = new AliPayService(aliPayConfigStorage, httpConfigStorage);
Integer listId = config.getListId();
if (ObjectUtils.isNotNull(payServiceMap.get(listId))) {
throw new RuntimeException(StrUtil.format("【支付配置】出现非全局唯一 listId:{}", listId));
}
payServiceMap.put(listId, aliPayService);
});
}
}
|
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/config/package-info.java | /**
* pay自动配置
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.pay.config; |
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/config | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/config/properties/AliPayProperties.java | package ai.yue.library.pay.config.properties;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import com.egzosn.pay.common.util.sign.SignUtils;
import lombok.Data;
/**
* 支付宝支付可配置属性
*
* @author ylyue
* @since 2018年7月13日
*/
@Data
@ConfigurationProperties("yue.pay.ali")
public class AliPayProperties {
/**
* 是否启用微信支付自动配置
* <p>
* 默认:false
*/
private boolean enabled = false;
/**
* 配置列表
*/
private List<AliPayConfig> configList;
@Data
public static class AliPayConfig {
/**
* 配置列表id,用于区分具体配置信息,全局唯一
*/
private Integer listId;
/**
* 商户应用id
*/
private String appId;
/**
* 商户签约拿到的pid,partner_id的简称,合作伙伴身份等同于 partner
*/
private String pid;
/**
* 商户收款账号
*/
private String seller;
/**
* 应用私钥,rsa_private pkcs8格式 生成签名时使用
*/
private String keyPrivate;
/**
* 支付平台公钥(签名校验使用)
*/
private String keyPublic;
/**
* 异步回调地址
*/
private String notifyUrl;
/**
* 签名加密类型
*/
private SignUtils signType;
/**
* 是否为沙箱环境,默认为正式环境
* <p>默认:false
*/
private Boolean test = false;
/**
* 字符类型:utf-8
*/
private final String inputCharset = "utf-8";
}
}
|
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/config | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/config/properties/WxPayProperties.java | package ai.yue.library.pay.config.properties;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import com.egzosn.pay.common.util.sign.SignUtils;
import lombok.Data;
/**
* 微信支付可配置属性
*
* @author ylyue
* @since 2018年7月13日
*/
@Data
@ConfigurationProperties("yue.pay.wx")
public class WxPayProperties {
/**
* 是否启用微信支付自动配置
* <p>
* 默认:false
*/
private boolean enabled = false;
/**
* 配置列表
*/
private List<WxPayConfig> configList;
@Data
public static class WxPayConfig {
/**
* 配置列表id,用于区分具体配置信息,全局唯一
*/
private Integer listId;
/**
* 商户应用id
*/
private String appId;
/**
* 商户号 合作者id
*/
private String mchId;
/**
* 密钥
*/
private String secretKey;
/**
* 转账公钥,转账时必填
*/
private String keyPublic;
/**
* 异步回调地址
*/
private String notifyUrl;
/**
* 签名加密类型
*/
private SignUtils signType;
}
}
|
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/config | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/config/properties/package-info.java | /**
* 自动配置属性
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.pay.config.properties; |
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/dto/ApplePayVerifyResult.java | package ai.yue.library.pay.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* {@link #status} 状态码对照:
* <p>0 正常
* <p>21000 App Store不能读取你提供的JSON对象
* <p>21002 receipt-data域的数据有问题
* <p>21003 receipt无法通过验证
* <p>21004 提供的shared secret不匹配你账号中的shared secret
* <p>21005 receipt服务器当前不可用
* <p>21006 receipt合法,但是订阅已过期。服务器接收到这个状态码时,receipt数据仍然会解码并一起发送
* <p>21007 receipt是Sandbox receipt,但却发送至生产系统的验证服务
* <p>21008 receipt是生产receipt,但却发送至Sandbox环境的验证服务
*
* @author ylyue
* @since 2019年8月20日
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ApplePayVerifyResult {
/**
* 状态码,参照类说明
*/
private Integer status;
/**
* 交易ID,由苹果方生成的交易单号
*/
private String transaction_id;
/**
* 产品ID,可用于支付金额确认
*/
private String product_id;
/**
* 交易数量
*/
private Integer quantity;
/**
* 交易日期
*/
private String purchase_date;
}
|
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/dto/package-info.java | /**
* DTO定义
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.pay.dto; |
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/ipo/PayOrderIPO.java | package ai.yue.library.pay.ipo;
import java.math.BigDecimal;
import com.egzosn.pay.common.bean.TransactionType;
import ai.yue.library.base.util.UUIDUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* 支付订单IPO
*
* @author ylyue
* @since 2019年8月22日
*/
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class PayOrderIPO extends com.egzosn.pay.common.bean.PayOrder {
/**
* 配置列表id,用于区分具体配置信息,全局唯一
*/
private Integer listId;
public PayOrderIPO(Integer listId, String subject, String body, BigDecimal price, TransactionType transactionType) {
super(subject, body, price, UUIDUtils.getOrderNo_19(), transactionType);
this.listId = listId;
}
public PayOrderIPO(Integer listId, String subject, String body, BigDecimal price, String outTradeNo, TransactionType transactionType) {
super(subject, body, price, outTradeNo, transactionType);
this.listId = listId;
}
}
|
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/ipo/QueryOrderIPO.java | package ai.yue.library.pay.ipo;
import java.math.BigDecimal;
import java.util.Date;
import lombok.Data;
/**
* 订单辅助接口
*
* @author ylyue
* @since 2019年8月23日
*/
@Data
public class QueryOrderIPO {
/**
* 列表id
*/
private Integer listId;
/**
* 支付平台订单号
*/
private String tradeNo;
/**
* 商户单号
*/
private String outTradeNo;
/**
* 退款金额
*/
private BigDecimal refundAmount;
/**
* 总金额
*/
private BigDecimal totalAmount;
/**
* 账单时间:具体请查看对应支付平台
*/
private Date billDate;
/**
* 账单时间:具体请查看对应支付平台
*/
private String billType;
/**
* 支付平台订单号或者账单日期
*/
private Object tradeNoOrBillDate;
/**
* 商户单号或者 账单类型
*/
private String outTradeNoBillType;
}
|
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/ipo/package-info.java | /**
* IPO定义
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.pay.ipo; |
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/util/ApplePayUtils.java | package ai.yue.library.pay.util;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
import ai.yue.library.base.exception.ResultException;
import ai.yue.library.base.util.ApplicationContextUtils;
import ai.yue.library.base.view.ResultInfo;
import ai.yue.library.pay.dto.ApplePayVerifyResult;
/**
* 苹果内购支付验证
*
* @author ylyue
* @since 2019年8月20日
*/
public class ApplePayUtils {
private static RestTemplate restTemplate;
/** 沙箱环境验证URI */
private static final String URI_SANDBOX = "https://sandbox.itunes.apple.com/verifyReceipt";
/** 正式环境验证URI */
private static final String URI_VERIFY = "https://buy.itunes.apple.com/verifyReceipt";
// 初始化
static {
restTemplate = ApplicationContextUtils.getBean(RestTemplate.class);
}
/**
* 验证
*
* @param receiptData 验证数据
* @return 验证结果
*/
public static ApplePayVerifyResult verify(String receiptData) {
return verify(URI_VERIFY, receiptData);
}
/**
* 验证
*
* @param uri 验证URI(用于区分验证环境)
* @param receiptData 验证数据
* @return 验证结果
*/
private static ApplePayVerifyResult verify(String uri, String receiptData) {
// 1. 发起请求
JSONObject requestData = new JSONObject();
requestData.put("receipt-data", receiptData);
String response = restTemplate.postForObject(uri, requestData, String.class);
JSONObject result = JSONObject.parseObject(response);
Integer status = result.getInteger("status");
// 2. 确认结果
if (status == 21007) {
return verify(URI_SANDBOX, receiptData);
}
if (status != 0) {
throw new ResultException(ResultInfo.error(response));
}
// 3. 获得结果
JSONObject receipt = result.getJSONObject("receipt");
JSONObject in_app = receipt.getJSONArray("in_app").getJSONObject(0);
String transaction_id = in_app.getString("transaction_id");
String product_id = in_app.getString("product_id");
Integer quantity = in_app.getInteger("quantity");
String purchase_date = in_app.getString("purchase_date");
// 4. 返回结果
return ApplePayVerifyResult.builder()
.status(status)
.transaction_id(transaction_id)
.product_id(product_id)
.quantity(quantity)
.purchase_date(purchase_date)
.build();
}
}
|
0 | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay | java-sources/ai/ylyue/yue-library-pay/2.1.0/ai/yue/library/pay/util/package-info.java | /**
* pay工具包,包括苹果支付所需的 {@linkplain ai.yue.library.pay.util.ApplePayUtils}
*
* @author ylyue
* @since 2019年10月14日
*/
package ai.yue.library.pay.util; |
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/package-info.java | /**
* yue-library是一个基于SpringBoot封装的基础库,内置丰富的JDK工具,自动装配了一系列的基础Bean与环境配置项,可用于快速构建SpringCloud项目,让微服务变得更简单。
*
* @author ylyue
* @since 2019年10月13日
*/
package ai.yue.library.web; |
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/WebAutoConfig.java | package ai.yue.library.web.config;
import java.util.Arrays;
import java.util.List;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import ai.yue.library.base.config.properties.CorsProperties;
import ai.yue.library.web.config.argument.resolver.CustomArgumentResolversConfig;
import ai.yue.library.web.config.handler.ExceptionHandlerConfig;
import ai.yue.library.web.config.properties.FastJsonHttpMessageConverterProperties;
import ai.yue.library.web.config.properties.JacksonHttpMessageConverterProperties;
import ai.yue.library.web.config.properties.WebProperties;
import ai.yue.library.web.env.WebMvcEnv;
import ai.yue.library.web.util.servlet.multipart.UploadProperties;
import lombok.extern.slf4j.Slf4j;
/**
* web bean 自动配置
*
* @author ylyue
* @since 2018年11月26日
*/
@Slf4j
@Configuration
@Import({ WebMvcConfig.class, WebMvcRegistrationsConfig.class, ExceptionHandlerConfig.class,
CustomArgumentResolversConfig.class, WebMvcEnv.class })
@EnableConfigurationProperties({ WebProperties.class, JacksonHttpMessageConverterProperties.class, FastJsonHttpMessageConverterProperties.class, UploadProperties.class })
public class WebAutoConfig {
// CorsConfig-跨域
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "yue.cors", name = "allow", havingValue = "true", matchIfMissing = true)
public CorsFilter corsFilter(CorsProperties corsProperties) {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("*"));
config.setAllowedOrigins(Arrays.asList("*"));
config.setMaxAge(3600L);
// 设置response允许暴露的Headers
List<String> exposedHeaders = corsProperties.getExposedHeaders();
if (exposedHeaders != null) {
config.setExposedHeaders(exposedHeaders);
} else {
config.addExposedHeader("token");
}
source.registerCorsConfiguration("/**", config);
log.info("【初始化配置-跨域】默认配置为true,当前环境为true:默认任何情况下都允许跨域访问 ... 已初始化完毕。");
return new CorsFilter(source);
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/WebMvcConfig.java | package ai.yue.library.web.config;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.BeanContext;
import com.alibaba.fastjson.serializer.ContextValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import ai.yue.library.base.constant.FieldNamingStrategyEnum;
import ai.yue.library.base.util.ClassUtils;
import ai.yue.library.base.util.ListUtils;
import ai.yue.library.web.config.argument.resolver.CustomRequestParamMethodArgumentResolver;
import ai.yue.library.web.config.argument.resolver.JavaBeanArgumentResolver;
import ai.yue.library.web.config.properties.FastJsonHttpMessageConverterProperties;
import ai.yue.library.web.config.properties.JacksonHttpMessageConverterProperties;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
/**
* @author ylyue
* @since 2020年4月5日
*/
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
FastJsonHttpMessageConverterProperties fastJsonProperties;
@Autowired
JacksonHttpMessageConverterProperties jacksonProperties;
/**
* 扩展HTTP消息转换器做Json解析处理
*/
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
if (fastJsonProperties.isEnabled()) {
// 使用FastJson优先于默认的Jackson做json解析
// https://github.com/alibaba/fastjson/wiki/%E5%9C%A8-Spring-%E4%B8%AD%E9%9B%86%E6%88%90-Fastjson
fastJsonHttpMessageConverterConfig(converters);
} else if (jacksonProperties.isEnabled()) {
// 启用yue-library对Jackson进行增强配置
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = ListUtils.get(converters, MappingJackson2HttpMessageConverter.class);
mappingJackson2HttpMessageConverterConfig(mappingJackson2HttpMessageConverter);
}
}
private void fastJsonHttpMessageConverterConfig(List<HttpMessageConverter<?>> converters) {
// 1. 创建FastJsonHttpMessageConverter
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setDateFormat(JSON.DEFFAULT_DATE_FORMAT);
config.setSerializerFeatures(fastJsonProperties.getSerializerFeatures());
// 2. 配置FastJsonHttpMessageConverter规则
ContextValueFilter contextValueFilter = (BeanContext context, Object object, String name, Object value) -> {
if (context == null) {
if (fastJsonProperties.isWriteNullAsStringEmpty()) {
return StrUtil.EMPTY;
}
return value;
}
Class<?> fieldClass = context.getFieldClass();
if (value != null || ClassUtils.isBasicType(fieldClass) || Collection.class.isAssignableFrom(fieldClass)) {
return value;
}
if (fastJsonProperties.isWriteNullMapAsEmpty() && Map.class.isAssignableFrom(fieldClass)) {
return new JSONObject();
} else if (fastJsonProperties.isWriteNullArrayAsEmpty() && fieldClass.isArray()) {
return ArrayUtil.newArray(0);
}
if (fastJsonProperties.isWriteNullAsStringEmpty()) {
return StrUtil.EMPTY;
}
return value;
};
// 3. 配置FastJsonHttpMessageConverter
if (fastJsonProperties.isWriteNullAsStringEmpty() || fastJsonProperties.isWriteNullMapAsEmpty()) {
config.setSerializeFilters(contextValueFilter);
}
FieldNamingStrategyEnum fieldNamingStrategy = fastJsonProperties.getFieldNamingStrategy();
if (fieldNamingStrategy != null) {
config.getSerializeConfig().setPropertyNamingStrategy(fieldNamingStrategy.getPropertyNamingStrategy());
}
converter.setFastJsonConfig(config);
converters.add(0, converter);
log.info("【初始化配置-FastJsonHttpMessageConverter】默认配置为false,当前环境为true:使用FastJson优先于默认的Jackson做json解析 ... 已初始化完毕。");
}
private void mappingJackson2HttpMessageConverterConfig(MappingJackson2HttpMessageConverter converter) {
ObjectMapper objectMapper = converter.getObjectMapper();
JsonSerializer<Object> jsonSerializer = new JsonSerializer<Object>() {
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
// 1. 确认currentValue是否有值
JsonStreamContext outputContext = gen.getOutputContext();
Object currentValue = outputContext.getCurrentValue();
if (currentValue == null) {
writeNullOrEmpty(gen);
return;
}
// 2. 确认当前字段
String currentName = outputContext.getCurrentName();
Field field = null;
try {
field = ReflectUtil.getField(currentValue.getClass(), currentName);
} catch (Exception e) {
// 不做处理
}
if (field == null) {
writeNullOrEmpty(gen);
return;
}
// 3. 处理初始化类型
Class<?> fieldClass = field.getType();
if (jacksonProperties.isWriteNullStringAsEmpty() && CharSequence.class.isAssignableFrom(fieldClass)) {
gen.writeString(StrUtil.EMPTY);
return;
} else if (jacksonProperties.isWriteNullNumberAsZero() && Number.class.isAssignableFrom(fieldClass)) {
gen.writeNumber(0);
return;
} else if (jacksonProperties.isWriteNullBooleanAsFalse() && Boolean.class.isAssignableFrom(fieldClass)) {
gen.writeBoolean(false);
return;
} else if (jacksonProperties.isWriteNullMapAsEmpty() && Map.class.isAssignableFrom(fieldClass)) {
gen.writeStartObject();
gen.writeEndObject();
return;
} else if (jacksonProperties.isWriteNullArrayAsEmpty() && (fieldClass.isArray() || Collection.class.isAssignableFrom(fieldClass))) {
gen.writeStartArray();
gen.writeEndArray();
return;
} else if (ClassUtils.isBasicType(fieldClass)) {
gen.writeNull();
return;
}
// 4. 其它类型处理
writeNullOrEmpty(gen);
}
private void writeNullOrEmpty(JsonGenerator gen) throws IOException {
if (jacksonProperties.isWriteNullAsStringEmpty()) {
gen.writeString(StrUtil.EMPTY);
return;
}
gen.writeNull();
}
};
objectMapper.getSerializerProvider().setNullValueSerializer(jsonSerializer);
}
/**
* 添加自定义方法参数解析器
*/
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new JavaBeanArgumentResolver());
resolvers.add(new CustomRequestParamMethodArgumentResolver(true));
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/WebMvcRegistrationsConfig.java | package ai.yue.library.web.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import ai.yue.library.base.annotation.api.version.ApiVersionProperties;
import ai.yue.library.web.config.api.version.ApiVersionRequestMappingHandlerMapping;
import lombok.extern.slf4j.Slf4j;
/**
* @author ylyue
* @since 2020年2月27日
*/
@Slf4j
@Configuration
@EnableConfigurationProperties(ApiVersionProperties.class)
public class WebMvcRegistrationsConfig implements WebMvcRegistrations {
@Autowired
private ApiVersionProperties apiVersionProperties;
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
if (!apiVersionProperties.isEnabled()) {
return WebMvcRegistrations.super.getRequestMappingHandlerMapping();
}
log.info("【初始化配置-ApiVersionRequestMappingHandlerMapping】默认配置为true,当前环境为true:Restful API接口版本控制,执行初始化 ...");
return new ApiVersionRequestMappingHandlerMapping(apiVersionProperties);
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/package-info.java | /**
* web配置包,提供自动配置项支持与增强
*
* @author ylyue
* @since 2019年9月16日
*/
package ai.yue.library.web.config; |
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/api | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/api/version/ApiVersionRequestCondition.java | package ai.yue.library.web.config.api.version;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import ai.yue.library.base.annotation.api.version.ApiVersion;
import ai.yue.library.base.annotation.api.version.ApiVersionProperties;
import ai.yue.library.base.exception.ApiVersionDeprecatedException;
import ai.yue.library.base.util.StringUtils;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @author ylyue
* @since 2020年2月26日
*/
@Data
@AllArgsConstructor
public class ApiVersionRequestCondition implements RequestCondition<ApiVersionRequestCondition> {
private ApiVersion apiVersion;
private ApiVersionProperties apiVersionProperties;
/**
* {@link RequestMapping} 版本占位符索引
*/
private Integer versionPlaceholderIndex;
@Override
public ApiVersionRequestCondition combine(ApiVersionRequestCondition apiVersionRequestCondition) {
// 最近优先原则:在方法上的 {@link ApiVersion} 可覆盖在类上面的 {@link ApiVersion}
return new ApiVersionRequestCondition(apiVersionRequestCondition.getApiVersion(), apiVersionRequestCondition.getApiVersionProperties(), apiVersionRequestCondition.getVersionPlaceholderIndex());
}
@Override
public ApiVersionRequestCondition getMatchingCondition(HttpServletRequest request) {
// 校验请求url中是否包含版本信息
String requestURI = request.getRequestURI();
String[] versionPaths = StringUtils.split(requestURI, "/");
double pathVersion = Double.valueOf(versionPaths[versionPlaceholderIndex].substring(1));
// 如果当前url中传递的版本信息高于(或等于)申明(或默认)版本,则用url的版本
double apiVersionValue = this.getApiVersion().value();
if (pathVersion >= apiVersionValue) {
double minimumVersion = apiVersionProperties.getMinimumVersion();
if ((this.getApiVersion().deprecated() || minimumVersion >= pathVersion) && pathVersion == apiVersionValue) {
throw new ApiVersionDeprecatedException(StrUtil.format("客户端调用弃用版本API接口,requestURI:{}", requestURI));
} else if (this.getApiVersion().deprecated()) {
return null;
}
return this;
}
return null;
}
@Override
public int compareTo(ApiVersionRequestCondition apiVersionRequestCondition, HttpServletRequest request) {
// 当出现多个符合匹配条件的ApiVersionCondition,优先匹配版本号较大的
return NumberUtil.compare(apiVersionRequestCondition.getApiVersion().value(), getApiVersion().value());
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/api | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/api/version/ApiVersionRequestMappingHandlerMapping.java | package ai.yue.library.web.config.api.version;
import java.lang.reflect.Method;
import java.util.Objects;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import ai.yue.library.base.annotation.api.version.ApiVersion;
import ai.yue.library.base.annotation.api.version.ApiVersionProperties;
import ai.yue.library.base.util.StringUtils;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
/**
* Restful API接口版本控制
*
* @author ylyue
* @since 2020年2月27日
*/
@AllArgsConstructor
public class ApiVersionRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
private ApiVersionProperties apiVersionProperties;
@Override
protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
// 扫描类或接口上的 {@link ApiVersion}
ApiVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
return createRequestCondition(apiVersion, handlerType);
}
@Override
protected RequestCondition<?> getCustomMethodCondition(Method method) {
// 扫描方法上的 {@link ApiVersion}
ApiVersion apiVersion = AnnotationUtils.findAnnotation(method, ApiVersion.class);
return createRequestCondition(apiVersion, method.getDeclaringClass());
}
private RequestCondition<ApiVersionRequestCondition> createRequestCondition(ApiVersion apiVersion, Class<?> handlerType) {
// 1. 确认是否进行版本控制-ApiVersion注解不为空
if (Objects.isNull(apiVersion)) {
return null;
}
// 2. 确认是否进行版本控制-RequestMapping注解包含版本占位符
RequestMapping requestMapping = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class);
if (requestMapping == null) {
return null;
}
String[] requestMappingValues = requestMapping.value();
if (StrUtil.isAllEmpty(requestMappingValues) || !requestMappingValues[0].contains(apiVersionProperties.getVersionPlaceholder())) {
return null;
}
// 3. 解析版本占位符索引位置
String[] versionPlaceholderValues = StringUtils.split(requestMappingValues[0], "/");
Integer index = null;
for (int i = 0; i < versionPlaceholderValues.length; i++) {
if (StringUtils.equals(versionPlaceholderValues[i], apiVersionProperties.getVersionPlaceholder())) {
index = i;
break;
}
}
// 4. 确认是否进行版本控制-占位符索引确认
if (index == null) {
return null;
}
// 5. 确认是否满足最低版本(v1)要求
double value = apiVersion.value();
Assert.isTrue(value >= 1, "Api Version Must be greater than or equal to 1");
// 6. 创建 RequestCondition
return new ApiVersionRequestCondition(apiVersion, apiVersionProperties, index);
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/argument | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/argument/resolver/CustomArgumentResolversConfig.java | package ai.yue.library.web.config.argument.resolver;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
/**
* 配置-自定义顺序方法参数解析器
*
* @author ylyue
* @since 2019年8月2日
*/
@Configuration
public class CustomArgumentResolversConfig {
@Autowired
public void prioritizeCustomMethodArgumentHandlers(RequestMappingHandlerAdapter adapter) {
List<HandlerMethodArgumentResolver> prioritizeCustomArgumentResolvers = new ArrayList<>();
prioritizeCustomArgumentResolvers.add(new JSONObjectArgumentResolver());
prioritizeCustomArgumentResolvers.addAll(adapter.getArgumentResolvers());
adapter.setArgumentResolvers(prioritizeCustomArgumentResolvers);
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/argument | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/argument/resolver/CustomRequestParamMethodArgumentResolver.java | package ai.yue.library.web.config.argument.resolver;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ValueConstants;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver;
import org.springframework.web.method.annotation.RequestParamMapMethodArgumentResolver;
import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver;
import org.springframework.web.method.support.UriComponentsContributor;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.multipart.support.MultipartResolutionDelegate;
import org.springframework.web.util.UriComponentsBuilder;
import com.alibaba.fastjson.JSONObject;
import ai.yue.library.base.constant.Constant;
import ai.yue.library.base.util.ParamUtils;
/**
* {@linkplain RequestParamMethodArgumentResolver} 增强
* <p>添加对body参数的解析
*
* @author ylyue
* @since 2020年7月25日
*/
public class CustomRequestParamMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver
implements UriComponentsContributor {
private static final TypeDescriptor STRING_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(String.class);
private final boolean useDefaultResolution;
/**
* Create a new {@link CustomRequestParamMethodArgumentResolver} instance.
* @param useDefaultResolution in default resolution mode a method argument
* that is a simple type, as defined in {@link BeanUtils#isSimpleProperty},
* is treated as a request parameter even if it isn't annotated, the
* request parameter name is derived from the method parameter name.
*/
public CustomRequestParamMethodArgumentResolver(boolean useDefaultResolution) {
this.useDefaultResolution = useDefaultResolution;
}
/**
* Create a new {@link CustomRequestParamMethodArgumentResolver} instance.
* @param beanFactory a bean factory used for resolving ${...} placeholder
* and #{...} SpEL expressions in default values, or {@code null} if default
* values are not expected to contain expressions
* @param useDefaultResolution in default resolution mode a method argument
* that is a simple type, as defined in {@link BeanUtils#isSimpleProperty},
* is treated as a request parameter even if it isn't annotated, the
* request parameter name is derived from the method parameter name.
*/
public CustomRequestParamMethodArgumentResolver(@Nullable ConfigurableBeanFactory beanFactory,
boolean useDefaultResolution) {
super(beanFactory);
this.useDefaultResolution = useDefaultResolution;
}
/**
* Supports the following:
* <ul>
* <li>@RequestParam-annotated method arguments.
* This excludes {@link Map} params where the annotation does not specify a name.
* See {@link RequestParamMapMethodArgumentResolver} instead for such params.
* <li>Arguments of type {@link MultipartFile} unless annotated with @{@link RequestPart}.
* <li>Arguments of type {@code Part} unless annotated with @{@link RequestPart}.
* <li>In default resolution mode, simple type arguments even if not with @{@link RequestParam}.
* </ul>
*/
@Override
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.hasParameterAnnotation(RequestParam.class)) {
if (Map.class.isAssignableFrom(parameter.nestedIfOptional().getNestedParameterType())) {
RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class);
return (requestParam != null && StringUtils.hasText(requestParam.name()));
}
else {
return true;
}
}
else {
if (parameter.hasParameterAnnotation(RequestPart.class)) {
return false;
}
parameter = parameter.nestedIfOptional();
if (MultipartResolutionDelegate.isMultipartArgument(parameter)) {
return true;
}
else if (this.useDefaultResolution) {
return BeanUtils.isSimpleProperty(parameter.getNestedParameterType());
}
else {
return false;
}
}
}
@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
RequestParam ann = parameter.getParameterAnnotation(RequestParam.class);
return (ann != null ? new RequestParamNamedValueInfo(ann) : new RequestParamNamedValueInfo());
}
@Override
@Nullable
protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
if (servletRequest != null) {
Object mpArg = MultipartResolutionDelegate.resolveMultipartArgument(name, parameter, servletRequest);
if (mpArg != MultipartResolutionDelegate.UNRESOLVABLE) {
return mpArg;
}
}
Object arg = null;
MultipartRequest multipartRequest = request.getNativeRequest(MultipartRequest.class);
if (multipartRequest != null) {
List<MultipartFile> files = multipartRequest.getFiles(name);
if (!files.isEmpty()) {
arg = (files.size() == 1 ? files.get(0) : files);
}
}
if (arg == null) {
String[] paramValues = request.getParameterValues(name);
if (paramValues != null) {
arg = (paramValues.length == 1 ? paramValues[0] : paramValues);
}
}
// yue-library
if (arg == null) {
JSONObject param = (JSONObject) servletRequest.getAttribute(Constant.BODY_PARAM_TRANSMIT);
if (param == null) {
param = ParamUtils.getParam();
servletRequest.setAttribute(Constant.BODY_PARAM_TRANSMIT, param);
}
arg = param.get(name);
}
return arg;
}
@Override
protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request)
throws Exception {
HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
if (MultipartResolutionDelegate.isMultipartArgument(parameter)) {
if (servletRequest == null || !MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
throw new MultipartException("Current request is not a multipart request");
}
else {
throw new MissingServletRequestPartException(name);
}
}
else {
throw new MissingServletRequestParameterException(name,
parameter.getNestedParameterType().getSimpleName());
}
}
@Override
public void contributeMethodArgument(MethodParameter parameter, @Nullable Object value,
UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {
Class<?> paramType = parameter.getNestedParameterType();
if (Map.class.isAssignableFrom(paramType) || MultipartFile.class == paramType || Part.class == paramType) {
return;
}
RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class);
String name = (requestParam != null && StringUtils.hasLength(requestParam.name()) ?
requestParam.name() : parameter.getParameterName());
Assert.state(name != null, "Unresolvable parameter name");
if (value == null) {
if (requestParam != null &&
(!requestParam.required() || !requestParam.defaultValue().equals(ValueConstants.DEFAULT_NONE))) {
return;
}
builder.queryParam(name);
}
else if (value instanceof Collection) {
for (Object element : (Collection<?>) value) {
element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element);
builder.queryParam(name, element);
}
}
else {
builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(parameter), value));
}
}
@Nullable
protected String formatUriValue(
@Nullable ConversionService cs, @Nullable TypeDescriptor sourceType, @Nullable Object value) {
if (value == null) {
return null;
}
else if (value instanceof String) {
return (String) value;
}
else if (cs != null) {
return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR);
}
else {
return value.toString();
}
}
private static class RequestParamNamedValueInfo extends NamedValueInfo {
public RequestParamNamedValueInfo() {
super("", false, ValueConstants.DEFAULT_NONE);
}
public RequestParamNamedValueInfo(RequestParam annotation) {
super(annotation.name(), annotation.required(), annotation.defaultValue());
}
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/argument | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/argument/resolver/JSONObjectArgumentResolver.java | package ai.yue.library.web.config.argument.resolver;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import com.alibaba.fastjson.JSONObject;
import ai.yue.library.base.util.ParamUtils;
/**
* JSONObject方法参数解析器
*
* @author ylyue
* @since 2019年8月2日
*/
public class JSONObjectArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(JSONObject.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
return ParamUtils.getParam();
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/argument | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/argument/resolver/JavaBeanArgumentResolver.java | package ai.yue.library.web.config.argument.resolver;
import javax.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.core.MethodParameter;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import ai.yue.library.base.util.ParamUtils;
import ai.yue.library.base.util.SpringUtils;
import ai.yue.library.base.validation.Validator;
import cn.hutool.core.bean.BeanUtil;
/**
* POJO、IPO、JavaBean对象方法参数解析器
*
* @author ylyue
* @since 2020年6月9日
*/
public class JavaBeanArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
Class<?> parameterType = parameter.getParameterType();
return !BeanUtils.isSimpleProperty(parameterType) && BeanUtil.isBean(parameterType);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
Object param = ParamUtils.getParam(parameter.getParameterType());
if (parameter.hasParameterAnnotation(Valid.class) || parameter.hasParameterAnnotation(Validated.class)) {
SpringUtils.getBean(Validator.class).valid(param);
}
return param;
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/argument | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/argument/resolver/package-info.java | /**
* 方法参数解析器
*
* @author ylyue
* @since 2019年10月13日
*/
package ai.yue.library.web.config.argument.resolver; |
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/handler/ExceptionHandlerConfig.java | package ai.yue.library.web.config.handler;
import java.io.IOException;
import java.util.List;
import javax.validation.Valid;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import ai.yue.library.base.config.handler.AbstractExceptionHandler;
import ai.yue.library.base.exception.AuthorizeException;
import ai.yue.library.base.exception.ParamDecryptException;
import ai.yue.library.base.exception.ParamException;
import ai.yue.library.base.exception.ParamVoidException;
import ai.yue.library.base.exception.ResultException;
import ai.yue.library.base.util.ExceptionUtils;
import ai.yue.library.base.view.Result;
import ai.yue.library.base.view.ResultInfo;
import ai.yue.library.web.util.servlet.ServletUtils;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
/**
* 全局统一异常处理
*
* @author ylyue
* @since 2017年10月8日
*/
@Slf4j
@ControllerAdvice
@ConditionalOnProperty(prefix = "yue.exception-handler", name = "enabled", havingValue = "true", matchIfMissing = true)
public class ExceptionHandlerConfig extends AbstractExceptionHandler {
// Restful 异常拦截
/**
* 异常结果处理-synchronized
*
* @param e 结果异常
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(ResultException.class)
public synchronized Result<?> resultExceptionHandler(ResultException e) {
var result = e.getResult();
ServletUtils.getResponse().setStatus(result.getCode());
log.error(result.toString());
ExceptionUtils.printException(e);
return result;
}
/**
* 参数效验为空统一处理-432
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(ParamVoidException.class)
public Result<?> paramVoidExceptionHandler() {
ServletUtils.getResponse().setStatus(432);
return ResultInfo.paramVoid();
}
/**
* 参数效验未通过统一处理-433
* @param e 参数校验未通过异常
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(ParamException.class)
public Result<?> paramExceptionHandler(ParamException e) {
ServletUtils.getResponse().setStatus(433);
ExceptionUtils.printException(e);
return ResultInfo.paramCheckNotPass(e.getMessage());
}
/**
* {@linkplain Valid} 验证异常统一处理-433
* @param e 验证异常
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(BindException.class)
public Result<?> bindExceptionHandler(BindException e) {
ServletUtils.getResponse().setStatus(433);
String uri = ServletUtils.getRequest().getRequestURI();
Console.error("uri={}", uri);
List<ObjectError> errors = e.getAllErrors();
JSONObject paramHint = new JSONObject();
errors.forEach(error -> {
String str = StrUtil.subAfter(error.getArguments()[0].toString(), "[", true);
String key = str.substring(0, str.length() - 1);
String msg = error.getDefaultMessage();
paramHint.put(key, msg);
Console.error(key + " " + msg);
});
return ResultInfo.paramCheckNotPass(paramHint.toString());
}
/**
* 验证异常统一处理-433
* @param e 验证异常
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(ValidateException.class)
public Result<?> validateExceptionHandler(ValidateException e) {
ServletUtils.getResponse().setStatus(433);
ExceptionUtils.printException(e);
return ResultInfo.paramCheckNotPass(e.getMessage());
}
/**
* 解密异常统一处理-435
*
* @param e 解密异常
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(ParamDecryptException.class)
public Result<?> paramDecryptExceptionHandler(ParamDecryptException e) {
ServletUtils.getResponse().setStatus(435);
log.error("【解密错误】错误信息如下:{}", e.getMessage());
ExceptionUtils.printException(e);
return ResultInfo.paramDecryptError();
}
// WEB 异常拦截
/**
* 拦截登录异常(Admin)-301
*
* @param e 认证异常
* @throws IOException 重定向失败
*/
@Override
@ExceptionHandler(AuthorizeException.class)
public void authorizeExceptionHandler(AuthorizeException e) throws IOException {
ExceptionUtils.printException(e);
ServletUtils.getResponse().sendRedirect("");
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/handler/package-info.java | /**
* 全局统一异常处理
*
* @author ylyue
* @since 2019年10月13日
*/
package ai.yue.library.web.config.handler; |
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/properties/FastJsonHttpMessageConverterProperties.java | package ai.yue.library.web.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import com.alibaba.fastjson.serializer.SerializerFeature;
import ai.yue.library.base.constant.FieldNamingStrategyEnum;
import lombok.Data;
/**
* FastJson HTTP消息转换器配置
*
* @author ylyue
* @since 2020年4月6日
*/
@Data
@ConfigurationProperties("yue.web.http-message-converter.fastjson")
public class FastJsonHttpMessageConverterProperties {
/**
* 启用FastJson优先于默认的Jackson做json解析
* <p>默认:false
*/
private boolean enabled = false;
/**
* 字段命名策略
*/
private FieldNamingStrategyEnum fieldNamingStrategy;
/**
* 自定义序列化特性
* <p>HTTP序列化时对null值进行初始化处理,默认做如下配置:
* <pre>
* SerializerFeature.PrettyFormat, // 格式化Json文本
* SerializerFeature.BrowserCompatible, // 浏览器兼容(IE)
* SerializerFeature.IgnoreErrorGetter, // 忽略错误的字段Get方法
* SerializerFeature.WriteDateUseDateFormat, // 对时间类型进行格式化(默认:yyyy-MM-dd HH:mm:ss)
* SerializerFeature.WriteMapNullValue, // 对Null值进行输出
* SerializerFeature.WriteNullListAsEmpty, // Null List 输出为 []
* SerializerFeature.WriteNullStringAsEmpty // Null String 输出为空字符串
* </pre>
*/
private SerializerFeature[] serializerFeatures = {
SerializerFeature.PrettyFormat, // 格式化Json文本
SerializerFeature.BrowserCompatible, // 浏览器兼容(IE)
SerializerFeature.IgnoreErrorGetter, // 忽略错误的字段Get方法
SerializerFeature.WriteDateUseDateFormat, // 对时间类型进行格式化(默认:yyyy-MM-dd HH:mm:ss)
SerializerFeature.WriteMapNullValue, // 对Null值进行输出
SerializerFeature.WriteNullListAsEmpty, // Null List 输出为 []
SerializerFeature.WriteNullStringAsEmpty // Null String 输出为空字符串
// SerializerFeature.WriteNullBooleanAsFalse, // Null Boolean 输出为 false
// SerializerFeature.WriteNullNumberAsZero // Null Number 输出为 0
};
/**
* 输出Null值为空字符串
* <p>排除 {@link #getSerializerFeatures()} 中可配置的Null处理(基本数据类型、List、Boolean)
* <p>排除 {@link #isWriteMapAsEmpty()} (Map)
* <p>默认:true
*/
private boolean writeNullAsStringEmpty = true;
/**
* 输出 Null Map 为 {}
* <p>默认:true
*/
private boolean writeNullMapAsEmpty = true;
/**
* 输出 Null Array 为 []
* <p>默认:true
*/
private boolean writeNullArrayAsEmpty = true;
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/properties/JacksonHttpMessageConverterProperties.java | package ai.yue.library.web.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import ai.yue.library.base.constant.FieldNamingStrategyEnum;
import lombok.Data;
/**
* Jackson HTTP消息转换器配置
*
* @author ylyue
* @since 2020年4月6日
*/
@Data
@ConfigurationProperties("yue.web.http-message-converter.jackson")
public class JacksonHttpMessageConverterProperties {
/**
* 启用yue-library对Jackson进行增强配置
* <p>Jackson是SpringBoot默认的Json解析器
* <p>默认:false
*/
private boolean enabled = false;
/**
* 字段命名策略
*/
private FieldNamingStrategyEnum fieldNamingStrategy;
/**
* 输出Null值为空字符串
* <p>默认:true
*/
private boolean writeNullAsStringEmpty = true;
/**
* Null String 输出为空字符串
* <p>默认:true
*/
private boolean WriteNullStringAsEmpty = true;
/**
* 输出 Null Map 为 {}
* <p>默认:true
*/
private boolean writeNullMapAsEmpty = true;
/**
* Null List 输出为 []
* <p>默认:true
*/
private boolean WriteNullListAsEmpty = true;
/**
* 输出 Null Array 为 []
* <p>默认:true
*/
private boolean writeNullArrayAsEmpty = true;
/**
* Null Boolean 输出为 false
* <p>默认:false
*/
private boolean WriteNullBooleanAsFalse = false;
/**
* Null Number 输出为 0
* <p>默认:false
*/
private boolean WriteNullNumberAsZero = false;
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/config/properties/WebProperties.java | package ai.yue.library.web.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
/**
* @author ylyue
* @since 2020年4月6日
*/
@Data
@ConfigurationProperties("yue.web")
public class WebProperties {
/**
* 启用FastJson优先于默认的Jackson做json解析
* <p>HTTP序列化时对null值进行初始化处理:<br>
* <code>
* SerializerFeature.WriteMapNullValue,
* SerializerFeature.WriteNullBooleanAsFalse,
* SerializerFeature.WriteNullListAsEmpty,
* SerializerFeature.WriteNullNumberAsZero,
* SerializerFeature.WriteNullStringAsEmpty
* </code>
* <p>默认:false
* @deprecated {@linkplain FastJsonHttpMessageConverterProperties#isEnabled()}
*/
@Deprecated
private boolean enabledFastJsonHttpMessageConverter = false;
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/env/WebMvcEnv.java | package ai.yue.library.web.env;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import ai.yue.library.base.view.Result;
import ai.yue.library.base.webenv.WebEnv;
import ai.yue.library.web.util.RequestParamUtils;
import ai.yue.library.web.util.servlet.ServletUtils;
/**
* @author ylyue
* @since 2020年4月16日
*/
@Component
public class WebMvcEnv implements WebEnv {
@Override
public void resultResponse(Result<?> result) {
HttpServletResponse response = ServletUtils.getResponse();
response.setContentType("application/json; charset=utf-8");
PrintWriter writer;
try {
writer = response.getWriter();
writer.print(JSONObject.toJSONString(result));
writer.close();
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public JSONObject getParam() {
return RequestParamUtils.getParam();
}
@Override
public <T> T getParam(Class<T> clazz) {
return RequestParamUtils.getParam(clazz);
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/ipo/CaptchaIPO.java | package ai.yue.library.web.ipo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 默认值:
* <p>
* <code>
* 字符数量(默认值:4个字符) int charQuantity = 4;<br>
*
* 图片宽度(默认值:100) int width = 100;<br>
*
* 图片高度(默认值:36) int height = 36;<br>
*
* 干扰线数量(默认值:5) int interferingLineQuantity = 5;<br>
*
* 字体大小(默认值:30) int fontSize = 30;
* </code>
*
* @author ylyue
* @since 2018年7月23日
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CaptchaIPO {
/** 字符数量(默认值:4个字符) */
@Builder.Default
int charQuantity = 4;
/** 图片宽度(默认值:100) */
@Builder.Default
int width = 100;
/** 图片高度(默认值:36) */
@Builder.Default
int height = 36;
/** 干扰线数量(默认值:5) */
@Builder.Default
int interferingLineQuantity = 5;
/** 字体大小(默认值:30) */
@Builder.Default
int fontSize = 30;
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/ipo/package-info.java | /**
* IPO定义
*
* @author ylyue
* @since 2019年10月13日
*/
package ai.yue.library.web.ipo; |
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/CaptchaUtils.java | package ai.yue.library.web.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.servlet.http.HttpSession;
import ai.yue.library.base.util.StringUtils;
import ai.yue.library.web.ipo.CaptchaIPO;
import ai.yue.library.web.util.servlet.ServletUtils;
import ai.yue.library.web.vo.CaptchaVO;
/**
* 验证码工具类,用于创建验证码图片与验证验证码
* <p>若需要分布式验证,推荐使用 yue-library-data-redis 模块 User 类所提供的 getCaptchaImage() 方法
*
* @author ylyue
* @since 2018年4月3日
*/
public class CaptchaUtils {
/**
* Captcha Key
*/
public static final String CAPTCHA_KEY = "captcha";
/**
* Captcha Redis 前缀
*/
public static final String CAPTCHA_REDIS_PREFIX = "captcha_%s";
private static final char[] CHARS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256));
return color;
}
/**
* 创建验证码
* @param captchaIPO 验证码IPO
* @return 验证码VO
*/
public static CaptchaVO createCaptchaImage(CaptchaIPO captchaIPO) {
// 1. 解析参数
int width = captchaIPO.getWidth();
int height = captchaIPO.getHeight();
int charQuantity = captchaIPO.getCharQuantity();
int fontSize = captchaIPO.getFontSize();
int interferingLineQuantity = captchaIPO.getInterferingLineQuantity();
// 2. 创建空白图片
StringBuffer captcha = new StringBuffer();
BufferedImage captchaImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 3. 获取图片画笔
Graphics graphic = captchaImage.getGraphics();
// 4.设置画笔颜色
graphic.setColor(Color.LIGHT_GRAY);
// 5.绘制矩形背景
graphic.fillRect(0, 0, width, height);
// 6.画随机字符
Random ran = new Random();
for (int i = 0; i < charQuantity; i++) {
// 取随机字符索引
int n = ran.nextInt(CHARS.length);
// 设置随机颜色
graphic.setColor(getRandomColor());
// 设置字体大小
graphic.setFont(new Font(
null, Font.BOLD + Font.ITALIC, fontSize));
// 画字符
graphic.drawString(CHARS[n] + "", i * width / charQuantity, height * 2 / 3);
// 记录字符
captcha.append(CHARS[n]);
}
// 7.画干扰线
for (int i = 0; i < interferingLineQuantity; i++) {
// 设置随机颜色
graphic.setColor(getRandomColor());
// 随机画线
graphic.drawLine(ran.nextInt(width), ran.nextInt(height), ran.nextInt(width), ran.nextInt(height));
}
graphic.dispose();
// 8.返回验证码和图片
return CaptchaVO.builder().captcha(captcha.toString()).captchaImage(captchaImage).build();
}
/**
* 验证-验证码
*
* @param captcha 验证码
* @return 是否正确
*/
public static boolean isValidateCaptcha(String captcha) {
HttpSession httpSession = ServletUtils.getSession();
String randCaptcha = (String) httpSession.getAttribute(CAPTCHA_KEY);
if (StringUtils.isEmpty(randCaptcha) || !randCaptcha.equalsIgnoreCase(captcha)) {
return false;
}
httpSession.removeAttribute(CAPTCHA_KEY);
return true;
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/NetUtils.java | package ai.yue.library.web.util;
import ai.yue.library.web.util.servlet.ServletUtils;
import cn.hutool.core.net.NetUtil;
/**
* 网络相关工具
*
* @author ylyue
* @since 2018年4月4日
*/
public class NetUtils extends NetUtil {
/**
* 判定是否为内网IP<br>
* 私有IP:A类 10.0.0.0-10.255.255.255 B类 172.16.0.0-172.31.255.255 C类 192.168.0.0-192.168.255.255 当然,还有127这个网段是环回地址
*
* @return 是否为内网IP
*/
public static Boolean isInnerIP() {
// 1. 获取客户端IP地址,考虑反向代理的问题
String ip = ServletUtils.getClientIP();
// 2. 确认是否为内网IP
if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
return true;
}
return isInnerIP(ip);
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/RequestParamUtils.java | package ai.yue.library.web.util;
import ai.yue.library.base.convert.Convert;
import ai.yue.library.base.util.StringUtils;
import ai.yue.library.web.util.servlet.ServletUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
* 请求参数工具栏
*
* @author: liuyang
* @Date: 2020/6/5
*/
@Slf4j
public class RequestParamUtils {
/**
* 工具栏,不允许实例
*/
private RequestParamUtils() {
}
/**
* 获取请求参数
*
* @Author: liuyang
* @return JSONObject
*/
public static JSONObject getParam() {
HttpServletRequest request = ServletUtils.getRequest();
String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);
//判断请求内容类型
if (StringUtils.isNotEmpty(contentType) && MediaType.MULTIPART_FORM_DATA_VALUE.equals(contentType.split(";")[0])) {
return getRequestUrlParamJson(request);
} else {
//TODO html、xml、JavaScript暂时当做json处理,后序有业务需求时再迭代
return getRawJson(request);
}
}
/**
* 获取参数,转换为java对象
*
* @Author: liuyang
* @param clazz java类
* @return 实例对象
*/
public static <T> T getParam(Class<T> clazz) {
JSONObject paramJson = getParam();
return Convert.toJavaBean(paramJson, clazz);
}
/**
* 获取url参数
*
* @Author: liuyang
* @return JSONObject
*/
private static JSONObject getRequestUrlParamJson(HttpServletRequest request) {
JSONObject json = new JSONObject();
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
json.put(paramName, request.getParameter(paramName));
}
return json;
}
/**
* 获取raw JSON格式
*
* @Author: liuyang
* @return json对象
*/
private static JSONObject getRawJson(HttpServletRequest request) {
//获取url中的参数
JSONObject json = getRequestUrlParamJson(request);
String body = null;
try {
body = ServletUtils.getBody(request);
}catch (IllegalStateException e){
log.warn("获取body读取流异常: {}",e.getMessage());
}
//将字符串转为json
if (StringUtils.isNotEmpty(body)) {
JSONObject tempJson = Convert.toJSONObject(body);
for (String key : tempJson.keySet()) {
json.put(key, tempJson.get(key));
}
}
return json;
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/package-info.java | /**
* 提供各种工具方法,按照归类入口为XXXUtils,如字符串工具StringUtils等
*
* @author ylyue
* @since 2019年10月13日
*/
package ai.yue.library.web.util; |
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet/ServletUtils.java | package ai.yue.library.web.util.servlet;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.alibaba.fastjson.JSONObject;
import ai.yue.library.web.util.servlet.multipart.MultipartFormData;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.bean.copier.ValueProvider;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.map.CaseInsensitiveMap;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
/**
* Servlet相关工具类封装<br>
* 源自 hutool-extra 增强
*
* @author ylyue
* @since 2019年8月14日
*/
public class ServletUtils {
public static final String METHOD_DELETE = "DELETE";
public static final String METHOD_HEAD = "HEAD";
public static final String METHOD_GET = "GET";
public static final String METHOD_OPTIONS = "OPTIONS";
public static final String METHOD_POST = "POST";
public static final String METHOD_PUT = "PUT";
public static final String METHOD_TRACE = "TRACE";
public static final String HTTP_TCP_NAME = "http://";
public static final String HTTPS_TCP_NAME = "https://";
/**
* HttpAspect请求切入点
*/
public static final String POINTCUT = "@annotation(org.springframework.web.bind.annotation.RequestMapping)"
+ " || @annotation(org.springframework.web.bind.annotation.GetMapping)"
+ " || @annotation(org.springframework.web.bind.annotation.PostMapping)"
+ " || @annotation(org.springframework.web.bind.annotation.PutMapping)"
+ " || @annotation(org.springframework.web.bind.annotation.PatchMapping)"
+ " || @annotation(org.springframework.web.bind.annotation.DeleteMapping)";
/**
* 获得当前请求上下文中的{@linkplain ServletRequestAttributes}
* @return ServletRequestAttributes
*/
public static ServletRequestAttributes getRequestAttributes() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
}
/**
* 获得当前请求上下文中的{@linkplain HttpServletRequest}
* @return HttpServletRequest
*/
public static HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
/**
* 获得当前请求上下文中的{@linkplain HttpServletResponse}
* @return HttpServletResponse
*/
public static HttpServletResponse getResponse() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
}
/**
* 获得当前请求{@linkplain HttpSession}
* @return HttpSession
*/
public static HttpSession getSession() {
return getRequest().getSession();
}
/**
* 获得当前请求的服务器的URL地址
* <p>
* 示例一:http://localhost:8080<br>
* 示例二:http://localhost:8080/projectName<br>
* @return 当前请求的服务器的URL地址
*/
public static String getServerURL() {
HttpServletRequest request = getRequest();
String serverName = request.getServerName();// 服务器地址
int serverPort = request.getServerPort();// 端口号
String contextPath = request.getContextPath();// 项目名称
return HTTP_TCP_NAME + serverName + ":" + serverPort + contextPath;
}
/**
* 打印请求报文
* <p>
* 注意:打印不包括:异步请求内容、数据流
*/
public static void printRequest() {
// 1. 打印请求信息
HttpServletRequest request = getRequest();
Console.error("========开始-打印请求报文========");
Console.log();
Console.log("打印请求信息:");
Console.log("RemoteAddr:{}", request.getRemoteAddr());
Console.log("Method:{}", request.getMethod());
Console.log("AuthType:{}", request.getAuthType());
// 2. 打印服务器信息
Console.log();
Console.log("打印服务器信息:");
Console.log("ServerURL:{}", getServerURL());
Console.log("RequestURL:{}", request.getRequestURL());
Console.log("RequestedSessionId:{}", request.getRequestedSessionId());
// 3. 打印请求参数
Console.log();
Console.log("打印请求参数:");
Console.log("QueryString:{}", request.getQueryString());
Console.log("ParameterMap:{}", JSONObject.toJSONString(request.getParameterMap()));
// 4. 打印请求头
Console.log();
Console.log("打印请求头:");
Console.log("Headers:");
request.getHeaderNames().asIterator().forEachRemaining(headerName -> {
StringBuilder headerValues = new StringBuilder();
request.getHeaders(headerName).asIterator().forEachRemaining(headerValue -> {
headerValues.append(headerValue);
});;
Console.log(" {}:{}", headerName, headerValues);
});;
// 5. 打印Cookie
Console.log();
Console.log("Cookies:");
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
Console.log(" {}:{}", cookie.getName(), cookie.getValue());
}
}
Console.error("========结束-打印请求报文========");
}
// --------------------------------------------------------- getParam start
/**
* 获得所有请求参数
*
* @param request 请求对象{@link ServletRequest}
* @return Map
*/
public static Map<String, String[]> getParams(ServletRequest request) {
final Map<String, String[]> map = request.getParameterMap();
return Collections.unmodifiableMap(map);
}
/**
* 获得所有请求参数
*
* @param request 请求对象{@link ServletRequest}
* @return Map
*/
public static Map<String, String> getParamMap(ServletRequest request) {
Map<String, String> params = new HashMap<>();
for (Map.Entry<String, String[]> entry : getParams(request).entrySet()) {
params.put(entry.getKey(), ArrayUtil.join(entry.getValue(), StrUtil.COMMA));
}
return params;
}
/**
* 获取请求体<br>
* 调用该方法后,getParam方法将失效
*
* @param request {@link ServletRequest}
* @return 获得请求体
* @since 4.0.2
*/
public static String getBody(ServletRequest request) {
try {
return IoUtil.read(request.getReader());
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
/**
* 获取请求体byte[]<br>
* 调用该方法后,getParam方法将失效
*
* @param request {@link ServletRequest}
* @return 获得请求体byte[]
* @since 4.0.2
*/
public static byte[] getBodyBytes(ServletRequest request) {
try {
return IoUtil.readBytes(request.getInputStream());
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
// --------------------------------------------------------- getParam end
// --------------------------------------------------------- fillBean start
/**
* ServletRequest 参数转Bean
*
* @param <T> Bean类型
* @param request ServletRequest
* @param bean Bean
* @param copyOptions 注入时的设置
* @return Bean
* @since 3.0.4
*/
public static <T> T fillBean(final ServletRequest request, T bean, CopyOptions copyOptions) {
final String beanName = StrUtil.lowerFirst(bean.getClass().getSimpleName());
return BeanUtil.fillBean(bean, new ValueProvider<String>() {
@Override
public Object value(String key, Type valueType) {
String[] values = request.getParameterValues(key);
if(ArrayUtil.isEmpty(values)){
values = request.getParameterValues(beanName + StrUtil.DOT + key);
if(ArrayUtil.isEmpty(values)){
return null;
}
}
if(1 == values.length){
// 单值表单直接返回这个值
return values[0];
}else{
// 多值表单返回数组
return values;
}
}
@Override
public boolean containsKey(String key) {
// 对于Servlet来说,返回值null意味着无此参数
return (null != request.getParameter(key)) || (null != request.getParameter(beanName + StrUtil.DOT + key));
}
}, copyOptions);
}
/**
* ServletRequest 参数转Bean
*
* @param <T> Bean类型
* @param request {@link ServletRequest}
* @param bean Bean
* @param isIgnoreError 是否忽略注入错误
* @return Bean
*/
public static <T> T fillBean(ServletRequest request, T bean, boolean isIgnoreError) {
return fillBean(request, bean, CopyOptions.create().setIgnoreError(isIgnoreError));
}
/**
* ServletRequest 参数转Bean
*
* @param <T> Bean类型
* @param request ServletRequest
* @param beanClass Bean Class
* @param isIgnoreError 是否忽略注入错误
* @return Bean
*/
public static <T> T toBean(ServletRequest request, Class<T> beanClass, boolean isIgnoreError) {
return fillBean(request, ReflectUtil.newInstanceIfPossible(beanClass), isIgnoreError);
}
// --------------------------------------------------------- fillBean end
/**
* 获取客户端IP
*
* <p>
* 默认检测的Header:
*
* <pre>
* 1、X-Forwarded-For
* 2、X-Real-IP
* 3、Proxy-Client-IP
* 4、WL-Proxy-Client-IP
* </pre>
*
* <p>
* otherHeaderNames参数用于自定义检测的Header<br>
* 需要注意的是,使用此方法获取的客户IP地址必须在Http服务器(例如Nginx)中配置头信息,否则容易造成IP伪造。
* </p>
*
* @param otherHeaderNames 其他自定义头文件,通常在Http服务器(例如Nginx)中配置
* @return IP地址
*/
public static String getClientIP(String... otherHeaderNames) {
String[] headers = { "X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR" };
if (ArrayUtil.isNotEmpty(otherHeaderNames)) {
headers = ArrayUtil.addAll(headers, otherHeaderNames);
}
return getClientIPByHeader(headers);
}
/**
* 获取客户端IP
*
* <p>
* headerNames参数用于自定义检测的Header<br>
* 需要注意的是,使用此方法获取的客户IP地址必须在Http服务器(例如Nginx)中配置头信息,否则容易造成IP伪造。
* </p>
*
* @param headerNames 自定义头,通常在Http服务器(例如Nginx)中配置
* @return IP地址
* @since 4.4.1
*/
public static String getClientIPByHeader(String... headerNames) {
String ip;
HttpServletRequest request = getRequest();
for (String header : headerNames) {
ip = request.getHeader(header);
if (false == isUnknow(ip)) {
return getMultistageReverseProxyIp(ip);
}
}
ip = request.getRemoteAddr();
return getMultistageReverseProxyIp(ip);
}
/**
* 获得multipart/form-data 表单内容<br>
* 包括文件和普通表单数据<br>
* 在同一次请求中,此方法只能被执行一次!
*
* @return MultiPart表单
* @throws IORuntimeException IO异常
* @since 4.0.2
*/
public static MultipartFormData getMultipart() throws IORuntimeException {
final MultipartFormData formData = new MultipartFormData();
try {
formData.parseRequest(getRequest());
} catch (IOException e) {
throw new IORuntimeException(e);
}
return formData;
}
// --------------------------------------------------------- Header start
/**
* 获取请求所有的头(header)信息
*
* @return header值
* @since 4.6.2
*/
public static Map<String, String> getHeaderMap() {
HttpServletRequest request = getRequest();
final Map<String, String> headerMap = new HashMap<>();
final Enumeration<String> names = request.getHeaderNames();
String name;
while (names.hasMoreElements()) {
name = names.nextElement();
headerMap.put(name, request.getHeader(name));
}
return headerMap;
}
/**
* 忽略大小写获得请求header中的信息
*
* @param nameIgnoreCase 忽略大小写头信息的KEY
* @return header值
*/
public static String getHeaderIgnoreCase(String nameIgnoreCase) {
HttpServletRequest request = getRequest();
final Enumeration<String> names = request.getHeaderNames();
String name;
while (names.hasMoreElements()) {
name = names.nextElement();
if (name != null && name.equalsIgnoreCase(nameIgnoreCase)) {
return request.getHeader(name);
}
}
return null;
}
/**
* 获得请求header中的信息
*
* @param name 头信息的KEY
* @param charsetName 字符集
* @return header值
*/
public static String getHeader(String name, String charsetName) {
return getHeader(name, CharsetUtil.charset(charsetName));
}
/**
* 获得请求header中的信息
*
* @param name 头信息的KEY
* @param charset 字符集
* @return header值
* @since 4.6.2
*/
public static String getHeader(String name, Charset charset) {
final String header = getRequest().getHeader(name);
if (null != header) {
return CharsetUtil.convert(header, CharsetUtil.CHARSET_ISO_8859_1, charset);
}
return null;
}
/**
* 客户浏览器是否为IE
*
* @return 客户浏览器是否为IE
*/
public static boolean isIE() {
String userAgent = getHeaderIgnoreCase("User-Agent");
if (StrUtil.isNotBlank(userAgent)) {
//noinspection ConstantConditions
userAgent = userAgent.toUpperCase();
return userAgent.contains("MSIE") || userAgent.contains("TRIDENT");
}
return false;
}
/**
* 是否为GET请求
*
* @return 是否为GET请求
*/
public static boolean isGetMethod() {
return METHOD_GET.equalsIgnoreCase(getRequest().getMethod());
}
/**
* 是否为POST请求
*
* @return 是否为POST请求
*/
public static boolean isPostMethod() {
return METHOD_POST.equalsIgnoreCase(getRequest().getMethod());
}
/**
* 是否为Multipart类型表单,此类型表单用于文件上传
*
* @return 是否为Multipart类型表单,此类型表单用于文件上传
*/
public static boolean isMultipart() {
if (false == isPostMethod()) {
return false;
}
String contentType = getRequest().getContentType();
if (StrUtil.isBlank(contentType)) {
return false;
}
return contentType.toLowerCase().startsWith("multipart/");
}
// --------------------------------------------------------- Header end
// --------------------------------------------------------- Cookie start
/**
* 获得指定的Cookie
*
* @param name cookie名
* @return Cookie对象
*/
public static Cookie getCookie(String name) {
return readCookieMap().get(name);
}
/**
* 将cookie封装到Map里面
*
* @return Cookie map
*/
public static Map<String, Cookie> readCookieMap() {
final Map<String, Cookie> cookieMap = new CaseInsensitiveMap<>();
final Cookie[] cookies = getRequest().getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie);
}
}
return cookieMap;
}
/**
* 设定返回给客户端的Cookie
*
* @param cookie Servlet Cookie对象
*/
public static void addCookie(Cookie cookie) {
getResponse().addCookie(cookie);
}
/**
* 设定返回给客户端的Cookie
*
* @param name Cookie名
* @param value Cookie值
*/
public static void addCookie(String name, String value) {
getResponse().addCookie(new Cookie(name, value));
}
/**
* 设定返回给客户端的Cookie
*
* @param name cookie名
* @param value cookie值
* @param maxAgeInSeconds -1: 关闭浏览器清除Cookie. 0: 立即清除Cookie. >0 : Cookie存在的秒数.
* @param path Cookie的有效路径
* @param domain the domain name within which this cookie is visible; form is according to RFC 2109
*/
public static void addCookie(String name, String value, int maxAgeInSeconds, String path, String domain) {
Cookie cookie = new Cookie(name, value);
if (domain != null) {
cookie.setDomain(domain);
}
cookie.setMaxAge(maxAgeInSeconds);
cookie.setPath(path);
addCookie(cookie);
}
/**
* 设定返回给客户端的Cookie<br>
* Path: "/"<br>
* No Domain
*
* @param name cookie名
* @param value cookie值
* @param maxAgeInSeconds -1: 关闭浏览器清除Cookie. 0: 立即清除Cookie. >0 : Cookie存在的秒数.
*/
public static void addCookie(String name, String value, int maxAgeInSeconds) {
addCookie(name, value, maxAgeInSeconds, "/", null);
}
// --------------------------------------------------------- Cookie end
// --------------------------------------------------------- Response start
/**
* 获得PrintWriter
*
* @return 获得PrintWriter
* @throws IORuntimeException IO异常
*/
public static PrintWriter getWriter() throws IORuntimeException {
try {
return getResponse().getWriter();
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
/**
* 返回数据给客户端
*
* @param text 返回的内容
* @param contentType 返回的类型
*/
public static void write(String text, String contentType) {
HttpServletResponse response = getResponse();
response.setContentType(contentType);
Writer writer = null;
try {
writer = response.getWriter();
writer.write(text);
writer.flush();
} catch (IOException e) {
throw new UtilException(e);
} finally {
IoUtil.close(writer);
}
}
/**
* 返回文件给客户端
*
* @param file 写出的文件对象
* @since 4.1.15
*/
public static void write(File file) {
final String fileName = file.getName();
final String contentType = ObjectUtil.defaultIfNull(FileUtil.getMimeType(fileName), "application/octet-stream");
BufferedInputStream in = null;
try {
in = FileUtil.getInputStream(file);
write(in, contentType, fileName);
} finally {
IoUtil.close(in);
}
}
/**
* 返回数据给客户端
*
* @param in 需要返回客户端的内容
* @param contentType 返回的类型
* @param fileName 文件名
* @since 4.1.15
*/
public static void write(InputStream in, String contentType, String fileName) {
HttpServletResponse response = getResponse();
final String charset = ObjectUtil.defaultIfNull(response.getCharacterEncoding(), CharsetUtil.UTF_8);
response.setHeader("Content-Disposition", StrUtil.format("attachment;filename={}", URLUtil.encode(fileName, charset)));
response.setContentType(contentType);
write(in);
}
/**
* 返回数据给客户端
*
* @param in 需要返回客户端的内容
* @param contentType 返回的类型
*/
public static void write(InputStream in, String contentType) {
getResponse().setContentType(contentType);
write(in);
}
/**
* 返回数据给客户端
*
* @param in 需要返回客户端的内容
*/
public static void write(InputStream in) {
write(in, IoUtil.DEFAULT_BUFFER_SIZE);
}
/**
* 返回数据给客户端
*
* @param in 需要返回客户端的内容
* @param bufferSize 缓存大小
*/
public static void write(InputStream in, int bufferSize) {
ServletOutputStream out = null;
try {
out = getResponse().getOutputStream();
IoUtil.copy(in, out, bufferSize);
} catch (IOException e) {
throw new UtilException(e);
} finally {
IoUtil.close(out);
IoUtil.close(in);
}
}
/**
* 设置响应的Header
*
* @param name 名
* @param value 值,可以是String,Date, int
*/
public static void setHeader(String name, Object value) {
HttpServletResponse response = getResponse();
if (value instanceof String) {
response.setHeader(name, (String) value);
} else if (Date.class.isAssignableFrom(value.getClass())) {
response.setDateHeader(name, ((Date) value).getTime());
} else if (value instanceof Integer || "int".equals(value.getClass().getSimpleName().toLowerCase())) {
response.setIntHeader(name, (int) value);
} else {
response.setHeader(name, value.toString());
}
}
// --------------------------------------------------------- Response end
// --------------------------------------------------------- Private methd start
/**
* 从多级反向代理中获得第一个非unknown IP地址
*
* @param ip 获得的IP地址
* @return 第一个非unknown IP地址
*/
private static String getMultistageReverseProxyIp(String ip) {
// 多级反向代理检测
if (ip != null && ip.indexOf(",") > 0) {
final String[] ips = ip.trim().split(",");
for (String subIp : ips) {
if (false == isUnknow(subIp)) {
ip = subIp;
break;
}
}
}
return ip;
}
/**
* 检测给定字符串是否为未知,多用于检测HTTP请求相关<br>
*
* @param checkString 被检测的字符串
* @return 是否未知
*/
private static boolean isUnknow(String checkString) {
return StrUtil.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
}
// --------------------------------------------------------- Private methd end
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet/package-info.java | /**
* Servlet工具类
*
* @author ylyue
* @since 2019年10月18日
*/
package ai.yue.library.web.util.servlet; |
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet/multipart/MultipartFormData.java | package ai.yue.library.web.util.servlet.multipart;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletRequest;
import cn.hutool.core.util.ArrayUtil;
import lombok.NoArgsConstructor;
/**
* HttpRequest解析器<br>
* 源自 hutool-extra
*
* @author ylyue
* @since 2019年8月14日
*/
@NoArgsConstructor
public class MultipartFormData {
/** 请求参数 */
private Map<String, String[]> requestParameters = new HashMap<String, String[]>();
/** 请求文件 */
private Map<String, UploadFile[]> requestFiles = new HashMap<String, UploadFile[]>();
/** 是否解析完毕 */
private boolean loaded;
/**
* 解析上传文件和表单数据
*
* @param request Http请求
* @throws IOException IO异常
*/
public void parseRequest(ServletRequest request) throws IOException {
parseRequestStream(request.getInputStream(), request.getCharacterEncoding());
}
/**
* 提取上传的文件和表单数据
*
* @param inputStream HttpRequest流
* @param charset 编码
* @throws IOException IO异常
*/
public void parseRequestStream(InputStream inputStream, String charset) throws IOException {
setLoaded();
MultipartRequestInputStream input = new MultipartRequestInputStream(inputStream);
input.readBoundary();
while (true) {
UploadFileHeader header = input.readDataHeader(charset);
if (header == null) {
break;
}
if (header.isFile == true) {
// 文件类型的表单项
String fileName = header.fileName;
if (fileName.length() > 0 && header.contentType.contains("application/x-macbinary")) {
input.skipBytes(128);
}
UploadFile newFile = new UploadFile(header);
newFile.processStream(input);
putFile(header.formFieldName, newFile);
} else {
// 标准表单项
ByteArrayOutputStream fbos = new ByteArrayOutputStream(1024);
input.copy(fbos);
String value = (charset != null) ? new String(fbos.toByteArray(), charset) : new String(fbos.toByteArray());
putParameter(header.formFieldName, value);
}
input.skipBytes(1);
input.mark(1);
// read byte, but may be end of stream
int nextByte = input.read();
if (nextByte == -1 || nextByte == '-') {
input.reset();
break;
}
input.reset();
}
}
// ---------------------------------------------------------------- parameters
/**
* 返回单一参数值,如果有多个只返回第一个
*
* @param paramName 参数名
* @return null未找到,否则返回值
*/
public String getParam(String paramName) {
if (requestParameters == null) {
return null;
}
String[] values = requestParameters.get(paramName);
if (ArrayUtil.isNotEmpty(values)) {
return values[0];
}
return null;
}
/**
* @return 获得参数名集合
*/
public Set<String> getParamNames() {
if (requestParameters == null) {
return Collections.emptySet();
}
return requestParameters.keySet();
}
/**
* 获得数组表单值
*
* @param paramName 参数名
* @return 数组表单值
*/
public String[] getArrayParam(String paramName) {
if (requestParameters == null) {
return null;
}
return requestParameters.get(paramName);
}
/**
* 获取所有属性的集合
*
* @return 所有属性的集合
*/
public Map<String, String[]> getParamMap() {
return requestParameters;
}
// --------------------------------------------------------------------------- Files parameters
/**
* 获取上传的文件
*
* @param paramName 文件参数名称
* @return 上传的文件, 如果无为null
*/
public UploadFile getFile(String paramName) {
UploadFile[] values = getFiles(paramName);
if ((values != null) && (values.length > 0)) {
return values[0];
}
return null;
}
/**
* 获得某个属性名的所有文件<br>
* 当表单中两个文件使用同一个name的时候
*
* @param paramName 属性名
* @return 上传的文件列表
*/
public UploadFile[] getFiles(String paramName) {
if (requestFiles == null) {
return null;
}
return requestFiles.get(paramName);
}
/**
* 获取上传的文件属性名集合
*
* @return 上传的文件属性名集合
*/
public Set<String> getFileParamNames() {
if (requestFiles == null) {
return Collections.emptySet();
}
return requestFiles.keySet();
}
/**
* 获取文件映射
*
* @return 文件映射
*/
public Map<String, UploadFile[]> getFileMap() {
return this.requestFiles;
}
// --------------------------------------------------------------------------- Load
/**
* 是否已被解析
*
* @return 如果流已被解析返回true
*/
public boolean isLoaded() {
return loaded;
}
// ---------------------------------------------------------------- Private method start
/**
* 加入上传文件
*
* @param name 参数名
* @param uploadFile 文件
*/
private void putFile(String name, UploadFile uploadFile) {
UploadFile[] fileUploads = requestFiles.get(name);
fileUploads = fileUploads == null ? new UploadFile[] { uploadFile } : ArrayUtil.append(fileUploads, uploadFile);
requestFiles.put(name, fileUploads);
}
/**
* 加入普通参数
*
* @param name 参数名
* @param value 参数值
*/
private void putParameter(String name, String value) {
String[] params = requestParameters.get(name);
params = params == null ? new String[] { value } : ArrayUtil.append(params, value);
requestParameters.put(name, params);
}
/**
* 设置使输入流为解析状态,如果已解析,则抛出异常
*
* @throws IOException IO异常
*/
private void setLoaded() throws IOException {
if (loaded == true) {
throw new IOException("Multi-part request already parsed.");
}
loaded = true;
}
// ---------------------------------------------------------------- Private method end
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet/multipart/MultipartRequestInputStream.java | package ai.yue.library.web.util.servlet.multipart;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Http请求解析流,提供了专门针对带文件的form表单的解析<br>
* 源自 hutool-extra
*
* @author ylyue
* @since 2019年8月14日
*/
public class MultipartRequestInputStream extends BufferedInputStream {
public MultipartRequestInputStream(InputStream in) {
super(in);
}
/**
* 读取byte字节流,在末尾抛出异常
*
* @return byte
* @throws IOException IO异常
*/
public byte readByte() throws IOException {
int i = super.read();
if (i == -1) {
throw new IOException("End of HTTP request stream reached");
}
return (byte) i;
}
/**
* 跳过指定位数的 bytes.
*
* @param i 跳过的byte数
* @throws IOException IO异常
*/
public void skipBytes(int i) throws IOException {
long len = super.skip(i);
if (len != i) {
throw new IOException("Unable to skip data in HTTP request");
}
}
// ---------------------------------------------------------------- boundary
/** part部分边界 */
protected byte[] boundary;
/**
* 输入流中读取边界
*
* @return 边界
* @throws IOException IO异常
*/
public byte[] readBoundary() throws IOException {
ByteArrayOutputStream boundaryOutput = new ByteArrayOutputStream(1024);
byte b;
// skip optional whitespaces
while ((b = readByte()) <= ' ') {
}
boundaryOutput.write(b);
// now read boundary chars
while ((b = readByte()) != '\r') {
boundaryOutput.write(b);
}
if (boundaryOutput.size() == 0) {
throw new IOException("Problems with parsing request: invalid boundary");
}
skipBytes(1);
boundary = new byte[boundaryOutput.size() + 2];
System.arraycopy(boundaryOutput.toByteArray(), 0, boundary, 2, boundary.length - 2);
boundary[0] = '\r';
boundary[1] = '\n';
return boundary;
}
// ---------------------------------------------------------------- data header
protected UploadFileHeader lastHeader;
public UploadFileHeader getLastHeader() {
return lastHeader;
}
/**
* 从流中读取文件头部信息, 如果达到末尾则返回null
*
* @param encoding 字符集
* @return 头部信息, 如果达到末尾则返回null
* @throws IOException IO异常
*/
public UploadFileHeader readDataHeader(String encoding) throws IOException {
String dataHeader = readDataHeaderString(encoding);
if (dataHeader != null) {
lastHeader = new UploadFileHeader(dataHeader);
} else {
lastHeader = null;
}
return lastHeader;
}
protected String readDataHeaderString(String encoding) throws IOException {
ByteArrayOutputStream data = new ByteArrayOutputStream();
byte b;
while (true) {
// end marker byte on offset +0 and +2 must be 13
if ((b = readByte()) != '\r') {
data.write(b);
continue;
}
mark(4);
skipBytes(1);
int i = read();
if (i == -1) {
// reached end of stream
return null;
}
if (i == '\r') {
reset();
break;
}
reset();
data.write(b);
}
skipBytes(3);
return encoding == null ? data.toString() : data.toString(encoding);
}
// ---------------------------------------------------------------- copy
/**
* 全部字节流复制到out
*
* @param out 输出流
* @return 复制的字节数
* @throws IOException IO异常
*/
public int copy(OutputStream out) throws IOException {
int count = 0;
while (true) {
byte b = readByte();
if (isBoundary(b)) {
break;
}
out.write(b);
count++;
}
return count;
}
/**
* 复制字节流到out, 大于maxBytes或者文件末尾停止
*
* @param out 输出流
* @param limit 最大字节数
* @return 复制的字节数
* @throws IOException IO异常
*/
public int copy(OutputStream out, int limit) throws IOException {
int count = 0;
while (true) {
byte b = readByte();
if (isBoundary(b)) {
break;
}
out.write(b);
count++;
if (count > limit) {
break;
}
}
return count;
}
/**
* 跳过边界表示
*
* @return 跳过的字节数
* @throws IOException IO异常
*/
public int skipToBoundary() throws IOException {
int count = 0;
while (true) {
byte b = readByte();
count++;
if (isBoundary(b)) {
break;
}
}
return count;
}
/**
* @param b byte
* @return 是否为边界的标志
* @throws IOException IO异常
*/
public boolean isBoundary(byte b) throws IOException {
int boundaryLen = boundary.length;
mark(boundaryLen + 1);
int bpos = 0;
while (b == boundary[bpos]) {
b = readByte();
bpos++;
if (bpos == boundaryLen) {
return true; // boundary found!
}
}
reset();
return false;
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet/multipart/UploadFile.java | package ai.yue.library.web.util.servlet.multipart;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import ai.yue.library.base.util.ApplicationContextUtils;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
/**
* 上传的文件对象<br>
* 源自 hutool-extra
*
* @author ylyue
* @since 2019年8月14日
*/
@Slf4j
public class UploadFile {
private static final String TMP_FILE_PREFIX = "hutool-";
private static final String TMP_FILE_SUFFIX = ".upload.tmp";
private UploadFileHeader header;
private UploadProperties uploadProperties;
private int size = -1;
// 文件流(小文件位于内存中)
private byte[] data;
// 临时文件(大文件位于临时文件夹中)
private File tempFile;
/**
* 构造
*
* @param header 头部信息
*/
public UploadFile(UploadFileHeader header) {
this.header = header;
uploadProperties = ApplicationContextUtils.getBean(UploadProperties.class);
}
// ---------------------------------------------------------------- operations
/**
* 从磁盘或者内存中删除这个文件
*/
public void delete() {
if (tempFile != null) {
tempFile.delete();
}
if (data != null) {
data = null;
}
}
/**
* 将上传的文件写入指定的目标文件路径,自动创建文件<br>
* 写入后原临时文件会被删除
* @param destPath 目标文件路径
* @return 目标文件
* @throws IOException IO异常
*/
public File write(String destPath) throws IOException {
if(data != null || tempFile != null) {
return write(FileUtil.touch(destPath));
}
return null;
}
/**
* 将上传的文件写入目标文件<br>
* 写入后原临时文件会被删除
*
* @param destination 目的地
* @return 目标文件
* @throws IOException IO异常
*/
public File write(File destination) throws IOException {
assertValid();
if (destination.isDirectory() == true) {
destination = new File(destination, this.header.getFileName());
}
if (data != null) {
FileUtil.writeBytes(data, destination);
data = null;
} else {
if (tempFile != null) {
FileUtil.move(tempFile, destination, true);
}
}
return destination;
}
/**
* @return 获得文件字节流
* @throws IOException IO异常
*/
public byte[] getFileContent() throws IOException {
assertValid();
if (data != null) {
return data;
}
if (tempFile != null) {
return FileUtil.readBytes(tempFile);
}
return null;
}
/**
* @return 获得文件流
* @throws IOException IO异常
*/
public InputStream getFileInputStream() throws IOException {
assertValid();
if (data != null) {
return new BufferedInputStream(new ByteArrayInputStream(data));
}
if (tempFile != null) {
return new BufferedInputStream(new FileInputStream(tempFile));
}
return null;
}
// ---------------------------------------------------------------- header
/**
* @return 上传文件头部信息
*/
public UploadFileHeader getHeader() {
return header;
}
/**
* @return 文件名
*/
public String getFileName() {
return header == null ? null : header.getFileName();
}
// ---------------------------------------------------------------- properties
/**
* @return 上传文件的大小,< 0 表示未上传
*/
public int size() {
return size;
}
/**
* @return 是否上传成功
*/
public boolean isUploaded() {
return size > 0;
}
/**
* @return 文件是否在内存中
*/
public boolean isInMemory() {
return data != null;
}
// ---------------------------------------------------------------- process
/**
* 处理上传表单流,提取出文件
*
* @param input 上传表单的流
* @return 是否处理成功
* @throws IOException IO异常
*/
protected boolean processStream(MultipartRequestInputStream input) throws IOException {
if (!isAllowedExtension()) {
// 非允许的扩展名
log.debug("Forbidden uploaded file [{}]", this.getFileName());
size = input.skipToBoundary();
return false;
}
size = 0;
// 处理内存文件
int memoryThreshold = uploadProperties.memoryThreshold;
if (memoryThreshold > 0) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(memoryThreshold);
int written = input.copy(baos, memoryThreshold);
data = baos.toByteArray();
if (written <= memoryThreshold) {
// 文件存放于内存
size = data.length;
return true;
}
}
// 处理硬盘文件
tempFile = FileUtil.createTempFile(TMP_FILE_PREFIX, TMP_FILE_SUFFIX, FileUtil.touch(uploadProperties.tmpUploadPath), false);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
if (data != null) {
size = data.length;
out.write(data);
data = null; // not needed anymore
}
int maxFileSize = uploadProperties.maxFileSize;
try {
if (maxFileSize == -1) {
size += input.copy(out);
return true;
}
size += input.copy(out, maxFileSize - size + 1); // one more byte to detect larger files
if (size > maxFileSize) {
// 超出上传大小限制
tempFile.delete();
tempFile = null;
log.debug("Upload file [{}] too big, file size > [{}]", this.getFileName(), maxFileSize);
input.skipToBoundary();
return false;
}
} finally {
IoUtil.close(out);
}
// if (getFileName().length() == 0 && size == 0) {
// size = -1;
// }
return true;
}
// ---------------------------------------------------------------------------- Private method start
/**
* @return 是否为允许的扩展名
*/
private boolean isAllowedExtension() {
List<String> exts = uploadProperties.fileExts;
boolean isAllow = uploadProperties.isAllowFileExts;
if (exts == null || exts.size() == 0) {
// 如果给定扩展名列表为空,当允许扩展名时全部允许,否则全部禁止
return isAllow;
}
String fileNameExt = FileUtil.extName(this.getFileName());
for (String fileExtension : exts) {
if (fileNameExt.equalsIgnoreCase(fileExtension)) {
return isAllow;
}
}
// 未匹配到扩展名,如果为允许列表,返回false, 否则true
return !isAllow;
}
/**
* 断言是否文件流可用
* @throws IOException
*/
private void assertValid() throws IOException {
if(! isUploaded()) {
throw new IOException(StrUtil.format("File [{}] upload fail", getFileName()));
}
}
// ---------------------------------------------------------------------------- Private method end
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet/multipart/UploadFileHeader.java | package ai.yue.library.web.util.servlet.multipart;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
/**
* 上传的文件的头部信息<br>
* 源自 hutool-extra
*
* @author ylyue
* @since 2019年8月14日
*/
public class UploadFileHeader {
// String dataHeader;
String formFieldName;
String formFileName;
String path;
String fileName;
boolean isFile;
String contentType;
String mimeType;
String mimeSubtype;
String contentDisposition;
UploadFileHeader(String dataHeader) {
processHeaderString(dataHeader);
}
// ---------------------------------------------------------------- public interface
/**
* @return <code>true</code> if uploaded data are correctly marked as a file. This is true if header contains string 'filename'.
*/
public boolean isFile() {
return isFile;
}
/**
* @return form field name.
*/
public String getFormFieldName() {
return formFieldName;
}
/**
* @return complete file name as specified at client side.
*/
public String getFormFileName() {
return formFileName;
}
/**
* @return file name (base name and extension, without full path data).
*/
public String getFileName() {
return fileName;
}
/**
* @return uploaded content type. It is usually in the following form:<br>
* mime_type/mime_subtype.
*
* @see #getMimeType()
* @see #getMimeSubtype()
*/
public String getContentType() {
return contentType;
}
/**
* @return file types MIME.
*/
public String getMimeType() {
return mimeType;
}
/**
* @return file sub type MIME.
*/
public String getMimeSubtype() {
return mimeSubtype;
}
/**
* @return content disposition. Usually it is 'form-data'.
*/
public String getContentDisposition() {
return contentDisposition;
}
// ---------------------------------------------------------------- Private Method
/**
* 获得头信息字符串字符串中指定的值
*
* @param dataHeader 头信息
* @param fieldName 字段名
* @return 字段值
*/
private String getDataFieldValue(String dataHeader, String fieldName) {
String value = null;
String token = StrUtil.format("{}=\"", fieldName);
int pos = dataHeader.indexOf(token);
if (pos > 0) {
int start = pos + token.length();
int end = dataHeader.indexOf('"', start);
if ((start > 0) && (end > 0)) {
value = dataHeader.substring(start, end);
}
}
return value;
}
/**
* 头信息中获得content type
*
* @param dataHeader data header string
* @return content type or an empty string if no content type defined
*/
private String getContentType(String dataHeader) {
String token = "Content-Type:";
int start = dataHeader.indexOf(token);
if (start == -1) {
return StrUtil.EMPTY;
}
start += token.length();
return dataHeader.substring(start);
}
private String getContentDisposition(String dataHeader) {
int start = dataHeader.indexOf(':') + 1;
int end = dataHeader.indexOf(';');
return dataHeader.substring(start, end);
}
private String getMimeType(String ContentType) {
int pos = ContentType.indexOf('/');
if (pos == -1) {
return ContentType;
}
return ContentType.substring(1, pos);
}
private String getMimeSubtype(String ContentType) {
int start = ContentType.indexOf('/');
if (start == -1) {
return ContentType;
}
start++;
return ContentType.substring(start);
}
/**
* 处理头字符串,使之转化为字段
* @param dataHeader
*/
private void processHeaderString(String dataHeader) {
isFile = dataHeader.indexOf("filename") > 0;
formFieldName = getDataFieldValue(dataHeader, "name");
if (isFile) {
formFileName = getDataFieldValue(dataHeader, "filename");
if (formFileName == null) {
return;
}
if (formFileName.length() == 0) {
path = StrUtil.EMPTY;
fileName = StrUtil.EMPTY;
}
int ls = FileUtil.lastIndexOfSeparator(formFileName);
if (ls == -1) {
path = StrUtil.EMPTY;
fileName = formFileName;
} else {
path = formFileName.substring(0, ls);
fileName = formFileName.substring(ls);
}
if (fileName.length() > 0) {
this.contentType = getContentType(dataHeader);
mimeType = getMimeType(contentType);
mimeSubtype = getMimeSubtype(contentType);
contentDisposition = getContentDisposition(dataHeader);
}
}
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet/multipart/UploadProperties.java | package ai.yue.library.web.util.servlet.multipart;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
/**
* 上传文件设定属性<br>
* 源自 hutool-extra
*
* @author ylyue
* @since 2019年8月14日
*/
@Data
@ConfigurationProperties("yue.servlet.upload")
public class UploadProperties {
/**
* 最大文件大小
* <p>
* 默认:-1(无限制)
*/
protected Integer maxFileSize = -1;
/**
* 文件保存到内存的边界,如果文件大小小于这个边界,将保存于内存中,否则保存至临时目录中
* <p>
* 默认:8192(8GB)
*/
protected Integer memoryThreshold = 8192;
/**
* 临时文件目录,上传文件的临时目录,若为空,使用系统目录
*/
protected String tmpUploadPath;
/**
* 文件扩展名限定,禁止列表还是允许列表取决于{@link #isAllowFileExts}
*/
protected List<String> fileExts;
/**
* 扩展名是允许列表还是禁止列表,若true表示只允许列表里的扩展名,否则是禁止列表里的扩展名
*/
protected Boolean isAllowFileExts = true;
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/util/servlet/multipart/package-info.java | /**
* Servlet相关操作支持
*
* @author ylyue
* @since 2019年10月18日
*/
package ai.yue.library.web.util.servlet.multipart; |
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/vo/CaptchaVO.java | package ai.yue.library.web.vo;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import ai.yue.library.web.util.CaptchaUtils;
import ai.yue.library.web.util.servlet.ServletUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 图片验证码VO,可直接将图片验证码写入响应结果中
*
* @author ylyue
* @since 2018年7月23日
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CaptchaVO {
/** 验证码 */
String captcha;
/** 验证码图片 */
BufferedImage captchaImage;
/**
* {@linkplain #captcha} set session
* <p>{@linkplain #captchaImage} write response
* <p>将验证码设置到session
* <p>将验证码图片写入response,并设置ContentType为image/png
*/
public void writeResponseAndSetSession() {
HttpSession httpSession = ServletUtils.getSession();
HttpServletResponse response = ServletUtils.getResponse();
httpSession.setAttribute(CaptchaUtils.CAPTCHA_KEY, captcha);
response.setContentType("image/png");
OutputStream output;
try {
output = response.getOutputStream();
// 响应结束时servlet会自动将output关闭
ImageIO.write(captchaImage, "png", output);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
0 | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web/2.1.0/ai/yue/library/web/vo/package-info.java | /**
* VO定义
*
* @author ylyue
* @since 2019年10月13日
*/
package ai.yue.library.web.vo; |
0 | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc/package-info.java | /**
* yue-library是一个基于SpringBoot封装的增强库,内置丰富的JDK工具,自动装配了一系列的基础Bean与环境配置项,可用于快速构建SpringCloud项目,让微服务变得更简单。
*
* @author ylyue
* @since 2019年10月13日
*/
package ai.yue.library.web.grpc; |
0 | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc/config/WebGrpcAutoConfig.java | package ai.yue.library.web.grpc.config;
import ai.yue.library.web.grpc.config.exception.ResultExceptionHandler;
import ai.yue.library.web.grpc.config.properties.WebProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* web bean 自动配置
*
* @author ylyue
* @since 2018年11月26日
*/
@Slf4j
@Configuration
@Import({ResultExceptionHandler.class})
@EnableConfigurationProperties({WebProperties.class})
public class WebGrpcAutoConfig {
@Autowired
WebProperties webProperties;
// CorsConfig-跨域
// @Bean
// @ConditionalOnMissingBean
// @ConditionalOnProperty(prefix = "yue.cors", name = "allow", havingValue = "true", matchIfMissing = true)
// public CorsFilter corsFilter(CorsProperties corsProperties) {
// final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// final CorsConfiguration config = new CorsConfiguration();
//
// config.setAllowCredentials(true);
// config.setAllowedHeaders(Arrays.asList("*"));
// config.setAllowedMethods(Arrays.asList("*"));
// config.setAllowedOriginPatterns(Arrays.asList("*"));
// config.setMaxAge(3600L);
//
// // 设置response允许暴露的Headers
// List<String> exposedHeaders = corsProperties.getExposedHeaders();
// if (exposedHeaders != null) {
// config.setExposedHeaders(exposedHeaders);
// } else {
// config.addExposedHeader("token");
// }
//
// source.registerCorsConfiguration("/**", config);
//
// log.info("【初始化配置-跨域】默认配置为true,当前环境为true:默认任何情况下都允许跨域访问 ... 已初始化完毕。");
// return new CorsFilter(source);
// }
}
|
0 | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc/config/package-info.java | /**
* web配置包,提供自动配置项支持与增强
*
* @author ylyue
* @since 2019年9月16日
*/
package ai.yue.library.web.grpc.config; |
0 | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc/config | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc/config/exception/ResultExceptionHandler.java | package ai.yue.library.web.grpc.config.exception;
import ai.yue.library.base.convert.Convert;
import ai.yue.library.base.exception.*;
import ai.yue.library.base.util.ExceptionUtils;
import ai.yue.library.base.view.R;
import ai.yue.library.base.view.Result;
import cn.hutool.core.convert.ConvertException;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.advice.GrpcAdvice;
import net.devh.boot.grpc.server.advice.GrpcExceptionHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import javax.validation.Valid;
import java.util.List;
/**
* <h2>全局统一异常处理</h2>
* <b>统一异常响应体使用HTTP状态码与GRPC状态码职责对照:</b>
* <br><br>
* <table>
* <thead>
* <tr>
* <th>HTTP状态码</th>
* <th>GRPC状态码</th>
* <th>异常范围</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>4xx</td>
* <td>3 INVALID_ARGUMENT</td>
* <td>客户端错误</td>
* </tr>
* <tr>
* <td>5xx</td>
* <td>13 INTERNAL</td>
* <td>服务端异常</td>
* </tr>
* <tr>
* <td>600</td>
* <td>12 UNIMPLEMENTED</td>
* <td>业务提示</td>
* </tr>
* </tbody>
* </table>
*
* @author ylyue
* @since 2022年5月20日
*/
@Slf4j
@GrpcAdvice
@ConditionalOnProperty(prefix = "yue.exception-handler", name = "enabled", havingValue = "true", matchIfMissing = true)
public class ResultExceptionHandler {
// RESTful 异常拦截
/**
* 拦截所有未处理异常-13 INTERNAL
*
* @param e 异常
* @return 结果
*/
@GrpcExceptionHandler(Exception.class)
public synchronized Status exceptionHandler(Exception e) {
Status status = Status.INTERNAL;
ExceptionUtils.printException(e);
return status.withDescription(R.getResult(e).castToJSONString());
}
/**
* 异常结果处理-synchronized
*
* @param e 结果异常
* @return 结果
*/
@GrpcExceptionHandler(ResultException.class)
public synchronized Status resultExceptionHandler(ResultException e) {
var result = e.getResult();
log.error(result.toString());
ExceptionUtils.printException(e);
Integer code = result.getCode();
Status status = null;
if (code >= 400 && code < 500) {
// 400客户端错误-grpc code 3
status = Status.INVALID_ARGUMENT;
} else if (code >= 500 && code < 600) {
// 500服务端错误-grpc code 13
status = Status.INTERNAL;
} else if (code == 600) {
// 600业务提示-grpc code 12
status = Status.UNIMPLEMENTED;
} else {
// 错误的使用RESTful code
status = Status.INTERNAL;
String dataPrompt = StrUtil.format("错误的使用RESTful code:4xx客户端错误、5xx服务端错误、600业务提示,当前code码为{},不应该在异常响应中出现,请排查。", code);
result = R.internalServerError(dataPrompt);
}
return status.withDescription(result.castToJSONString());
}
/**
* 拦截登录异常(User)
* <p>Grpc状态码:3 INVALID_ARGUMENT</p>
* <p>Http状态码:401</p>
*
* @param e 登录异常
* @return 结果
*/
@GrpcExceptionHandler(LoginException.class)
public Status loginExceptionHandler(LoginException e) {
ExceptionUtils.printException(e);
Status status = Status.INVALID_ARGUMENT;
return status.withDescription(R.unauthorized().castToJSONString());
}
/**
* 非法请求异常拦截
* <p>Grpc状态码:3 INVALID_ARGUMENT</p>
* <p>Http状态码:402</p>
*
* @param e 非法请求异常
* @return 结果
*/
@GrpcExceptionHandler(AttackException.class)
public Status attackExceptionHandler(AttackException e) {
ExceptionUtils.printException(e);
Status status = Status.INVALID_ARGUMENT;
return status.withDescription(R.attack(e.getMessage()).castToJSONString());
}
/**
* 无权限异常访问处理
* <p>Grpc状态码:3 INVALID_ARGUMENT</p>
* <p>Http状态码:403</p>
*
* @param e 无权限异常
* @return 结果
*/
@GrpcExceptionHandler(ForbiddenException.class)
public Status forbiddenExceptionHandler(ForbiddenException e) {
ExceptionUtils.printException(e);
Status status = Status.INVALID_ARGUMENT;
return status.withDescription(R.forbidden().castToJSONString());
}
/**
* 拦截API接口版本弃用异常
* <p>Grpc状态码:3 INVALID_ARGUMENT</p>
* <p>Http状态码:410</p>
*
* @param e API接口版本弃用异常
* @return 结果
*/
@GrpcExceptionHandler(ApiVersionDeprecatedException.class)
public Status apiVersionDeprecatedExceptionHandler(ApiVersionDeprecatedException e) {
ExceptionUtils.printException(e);
Status status = Status.INVALID_ARGUMENT;
return status.withDescription(R.gone().castToJSONString());
}
/**
* 参数效验为空统一处理
* <p>Grpc状态码:3 INVALID_ARGUMENT</p>
* <p>Http状态码:432</p>
*
* @return 结果
*/
@GrpcExceptionHandler(ParamVoidException.class)
public Status paramVoidExceptionHandler() {
Status status = Status.INVALID_ARGUMENT;
return status.withDescription(R.paramVoid().castToJSONString());
}
/**
* 参数效验未通过统一处理
* <p>Grpc状态码:3 INVALID_ARGUMENT</p>
* <p>Http状态码:433</p>
*
* @param e 参数校验未通过异常
* @return 结果
*/
@GrpcExceptionHandler(ParamException.class)
public Status paramExceptionHandler(ParamException e) {
ExceptionUtils.printException(e);
Status status = Status.INVALID_ARGUMENT;
return status.withDescription(R.paramCheckNotPass(e.getMessage()).castToJSONString());
}
/**
* {@linkplain Valid} 验证异常统一处理
* <p>Grpc状态码:3 INVALID_ARGUMENT</p>
* <p>Http状态码:433</p>
*
* @param e 验证异常
* @return 结果
*/
@GrpcExceptionHandler(BindException.class)
public Status bindExceptionHandler(BindException e) {
List<ObjectError> errors = e.getAllErrors();
JSONObject paramHint = new JSONObject();
errors.forEach(error -> {
String str = StrUtil.subAfter(error.getArguments()[0].toString(), "[", true);
String key = str.substring(0, str.length() - 1);
String msg = error.getDefaultMessage();
paramHint.put(key, msg);
Console.error(key + " " + msg);
});
Status status = Status.INVALID_ARGUMENT;
return status.withDescription(R.paramCheckNotPass(paramHint).castToJSONString());
}
/**
* 验证异常统一处理
* <p>Grpc状态码:3 INVALID_ARGUMENT</p>
* <p>Http状态码:433</p>
*
* @param e 验证异常
* @return 结果
*/
@GrpcExceptionHandler(ValidateException.class)
public Status validateExceptionHandler(ValidateException e) {
ExceptionUtils.printException(e);
Result<?> result = null;
try {
result = R.paramCheckNotPass(Convert.toJSONArray(e.getMessage()));
} catch (Exception exception) {
result = R.paramCheckNotPass(e.getMessage());
}
Status status = Status.INVALID_ARGUMENT;
return status.withDescription(result.castToJSONString());
}
/**
* DB异常统一处理
* <p>Grpc状态码:13 INTERNAL</p>
* <p>Http状态码:506</p>
*
* @param e DB异常
* @return 结果
*/
@GrpcExceptionHandler(DbException.class)
public Status dbExceptionHandler(DbException e) {
e.printStackTrace();
Result<?> result = null;
if (e.isShowMsg()) {
result = R.dbError(e.getMessage());
} else {
result = R.dbError();
}
Status status = Status.INTERNAL;
return status.withDescription(result.castToJSONString());
}
/**
* 服务降级
* <p>Grpc状态码:13 INTERNAL</p>
* <p>Http状态码:507</p>
*
* @param e 服务降级异常
* @return 结果
*/
@GrpcExceptionHandler(ClientFallbackException.class)
public Status clientFallbackExceptionHandler(ClientFallbackException e) {
ExceptionUtils.printException(e);
Status status = Status.INTERNAL;
return status.withDescription(R.clientFallback().castToJSONString());
}
/**
* 服务降级
* <p>Grpc状态码:13 INTERNAL</p>
* <p>Http状态码:507</p>
*
* @param e grpc请求异常
* @return 结果
*/
@GrpcExceptionHandler(StatusRuntimeException.class)
public Status statusRuntimeExceptionHandler(StatusRuntimeException e) {
ExceptionUtils.printException(e);
Status status = Status.INTERNAL;
return status.withDescription(R.clientFallback().castToJSONString());
}
/**
* 类型转换异常统一处理
* <p>Grpc状态码:13 INTERNAL</p>
* <p>Http状态码:509</p>
*
* @param e 转换异常
* @return 结果
*/
@GrpcExceptionHandler(ConvertException.class)
public Status convertExceptionHandler(ConvertException e) {
log.error("【类型转换异常】转换类型失败,错误信息如下:{}", e.getMessage());
ExceptionUtils.printException(e);
Status status = Status.INTERNAL;
return status.withDescription(R.typeConvertError(e.getMessage()).castToJSONString());
}
// DuplicateKeyException Status.INVALID_ARGUMENT
// IllegalArgumentException Status.INVALID_ARGUMENT
}
|
0 | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc/config | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc/config/exception/package-info.java | /**
* 全局统一异常处理
*
* @author ylyue
* @since 2019年10月13日
*/
package ai.yue.library.web.grpc.config.exception; |
0 | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc/config | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc/config/properties/WebProperties.java | package ai.yue.library.web.grpc.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Web自动配置属性
*
* @author ylyue
* @since 2020年4月6日
*/
@Data
@ConfigurationProperties(WebProperties.PREFIX)
public class WebProperties {
/**
* Prefix of {@link WebProperties}.
*/
public static final String PREFIX = "yue.web-grpc";
}
|
0 | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc/util/ProtoUtils.java | package ai.yue.library.web.grpc.util;
import ai.yue.library.base.convert.Convert;
import ai.yue.library.data.jdbc.ipo.PageIPO;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.protobuf.*;
import com.google.protobuf.util.JsonFormat;
import lombok.SneakyThrows;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* <b>Protobuf工具类</b>
* <p>实现Proto、Bean、Json之间的转换</p>
*
* @author ylyue
* @since 2022/5/19
*/
public class ProtoUtils extends Convert {
/**
* Protobuf反序列化解析器
* <p>用于将proto3 json解析为protobuf message</p>
* <p>支持配置:忽略未知字段、添加多个不同的TypeRegistry用来处理Any类型</p>
*/
public static JsonFormat.Parser parser = JsonFormat.parser().ignoringUnknownFields();
public static JsonFormat.Printer printer = JsonFormat.printer();
private static List<Descriptors.Descriptor> messageTypes = new ArrayList<>();
// ============= 注册Any转换类型 =============
/**
* 注册 {@linkplain Any} 类型转换时需要的Protobuf类型描述
*
* @param descriptors Protobuf类型描述
*/
public static void registerType(Descriptors.Descriptor... descriptors) {
for (Descriptors.Descriptor descriptor : descriptors) {
messageTypes.add(descriptor);
}
TypeRegistry typeRegistry = TypeRegistry.newBuilder().add(messageTypes).build();
parser = parser.usingTypeRegistry(typeRegistry);
printer = printer.usingTypeRegistry(typeRegistry);
}
/**
* 注册 {@linkplain Any} 类型转换时需要的Protobuf类型描述
*
* @param registerClasss protobuf message class
*/
public static <T extends GeneratedMessageV3> void registerType(Class<T>... registerClasss) {
List<Descriptors.Descriptor> descriptors = new ArrayList<>();
for (Class<T> registryClass : registerClasss) {
Descriptors.Descriptor descriptor = ReflectUtil.invokeStatic(ReflectUtil.getPublicMethod(registryClass, "getDescriptor"));
descriptors.add(descriptor);
}
registerType(ArrayUtil.toArray(descriptors, Descriptors.Descriptor.class));
}
// ============= 转换 =============
public static JSONObject toJSONObject(MessageOrBuilder message) {
return JSONObject.parseObject(toJsonString(message));
}
public static PageIPO toPageIPO(MessageOrBuilder message) {
return PageIPO.parsePageIPO(toJSONObject(message));
}
// ============= 序列化 =============
/**
* 转换为Json字符串
*
* @param message protobuf message
* @return Json字符串
*/
@SneakyThrows
@SuppressWarnings("all")
public static String toJsonString(MessageOrBuilder message) {
return printer.print(message);
}
/**
* 转换为Json字符串
* <p>输出null值为默认value</p>
*
* @param message protobuf message
* @return Json字符串
*/
@SneakyThrows
@SuppressWarnings("all")
public static String toJsonStringIncludingDefaultValue(MessageOrBuilder message) {
return printer.includingDefaultValueFields().print(message);
}
// ============= 反序列化 =============
private static void mergeObject(Object jsonOrJavaBean, Message.Builder builder) {
merge(JSONObject.toJSONString(jsonOrJavaBean, SerializerFeature.WriteDateUseDateFormat), builder);
}
/**
* json字符串对象合并到protobuf message
*
* @param json json字符串
* @param builder protobuf message
*/
public static void merge(String json, Message.Builder builder) {
try {
parser.merge(json, builder);
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
/**
* json对象合并到protobuf message
*
* @param json json对象
* @param builder protobuf message
*/
public static void merge(Map json, Message.Builder builder) {
mergeObject(json, builder);
}
/**
* JavaBean合并到protobuf message
*
* @param javaBean JavaBean
* @param builder protobuf message
*/
public static void merge(Object javaBean, Message.Builder builder) {
mergeObject(javaBean, builder);
}
/**
* json字符串对象转换为protobuf message
*
* @param json json字符串
* @param builderClass protobuf message class
* @return protobuf message builder对象
*/
@SneakyThrows
@SuppressWarnings("all")
public static <T extends Message.Builder> T toBuilder(String json, Class<T> builderClass) {
Message.Builder builder = ReflectUtil.newInstance(builderClass);
merge(json, builder);
return (T) builder;
}
/**
* json对象转换为protobuf message
*
* @param json json对象
* @param builderClass protobuf message class
* @return protobuf message builder对象
*/
@SneakyThrows
@SuppressWarnings("all")
public static <T extends Message.Builder> T toBuilder(Map json, Class<T> builderClass) {
Message.Builder builder = ReflectUtil.newInstance(builderClass);
mergeObject(json, builder);
return (T) builder;
}
/**
* JavaBean转换为protobuf message
*
* @param javaBean JavaBean
* @param builderClass protobuf message class
* @return protobuf message builder对象
*/
@SneakyThrows
@SuppressWarnings("all")
public static <T extends Message.Builder> T toBuilder(Object javaBean, Class<T> builderClass) {
Message.Builder builder = ReflectUtil.newInstance(builderClass);
mergeObject(javaBean, builder);
return (T) builder;
}
}
|
0 | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc | java-sources/ai/ylyue/yue-library-web-grpc/j11.2.6.1/ai/yue/library/web/grpc/util/package-info.java | /**
* 提供各种工具方法,按照归类入口为XXXUtils,如字符串工具、Spring上下文工具等
*
* @author ylyue
* @since 2019年10月13日
*/
package ai.yue.library.web.grpc.util; |
0 | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/package-info.java | /**
* yue-library为webflux提供的封装模块
*
* @author ylyue
* @since 2019年10月13日
*/
package ai.yue.library.webflux; |
0 | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/config/WebFluxAutoConfig.java | package ai.yue.library.webflux.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import ai.yue.library.webflux.config.handler.ExceptionHandlerConfig;
import ai.yue.library.webflux.env.WebFluxEnv;
/**
* webflux bean 自动配置
*
* @author ylyue
* @since 2018年11月26日
*/
@Configuration
@Import({ WebFluxRegistrationsConfig.class, WebFluxEnv.class, ExceptionHandlerConfig.class })
public class WebFluxAutoConfig {
}
|
0 | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/config/WebFluxRegistrationsConfig.java | package ai.yue.library.webflux.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.reactive.WebFluxRegistrations;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
import ai.yue.library.base.annotation.api.version.ApiVersionProperties;
import ai.yue.library.webflux.config.api.version.ApiVersionRequestMappingHandlerMapping;
import lombok.extern.slf4j.Slf4j;
/**
* @author ylyue
* @since 2020年2月27日
*/
@Slf4j
@Configuration
@EnableConfigurationProperties(ApiVersionProperties.class)
public class WebFluxRegistrationsConfig implements WebFluxRegistrations {
@Autowired
private ApiVersionProperties apiVersionProperties;
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
if (!apiVersionProperties.isEnabled()) {
return WebFluxRegistrations.super.getRequestMappingHandlerMapping();
}
log.info("【初始化配置-ApiVersionRequestMappingHandlerMapping】默认配置为true,当前环境为true:Restful API接口版本控制,执行初始化 ...");
return new ApiVersionRequestMappingHandlerMapping(apiVersionProperties);
}
}
|
0 | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/config/package-info.java | /**
* webflux配置包,提供自动配置项支持与增强
*
* @author ylyue
* @since 2019年9月16日
*/
package ai.yue.library.webflux.config; |
0 | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/config/api | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/config/api/version/ApiVersionRequestCondition.java | package ai.yue.library.webflux.config.api.version;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.reactive.result.condition.RequestCondition;
import org.springframework.web.server.ServerWebExchange;
import ai.yue.library.base.annotation.api.version.ApiVersion;
import ai.yue.library.base.annotation.api.version.ApiVersionProperties;
import ai.yue.library.base.exception.ApiVersionDeprecatedException;
import ai.yue.library.base.util.StringUtils;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @author ylyue
* @since 2020年2月26日
*/
@Data
@AllArgsConstructor
public class ApiVersionRequestCondition implements RequestCondition<ApiVersionRequestCondition> {
private ApiVersion apiVersion;
private ApiVersionProperties apiVersionProperties;
/**
* {@link RequestMapping} 版本占位符索引
*/
private Integer versionPlaceholderIndex;
@Override
public ApiVersionRequestCondition combine(ApiVersionRequestCondition apiVersionRequestCondition) {
// 最近优先原则:在方法上的 {@link ApiVersion} 可覆盖在类上面的 {@link ApiVersion}
return new ApiVersionRequestCondition(apiVersionRequestCondition.getApiVersion(), apiVersionRequestCondition.getApiVersionProperties(), apiVersionRequestCondition.getVersionPlaceholderIndex());
}
@Override
public ApiVersionRequestCondition getMatchingCondition(ServerWebExchange exchange) {
// 校验请求url中是否包含版本信息
ServerHttpRequest serverHttpRequest = exchange.getRequest();
String requestURI = serverHttpRequest.getURI().getPath();
String[] versionPaths = StringUtils.split(requestURI, "/");
double pathVersion = Double.valueOf(versionPaths[versionPlaceholderIndex].substring(1));
// 如果当前url中传递的版本信息高于(或等于)申明(或默认)版本,则用url的版本
double apiVersionValue = this.getApiVersion().value();
if (pathVersion >= apiVersionValue) {
double minimumVersion = apiVersionProperties.getMinimumVersion();
if ((this.getApiVersion().deprecated() || minimumVersion >= pathVersion) && pathVersion == apiVersionValue) {
throw new ApiVersionDeprecatedException(StrUtil.format("客户端调用弃用版本API接口,requestURI:{}", requestURI));
} else if (this.getApiVersion().deprecated()) {
return null;
}
return this;
}
return null;
}
@Override
public int compareTo(ApiVersionRequestCondition apiVersionRequestCondition, ServerWebExchange exchange) {
// 当出现多个符合匹配条件的ApiVersionCondition,优先匹配版本号较大的
return NumberUtil.compare(apiVersionRequestCondition.getApiVersion().value(), getApiVersion().value());
}
}
|
0 | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/config/api | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/config/api/version/ApiVersionRequestMappingHandlerMapping.java | package ai.yue.library.webflux.config.api.version;
import java.lang.reflect.Method;
import java.util.Objects;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.reactive.result.condition.RequestCondition;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
import ai.yue.library.base.annotation.api.version.ApiVersion;
import ai.yue.library.base.annotation.api.version.ApiVersionProperties;
import ai.yue.library.base.util.StringUtils;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
/**
* @author ylyue
* @since 2020年2月27日
*/
@AllArgsConstructor
public class ApiVersionRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
private ApiVersionProperties apiVersionProperties;
@Override
protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
// 扫描类或接口上的 {@link ApiVersion}
ApiVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
return createRequestCondition(apiVersion, handlerType);
}
@Override
protected RequestCondition<?> getCustomMethodCondition(Method method) {
// 扫描方法上的 {@link ApiVersion}
ApiVersion apiVersion = AnnotationUtils.findAnnotation(method, ApiVersion.class);
return createRequestCondition(apiVersion, method.getDeclaringClass());
}
private RequestCondition<ApiVersionRequestCondition> createRequestCondition(ApiVersion apiVersion, Class<?> handlerType) {
// 1. 确认是否进行版本控制-ApiVersion注解不为空
if (Objects.isNull(apiVersion)) {
return null;
}
// 2. 确认是否进行版本控制-RequestMapping注解包含版本占位符
RequestMapping requestMapping = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class);
if (requestMapping == null) {
return null;
}
String[] requestMappingValues = requestMapping.value();
if (StrUtil.isAllEmpty(requestMappingValues) || !requestMappingValues[0].contains(apiVersionProperties.getVersionPlaceholder())) {
return null;
}
// 3. 解析版本占位符索引位置
String[] versionPlaceholderValues = StringUtils.split(requestMappingValues[0], "/");
Integer index = null;
for (int i = 0; i < versionPlaceholderValues.length; i++) {
if (StringUtils.equals(versionPlaceholderValues[i], apiVersionProperties.getVersionPlaceholder())) {
index = i;
break;
}
}
// 4. 确认是否进行版本控制-占位符索引确认
if (index == null) {
return null;
}
// 5. 确认是否满足最低版本(v1)要求
double value = apiVersion.value();
Assert.isTrue(value >= 1, "Api Version Must be greater than or equal to 1");
// 6. 创建 RequestCondition
return new ApiVersionRequestCondition(apiVersion, apiVersionProperties, index);
}
}
|
0 | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/config | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/config/handler/ExceptionHandlerConfig.java | package ai.yue.library.webflux.config.handler;
import java.io.IOException;
import java.util.List;
import javax.validation.Valid;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import ai.yue.library.base.config.handler.AbstractExceptionHandler;
import ai.yue.library.base.exception.AuthorizeException;
import ai.yue.library.base.exception.ParamDecryptException;
import ai.yue.library.base.exception.ParamException;
import ai.yue.library.base.exception.ParamVoidException;
import ai.yue.library.base.exception.ResultException;
import ai.yue.library.base.util.ExceptionUtils;
import ai.yue.library.base.view.Result;
import ai.yue.library.base.view.ResultInfo;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
/**
* 全局统一异常处理
*
* @author ylyue
* @since 2017年10月8日
*/
@Slf4j
@ControllerAdvice
@ConditionalOnProperty(prefix = "yue.exception-handler", name = "enabled", havingValue = "true", matchIfMissing = true)
public class ExceptionHandlerConfig extends AbstractExceptionHandler {
// Restful 异常拦截
/**
* 异常结果处理-synchronized
*
* @param e 结果异常
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(ResultException.class)
public synchronized Result<?> resultExceptionHandler(ResultException e) {
var result = e.getResult();
// ServletUtils.getResponse().setStatus(result.getCode());
log.error(result.toString());
ExceptionUtils.printException(e);
return result;
}
/**
* 参数效验为空统一处理-432
*
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(ParamVoidException.class)
public Result<?> paramVoidExceptionHandler() {
// ServletUtils.getResponse().setStatus(432);
return ResultInfo.paramVoid();
}
/**
* 参数效验未通过统一处理-433
*
* @param e 参数校验未通过异常
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(ParamException.class)
public Result<?> paramExceptionHandler(ParamException e) {
// ServletUtils.getResponse().setStatus(433);
ExceptionUtils.printException(e);
return ResultInfo.paramCheckNotPass(e.getMessage());
}
/**
* {@linkplain Valid} 验证异常统一处理-433
*
* @param e 验证异常
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(BindException.class)
public Result<?> bindExceptionHandler(BindException e) {
// ServletUtils.getResponse().setStatus(433);
// String uri = ServletUtils.getRequest().getRequestURI();
// Console.error("uri={}", uri);
List<ObjectError> errors = e.getAllErrors();
JSONObject paramHint = new JSONObject();
errors.forEach(error -> {
String str = StrUtil.subAfter(error.getArguments()[0].toString(), "[", true);
String key = str.substring(0, str.length() - 1);
String msg = error.getDefaultMessage();
paramHint.put(key, msg);
Console.error(key + " " + msg);
});
return ResultInfo.paramCheckNotPass(paramHint.toString());
}
/**
* 验证异常统一处理-433
*
* @param e 验证异常
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(ValidateException.class)
public Result<?> validateExceptionHandler(ValidateException e) {
// ServletUtils.getResponse().setStatus(433);
ExceptionUtils.printException(e);
return ResultInfo.paramCheckNotPass(e.getMessage());
}
/**
* 解密异常统一处理-435
*
* @param e 解密异常
* @return 结果
*/
@Override
@ResponseBody
@ExceptionHandler(ParamDecryptException.class)
public Result<?> paramDecryptExceptionHandler(ParamDecryptException e) {
// ServletUtils.getResponse().setStatus(435);
log.error("【解密错误】错误信息如下:{}", e.getMessage());
ExceptionUtils.printException(e);
return ResultInfo.paramDecryptError();
}
// WEB 异常拦截
/**
* 拦截登录异常(Admin)-301
*
* @param e 认证异常
* @throws IOException 重定向失败
*/
@ExceptionHandler(AuthorizeException.class)
public void authorizeExceptionHandler(AuthorizeException e) throws IOException {
ExceptionUtils.printException(e);
log.error("WebFlux 暂不支持异常拦截后重定向操作 ...");
// ServletUtils.getResponse().sendRedirect("");
}
}
|
0 | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/config | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/config/handler/package-info.java | /**
* 全局统一异常处理
*
* @author ylyue
* @since 2019年10月13日
*/
package ai.yue.library.webflux.config.handler; |
0 | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux | java-sources/ai/ylyue/yue-library-webflux/2.1.0/ai/yue/library/webflux/env/WebFluxEnv.java | package ai.yue.library.webflux.env;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import ai.yue.library.base.view.Result;
import ai.yue.library.base.webenv.WebEnv;
import lombok.extern.slf4j.Slf4j;
/**
* @author ylyue
* @since 2020年4月16日
*/
@Slf4j
@Component
public class WebFluxEnv implements WebEnv {
@Override
public void resultResponse(Result<?> result) {
log.error("无效的Result.response()方法,webflux暂未实现。");
// ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8).syncBody(result);
}
@Override
public JSONObject getParam() {
// TODO webflux方案实现
log.error("无效的ParamUtils.getParam()方法,webflux暂未实现。");
return null;
}
@Override
public <T> T getParam(Class<T> clazz) {
// TODO webflux方案实现
log.error("无效的ParamUtils.getParam()方法,webflux暂未实现。");
return null;
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/Main.java | package al.aldi.sprova4j;
import al.aldi.sprova4j.models.*;
import al.aldi.sprova4j.utils.SprovaObjectFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static Project project;
private static Cycle cycle;
private static SprovaApiClient apiClient;
private static Execution exec;
public static void main(String[] args) {
logger.info("Sprova4J running");
logger.info("Implementation still missing");
SprovaConnector conn = null;
try {
conn = new SprovaConnector("http://localhost:8181/", "admin", "admin");
apiClient = conn.getApiClient();
project = apiClient.getProject("5ae5bda75b435f3d2b999c79");
cycle = project.getCycle(new SprovaObjectFilter().add("title", "Release 6.3"));
final List<TestCase> testCases = project.getTestCases();
apiClient.filterProjects(SprovaObjectFilter.empty());
List<TestSet> testSets = cycle.getTestSets();
List<TestCase> testCases1 = cycle.getTestCases();
SprovaObjectFilter filter = new SprovaObjectFilter().add("jiraId", "SYSTEST-1");
TestCase test1 = cycle.findTestCase(filter);
exec = test1.startExecution();
TestSet oneTestSet = cycle.findOneTestSet(new SprovaObjectFilter().add("title", "import"));
TestSetExecution execution = oneTestSet.createExecution();
Execution execution1 = null;
while((execution1 = execution.getNextPending()) != null){
execution1.passTest();
}
} catch (Exception e) {
System.err.println("Tried to connect to Sprova server but got " + e.getMessage());
}
logger.info("Exiting");
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/SprovaApiClient.java | package al.aldi.sprova4j;
import al.aldi.sprova4j.exceptions.CycleException;
import al.aldi.sprova4j.exceptions.ExecutionException;
import al.aldi.sprova4j.exceptions.SprovaClientException;
import al.aldi.sprova4j.exceptions.TestCaseException;
import al.aldi.sprova4j.exceptions.TestSetException;
import al.aldi.sprova4j.models.*;
import al.aldi.sprova4j.models.aux.MongoDbInsertResponse;
import al.aldi.sprova4j.models.aux.TestSetExecutionResponse;
import al.aldi.sprova4j.models.enums.ExecutionStatus;
import al.aldi.sprova4j.models.enums.ExecutionStepStatus;
import al.aldi.sprova4j.utils.AuthorizationInterceptor;
import al.aldi.sprova4j.utils.LoggingInterceptor;
import javax.validation.constraints.NotNull;
import static java.lang.String.*;
import al.aldi.sprova4j.utils.SprovaObjectFilter;
import okhttp3.*;
import java.io.IOException;
import java.util.List;
import static al.aldi.sprova4j.utils.ApiUtils.*;
public class SprovaApiClient {
public final String apiUrl;
public final String jwtToken;
private OkHttpClient client;
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
protected SprovaApiClient(@NotNull String apiUrl, @NotNull String jwtToken) throws SprovaClientException {
if (apiUrl == null) {
throw new SprovaClientException("apiUrl cannot be null");
}
if (jwtToken == null) {
throw new SprovaClientException("jwtToken cannot be null");
}
this.apiUrl = apiUrl;
this.jwtToken = jwtToken;
this.client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.addInterceptor(new AuthorizationInterceptor(this.jwtToken))
.build();
}
// ----------------------------------------------------------------------------
// By ID
// ----------------------------------------------------------------------------
/**
* Get project by ID
*
* @param projectId
* @return
*/
public Project getProject(final String projectId) {
try {
Project project = Project.toObject(get(format("%s/%s", API_PROJECTS, projectId)));
project.setClient(this);
return project;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Get test sets by ID
*
* @param testSetId
* @return
*/
public TestSet getTestSet(String testSetId) {
TestSet result = null;
try {
result = TestSet.toObject(get(format("%s/%s", API_TESTSETS, testSetId)));
result.setClient(this);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* Get test case by ID
*
* @param testCaseId
* @return
*/
public TestCase getTestCase(String testCaseId) {
TestCase result = null;
try {
result = TestCase.toObject(get(format("%s/%s", API_TESTCASES, testCaseId)));
result.setClient(this);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* Get test execution by ID
*
* @param id
* @return
*/
public TestSetExecution getTestSetExecution(final String id) {
TestSetExecution result = null;
try {
result = TestSetExecution.toObject(get(format("%s/%s", API_TESTSET_EXECUTIONS, id)));
result.setClient(this);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
// ----------------------------------------------------------------------------
// By SprovaObjectFilter
// ----------------------------------------------------------------------------
/**
* Search in projects
*
* @param jsonFiler
* @return
* @throws CycleException
*/
public List<Project> filterProjects(SprovaObjectFilter jsonFiler) throws CycleException {
List<Project> result = null;
try {
result = Project.toObjects(post(format("%s/%s", API_SEARCH, PROJECTS), jsonFiler.toJson()));
if (result == null) {
throw new CycleException("Project not found => filter: " + jsonFiler);
}
for (Project project : result) {
project.setClient(this);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* Search in cycles
*
* @param jsonFiler
* @return
* @throws CycleException
*/
public List<Cycle> filterCycles(SprovaObjectFilter jsonFiler) throws CycleException {
List<Cycle> result = null;
try {
result = Cycle.toObjects(post(format("%s/%s", API_SEARCH, CYCLES), jsonFiler.toJson()));
if (result == null) {
throw new CycleException("Cycle not found => filter: " + jsonFiler);
}
for (Cycle cycle : result) {
cycle.setClient(this);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* Search in test cases
*
* @param filer
* @return
* @throws TestCaseException
*/
public List<TestCase> filterTestCases(SprovaObjectFilter filer) throws TestCaseException {
List<TestCase> result = null;
try {
String json = filer.toJson();
result = TestCase.toObjects(post(format("%s/%s", API_SEARCH, TESTCASES), json));
if (result == null) {
throw new TestCaseException("Test case not found => filter: " + json);
}
for (TestCase testCase : result) {
testCase.setClient(this);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* Search in test cases
*
* @param filer
* @return
* @throws TestCaseException
*/
public TestCase filterCycleTestCase(final String cycleId, final SprovaObjectFilter filer) throws TestCaseException {
TestCase result = null;
try {
String json = filer.toJson();
result = TestCase.toObject(post(format("%s/%s/%s/%s/%s", API_SEARCH, CYCLES, cycleId, TESTCASES, FIND_ONE), json));
if (result == null) {
throw new TestCaseException("Test case not found => filter: " + json);
}
result.setClient(this);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* Search in test cases
*
* @param filer
* @return
* @throws TestCaseException
*/
public List<TestCase> filterCycleTestCases(final String cycleId, final SprovaObjectFilter filer) throws TestCaseException {
List<TestCase> result = null;
try {
String json = filer.toJson();
result = TestCase.toObjects(post(format("%s/%s/%s/%s/%s", API_SEARCH, CYCLES, cycleId, TESTCASES, FIND), json));
if (result == null) {
throw new TestCaseException("Test case not found => filter: " + json);
}
for (TestCase testCase : result) {
testCase.setClient(this);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* Search in test sets
*
* @param jsonFiler
* @return
* @throws TestCaseException
*/
public List<TestSet> filterTestSets(final SprovaObjectFilter jsonFiler) throws TestCaseException {
List<TestSet> result = null;
try {
result = TestSet.toObjects(post(format("%s/%s", API_SEARCH, TESTSETS), jsonFiler.toJson()));
if (result == null) {
throw new TestCaseException("Test set not found => filter: " + jsonFiler);
}
for (TestSet testSet : result) {
testSet.setClient(this);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
// ----------------------------------------------------------------------------
// TEST SET EXECUTION
// ----------------------------------------------------------------------------
public TestSetExecutionResponse createTestSetExecution(final TestSetExecution testSetExecution) throws TestSetException {
TestSetExecutionResponse result = null;
try {
result = TestSetExecutionResponse.toObject(post(format("%s", API_TESTSET_EXECUTIONS), testSetExecution.toJson()));
if (result == null) {
throw new TestSetException("Could not create new test set execution");
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public Execution getNextPendingExecution(final TestSetExecution testSetExecution) {
Execution result = null;
try {
result = Execution.toObject(get(format("%s/%s/%s", API_TESTSET_EXECUTIONS, testSetExecution._id, NEXT_PENDING)));
if (result != null) {
result.setClient(this);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
// ----------------------------------------------------------------------------
// EXECUTION
// ----------------------------------------------------------------------------
public Execution startExecution(Execution execution) {
MongoDbInsertResponse response;
String jsonString = execution.toJson();
try {
response = MongoDbInsertResponse.toObject(post(API_EXECUTIONS, jsonString));
if (response.ok == 1) {
execution._id = response._id;
} else {
throw new ExecutionException("Could not start execution " + execution._id);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return execution;
}
public Execution resetExecution(Execution execution) {
MongoDbInsertResponse response;
String jsonString = null;
try {
response = MongoDbInsertResponse.toObject(post(API_EXECUTIONS, jsonString));
if (response.ok == 1) {
execution._id = response._id;
} else {
throw new ExecutionException("Could not start execution " + execution._id);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return execution;
}
public boolean passStep(Execution execution, int stepIndex) {
return setStepStatus(execution, stepIndex, ExecutionStepStatus.SUCCESSFUL);
}
public boolean failStep(Execution execution, int stepIndex) {
return setStepStatus(execution, stepIndex, ExecutionStepStatus.FAILED);
}
private boolean setStepStatus(Execution execution, int stepIndex, ExecutionStepStatus status) {
boolean result = false;
String jsonString = status.toJsonObjectString();
try {
MongoDbInsertResponse response = MongoDbInsertResponse.toObject(put(format("%s/%s/%s/%s/status", API_EXECUTIONS, execution._id, STEPS, stepIndex), jsonString));
result = response.ok == 1;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public Execution passExecution(Execution execution) {
return setExecutionStatus(execution, ExecutionStatus.SUCCESSFUL);
}
public Execution failExecution(Execution execution) {
return setExecutionStatus(execution, ExecutionStatus.FAILED);
}
public Execution warnExecution(Execution execution) {
return setExecutionStatus(execution, ExecutionStatus.WARNING);
}
public Execution workingOnExecution(Execution execution) {
return setExecutionStatus(execution, ExecutionStatus.WORKING);
}
public Execution pendExecution(Execution execution) {
return setExecutionStatus(execution, ExecutionStatus.PENDING);
}
private Execution setExecutionStatus(Execution execution, ExecutionStatus status) {
MongoDbInsertResponse response;
String jsonString = status.toJsonObjectString();
try {
response = MongoDbInsertResponse.toObject(put(format("%s/%s/status", API_EXECUTIONS, execution._id), jsonString));
if (response.ok == 1) {
execution._id = response._id;
} else {
throw new ExecutionException("Could not pass execution " + execution._id);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return execution;
}
// ----------------------------------------------------------------------------
// TEST SET EXECUTION
// ----------------------------------------------------------------------------
public List<TestSetExecution> getTestSetExecutionsByTestSetId(String testSetId) {
List<TestSetExecution> result = null;
try {
result = TestSetExecution.toObjects(get(format("%s/%s/%s", API_TESTSETS, testSetId, TESTSET_EXECUTIONS)));
for (TestSetExecution c : result) {
c.setClient(this);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
// ----------------------------------------------------------------------------
// CUSTOM
// ----------------------------------------------------------------------------
public List<TestCase> getCycleTestCases(String cycleId) throws TestCaseException {
List<TestCase> result = null;
try {
result = TestCase.toObjects(get(format("%s/%s/%s", API_CYCLES, cycleId, TESTCASES)));
if (result == null) {
throw new TestCaseException("Test case not found => filter: " + cycleId);
}
for (TestCase testCase : result) {
testCase.setClient(this);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
public String get(String urlSuffix) throws IOException {
final String url = apiUrl + urlSuffix;
Request.Builder builder = getBuilder(url);
Request request = builder.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public String post(final String urlSuffix, String json) throws IOException {
final String url = apiUrl + urlSuffix;
RequestBody body = RequestBody.create(JSON, json);
Request.Builder builder = getBuilder(url).post(body);
Request request = builder.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public String put(final String urlSuffix, String json) throws IOException {
final String url = apiUrl + urlSuffix;
RequestBody body = RequestBody.create(JSON, json);
Request.Builder builder = getBuilder(url).put(body);
Request request = builder.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
private Request.Builder getBuilder(String url) {
Request.Builder result = new Request.Builder().url(url);
return result;
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/SprovaConnector.java | package al.aldi.sprova4j;
import al.aldi.sprova4j.exceptions.SprovaClientException;
import al.aldi.sprova4j.models.aux.AuthenticationRequest;
import al.aldi.sprova4j.models.aux.AuthenticationResponse;
import al.aldi.sprova4j.models.aux.StatusResponse;
import al.aldi.sprova4j.utils.ApiUtils;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class SprovaConnector {
private static final Logger logger = LoggerFactory.getLogger(SprovaConnector.class);
private final String apiAddress;
private final String jwtKey;
private final String username;
private SprovaApiClient apiClient;
public SprovaConnector(String apiAddress, String jwtKey) throws Exception {
this.apiAddress = ApiUtils.sanitizeUrl(apiAddress);
this.jwtKey = jwtKey;
this.username = null;
}
public SprovaConnector(String apiAddress, String username, String password) throws Exception {
this.apiAddress = ApiUtils.sanitizeUrl(apiAddress);
this.username = username;
// authenticate
this.jwtKey = this.authenticate(username, password);
}
/**
* Make sure user is authenticated via JWT token.
*
* @return authentication success
*/
public boolean isAuthenticated() {
boolean result = false;
try {
final String url = apiAddress + ApiUtils.STATUS;
Response response = ApiUtils.GET(url);
StatusResponse status = StatusResponse.toObject(response.body().string());
result = status.success;
} catch (Exception e) {
logger.info("Authentication has failed. You need to re-authenticate!");
}
return result;
}
/**
* Authenticate by user and password in order to get JWT key for further requests.
*
* @param username
* @param password
* @return JWT token
*/
protected String authenticate(final String username, final String password) throws IOException {
String result = null;
String url = this.apiAddress + ApiUtils.AUTHENTICATE;
AuthenticationRequest request = new AuthenticationRequest(username, password);
Response response = ApiUtils.POST(url, request.toJson());
AuthenticationResponse auth = AuthenticationResponse.toObject(response.body().string());
result = auth.token;
return result;
}
/**
* Get or initialize and get client.
*
* @return sprova api client
*/
public SprovaApiClient getApiClient() {
if (this.apiClient == null) {
try {
this.apiClient = new SprovaApiClient(this.apiAddress, this.jwtKey);
} catch (SprovaClientException e) {
e.printStackTrace();
}
}
return this.apiClient;
}
public String getUsername() {
return username;
}
public String getApiAddress() {
return apiAddress;
}
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/SprovaLogger.java | package al.aldi.sprova4j;
/**
* Logs information to the sprova test management server.
* @author Aldi Alimuçaj
*/
public class SprovaLogger {
}
|
0 | java-sources/al/aldi/sprova4j/0.2.1/al/aldi | java-sources/al/aldi/sprova4j/0.2.1/al/aldi/sprova4j/SprovaTest.java | package al.aldi.sprova4j;
public @interface SprovaTest {
/**
* Test case ID.
* Autogenerated Object id ID
* @return
*/
String id();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.